upload-url.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import { z } from 'zod'
  2. /**
  3. * The URLs the app hands out for its own uploads, and nothing else.
  4. *
  5. * Every stored file URL is later turned into a path on disk and read, copied
  6. * or unlinked, so what may be stored is exactly the shape the upload routes
  7. * produce: an organisation id, a category folder and one file name. Anything
  8. * with a slash or a dot pair in the wrong place, another host, or a scheme is
  9. * refused before it reaches the database.
  10. */
  11. export const UPLOAD_CATEGORIES = [
  12. 'vehicles',
  13. 'inventory',
  14. 'services',
  15. 'logos',
  16. 'email-logos',
  17. 'email-images',
  18. 'quotes',
  19. 'portal',
  20. 'tire-hotel',
  21. ] as const
  22. export type UploadCategory = (typeof UPLOAD_CATEGORIES)[number]
  23. const UPLOAD_URL =
  24. /^\/api\/(?:protected\/)?files\/([A-Za-z0-9_-]{1,64})\/([a-z-]{1,32})\/([A-Za-z0-9][A-Za-z0-9._-]{0,200})$/
  25. /**
  26. * The shape files had before uploads were served per organisation: a
  27. * category folder under public/uploads and one file name. Nothing left on
  28. * disk is written this way any more, but records that still carry one are
  29. * sent back whole when their owner edits them, so the shape stays storable.
  30. * There is no organisation in it to check; the path resolver contains it.
  31. */
  32. const LEGACY_UPLOAD_URL = /^\/uploads\/([a-z-]{1,32})\/([A-Za-z0-9][A-Za-z0-9._-]{0,200})$/
  33. export interface UploadUrlParts {
  34. organizationId: string
  35. category: string
  36. file: string
  37. }
  38. /** The parts of one of our upload URLs, or null for anything else. */
  39. export function parseUploadUrl(value: string | null | undefined): UploadUrlParts | null {
  40. const match = value ? UPLOAD_URL.exec(value) : null
  41. if (!match) return null
  42. const [, organizationId, category, file] = match
  43. if (file.includes('..') || !(UPLOAD_CATEGORIES as readonly string[]).includes(category)) {
  44. return null
  45. }
  46. return { organizationId, category, file }
  47. }
  48. /** Whether a value is a file of ours in any of the shapes we have stored. */
  49. export function isStoredUploadUrl(value: string | null | undefined): boolean {
  50. if (!value) return false
  51. if (parseUploadUrl(value)) return true
  52. const legacy = LEGACY_UPLOAD_URL.exec(value)
  53. return !!legacy && !legacy[2].includes('..')
  54. }
  55. /**
  56. * Whether a value is a picture on another site: the address a supplier's
  57. * catalogue gives for a part. It never reaches the disk, only an <img>, so
  58. * the only thing to refuse is a scheme that could run something.
  59. */
  60. export function isRemoteImageUrl(value: string | null | undefined): boolean {
  61. if (!value || value.length > 2000) return false
  62. try {
  63. const url = new URL(value)
  64. return url.protocol === 'https:' || url.protocol === 'http:'
  65. } catch {
  66. return false
  67. }
  68. }
  69. /** Whether a stored URL names one of this organisation's own uploads. */
  70. export function isOwnUploadUrl(value: string | null | undefined, organizationId: string): boolean {
  71. return parseUploadUrl(value)?.organizationId === organizationId
  72. }
  73. /**
  74. * Refuses a URL that is not one of this organisation's uploads. Empty means
  75. * "no file" and passes, since that is how a cleared image is expressed.
  76. */
  77. export function assertOwnUploadUrl(
  78. value: string | null | undefined,
  79. organizationId: string,
  80. what = 'file'
  81. ): void {
  82. if (!value) return
  83. if (!isOwnUploadUrl(value, organizationId)) {
  84. throw new Error(`The ${what} is not an upload of this workshop`)
  85. }
  86. }
  87. /** A zod string that must be one of our upload URLs. */
  88. export const uploadUrlSchema = z
  89. .string()
  90. .max(300)
  91. .refine((value) => isStoredUploadUrl(value), 'Not an upload of this workshop')
  92. /** The same, but an empty string is allowed for "no file". */
  93. export const optionalUploadUrlSchema = z
  94. .string()
  95. .max(300)
  96. .refine((value) => value === '' || isStoredUploadUrl(value), 'Not an upload of this workshop')
  97. /**
  98. * A picture that may be one of our uploads or live on another site. Part
  99. * images are the case: "fetch from supplier" keeps the catalogue's own
  100. * address rather than copying the file, and the record is saved with it.
  101. */
  102. export const imageUrlSchema = z
  103. .string()
  104. .max(2000)
  105. .refine(
  106. (value) => isStoredUploadUrl(value) || isRemoteImageUrl(value),
  107. 'Not an upload of this workshop or a web address'
  108. )
  109. const UPLOAD_PREFIXES = ['/api/protected/files/', '/api/files/']
  110. /**
  111. * Walks a parsed input and refuses any string that names an upload of
  112. * another organisation. The shape checks above say what a URL must look
  113. * like; this says whose it must be, and it runs after every parse that
  114. * stores one, so a copied URL can never point a record at a stranger's file.
  115. */
  116. export function assertOwnUploads(value: unknown, organizationId: string): void {
  117. if (typeof value === 'string') {
  118. if (UPLOAD_PREFIXES.some((prefix) => value.startsWith(prefix))) {
  119. const normalised = value.replace('/api/files/', '/api/protected/files/')
  120. if (!isOwnUploadUrl(normalised, organizationId)) {
  121. throw new Error('A file in this request is not an upload of this workshop')
  122. }
  123. }
  124. return
  125. }
  126. if (Array.isArray(value)) {
  127. for (const item of value) assertOwnUploads(item, organizationId)
  128. return
  129. }
  130. if (value && typeof value === 'object') {
  131. for (const item of Object.values(value as Record<string, unknown>)) {
  132. assertOwnUploads(item, organizationId)
  133. }
  134. }
  135. }
  136. /** The extension a stored file gets, from its validated MIME type, never from its name. */
  137. const EXTENSION_BY_TYPE: Record<string, string> = {
  138. 'image/jpeg': 'jpg',
  139. 'image/png': 'png',
  140. 'image/webp': 'webp',
  141. 'image/avif': 'avif',
  142. 'image/gif': 'gif',
  143. 'application/pdf': 'pdf',
  144. 'text/csv': 'csv',
  145. 'text/plain': 'txt',
  146. 'video/mp4': 'mp4',
  147. 'video/webm': 'webm',
  148. 'video/quicktime': 'mov',
  149. }
  150. export function extensionForType(mimeType: string, fallback = 'bin'): string {
  151. return EXTENSION_BY_TYPE[mimeType.toLowerCase()] ?? fallback
  152. }
  153. /**
  154. * Headers for serving a stored SVG. The file is offered as a download inside
  155. * a sandbox, never rendered in the app's origin, so a script inside it has
  156. * nowhere to run.
  157. */
  158. export function svgDownloadHeaders(cacheControl: string): Record<string, string> {
  159. return {
  160. 'Content-Type': 'image/svg+xml',
  161. 'Content-Disposition': 'attachment',
  162. 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
  163. 'X-Content-Type-Options': 'nosniff',
  164. 'Cache-Control': cacheControl,
  165. }
  166. }