Browse Source

Serve only a shared document's own files on its link (#648)

* Serve only a shared document's own files on its link

The public file route now opens the files the token's document shows the customer (its attachments, inspection photos, status report video) and the workshop's logos, and answers anything else as a missing file. An expired status report's video closes with its page.

* Look a shared file's link up once and ask only about the file requested

The token is resolved once per request for both the expiry check and the file check, and each file is one narrow query on the document instead of a load of all its files. An expired status report's video answers 410 like every other closed link.
Bernt Christian Egeland 6 ngày trước cách đây
mục cha
commit
33bff17a99

+ 13 - 11
e2e/specs/security/files.spec.ts

@@ -242,17 +242,19 @@ test.describe('an SVG', () => {
       '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="owned"</script></svg>'
     )
     try {
-      for (const url of [
-        `/api/protected/files/${organizationId}/logos/${name}`,
-        `/api/public/files/${shareToken}/logos/${name}`,
-      ]) {
-        const response = await page.request.get(url)
-        expect(response.status(), `${url} is served`).toBe(200)
-        const headers = response.headers()
-        expect(headers['content-disposition'], `${url} is a download`).toBe('attachment')
-        expect(headers['content-security-policy'], `${url} is sandboxed`).toContain('sandbox')
-        expect(headers['x-content-type-options']).toBe('nosniff')
-      }
+      const url = `/api/protected/files/${organizationId}/logos/${name}`
+      const response = await page.request.get(url)
+      expect(response.status(), `${url} is served`).toBe(200)
+      const headers = response.headers()
+      expect(headers['content-disposition'], `${url} is a download`).toBe('attachment')
+      expect(headers['content-security-policy'], `${url} is sandboxed`).toContain('sandbox')
+      expect(headers['x-content-type-options']).toBe('nosniff')
+
+      // A share link opens only what its document shows, and this file is
+      // no logo the workshop uses. The public route's own SVG headers are
+      // unit-tested in src/__tests__/lib/shared-files.test.ts.
+      const shared = await page.request.get(`/api/public/files/${shareToken}/logos/${name}`)
+      expect(shared.status(), 'a file the shared document does not show').toBe(404)
     } finally {
       await unlink(uploadDir('logos', name))
     }

+ 238 - 0
e2e/specs/security/shared-files.spec.ts

@@ -0,0 +1,238 @@
+import { randomUUID } from 'node:crypto'
+import { mkdir, rm, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { type APIRequestContext, type Browser, expect, type Page, test } from '@playwright/test'
+import { attach } from '../../support/attachments'
+import {
+  ownerOrganizationId,
+  type PlantedSharedDocuments,
+  plantSharedDocuments,
+  removeSharedDocuments,
+  userIdFor,
+} from '../../support/db'
+import { sharesDiskWithServer, uploadPath } from '../../support/files'
+import { makePdf, TINY_PNG } from '../../support/pdf'
+import {
+  addPart,
+  newWorkOrder,
+  saveWorkOrder,
+  seededVehicleUrl,
+  shareLink,
+} from '../../support/work-order'
+
+/**
+ * What a share link opens on the public file route.
+ *
+ * Every page a customer reaches through a link draws its pictures, videos
+ * and documents through `/api/public/files/<token>/...`. Each one has to
+ * load, on every kind of shared document, for a reader with no session at
+ * all. And a link opens its own document's files only: the token of one job
+ * is no key to the rest of the workshop's uploads, and a file it does not
+ * show answers exactly as a file that does not exist.
+ */
+
+test.describe.configure({ mode: 'serial' })
+
+const stamp = Date.now()
+const PHOTO = `e2e-shared-photo-${stamp}.png`
+const REPORT = `e2e-shared-report-${stamp}.pdf`
+
+let organizationId = ''
+let jobShareUrl = ''
+let planted: PlantedSharedDocuments | null = null
+const plantedFiles: string[] = []
+const plantedUrls: Record<string, string> = {}
+
+/** A file under the workshop's uploads with the URL a row would hold for it. */
+async function plant(folder: string, ext: string, body: Buffer): Promise<string> {
+  const name = `${randomUUID()}.${ext}`
+  const file = uploadPath(organizationId, folder, name)
+  await mkdir(path.dirname(file), { recursive: true })
+  await writeFile(file, body)
+  plantedFiles.push(file)
+  return `/api/protected/files/${organizationId}/${folder}/${name}`
+}
+
+/** The public address a share page gives a stored file under this token. */
+function publicUrl(token: string, storedUrl: string): string {
+  return storedUrl.replace(/^\/api\/protected\/files\/[^/]+\//, `/api/public/files/${token}/`)
+}
+
+/** A browser with nobody signed in, as the customer opens the link. */
+async function customer(browser: Browser) {
+  const context = await browser.newContext({ storageState: { cookies: [], origins: [] } })
+  return { context, page: await context.newPage() }
+}
+
+/** Every public file address the page draws or links to. */
+async function publicFileUrls(page: Page): Promise<string[]> {
+  const urls = await page.evaluate(() =>
+    [...document.querySelectorAll('img[src], video[src], source[src], a[href]')]
+      .map((el) => el.getAttribute('src') ?? el.getAttribute('href') ?? '')
+      .filter((url) => url.startsWith('/api/public/files/'))
+  )
+  return [...new Set(urls)]
+}
+
+/** Every picture from the file route on the page has decoded. */
+async function expectPicturesLoaded(page: Page) {
+  await expect(async () => {
+    const broken = await page.evaluate(() =>
+      [...document.querySelectorAll<HTMLImageElement>('img')]
+        .filter((img) => (img.getAttribute('src') ?? '').startsWith('/api/public/files/'))
+        .filter((img) => !img.complete || img.naturalWidth === 0)
+        .map((img) => img.getAttribute('src'))
+    )
+    expect(broken, 'every picture on the shared page loaded').toEqual([])
+  }).toPass({ timeout: 15_000 })
+}
+
+/** Each address answers with the file, to a client with no cookies. */
+async function expectServed(request: APIRequestContext, urls: string[]) {
+  for (const url of urls) {
+    const response = await request.get(url)
+    expect(response.status(), `${url} is served`).toBe(200)
+    expect(response.headers()['cache-control']).toBe('private, no-store')
+  }
+}
+
+test.beforeAll(async ({ browser }) => {
+  test.setTimeout(180_000)
+  organizationId = await ownerOrganizationId()
+
+  // A job made the way a workshop makes one: a photo and a report on it,
+  // then shared.
+  const page = await browser.newPage({ storageState: 'e2e/.auth/owner.json' })
+  const vehicleUrl = await seededVehicleUrl(page)
+  await newWorkOrder(page, vehicleUrl, `E2E shared files ${stamp}`)
+  await addPart(page, { name: `E2E filter ${stamp}`, quantity: 1, unitPrice: 100 })
+  await saveWorkOrder(page)
+  await attach(page, 'Photos', { name: PHOTO, mimeType: 'image/png', buffer: TINY_PNG })
+  await attach(page, 'Documents', {
+    name: REPORT,
+    mimeType: 'application/pdf',
+    buffer: await makePdf(['E2E SHARED REPORT']),
+  })
+  jobShareUrl = await shareLink(page)
+  await page.close()
+
+  // The other documents a link can lead to, planted with their files when
+  // the suite shares a disk with the server.
+  if (!sharesDiskWithServer()) return
+  const files = {
+    quotePhoto: await plant('quotes', 'png', TINY_PNG),
+    quoteDocument: await plant('quotes', 'pdf', await makePdf(['E2E QUOTE TERMS'])),
+    inspectionPhoto: await plant('inspections', 'png', TINY_PNG),
+    inspectionOverview: await plant('inspections', 'png', TINY_PNG),
+    inspectionHidden: await plant('inspections', 'pdf', await makePdf(['E2E PAPERWORK'])),
+    statusVideo: await plant('services', 'mp4', Buffer.from('e2e video')),
+  }
+  Object.assign(plantedUrls, files)
+  planted = await plantSharedDocuments(
+    organizationId,
+    await userIdFor('demo@torqvoice.com'),
+    files,
+    `Shared files ${stamp}`
+  )
+})
+
+test.afterAll(async () => {
+  if (planted) await removeSharedDocuments(planted)
+  await Promise.all(plantedFiles.map((file) => rm(file, { force: true })))
+})
+
+test.describe('a shared invoice', () => {
+  test('shows its photo and its report to a customer with no session', async ({ browser }) => {
+    const { context, page } = await customer(browser)
+    await page.goto(jobShareUrl)
+    await expect(page.getByText(REPORT).first()).toBeVisible()
+    await expectPicturesLoaded(page)
+
+    const urls = await publicFileUrls(page)
+    expect(urls.length, 'the photo and the report are drawn through the file route').toBe(2)
+    await expectServed(context.request, urls)
+    await context.close()
+  })
+})
+
+test.describe('the other shared documents', () => {
+  test.beforeEach(() => {
+    test.skip(!planted, 'the suite does not share a disk with the app server')
+  })
+
+  test('a quote shows its photo and its document', async ({ browser }) => {
+    const { context, page } = await customer(browser)
+    await page.goto(`/share/quote/${organizationId}/${planted?.quoteToken}`)
+    await expect(page.getByText('estimate.pdf').first()).toBeVisible()
+    await expectPicturesLoaded(page)
+
+    const token = planted?.quoteToken ?? ''
+    const urls = await publicFileUrls(page)
+    expect(urls).toEqual(
+      expect.arrayContaining([
+        publicUrl(token, plantedUrls.quotePhoto),
+        publicUrl(token, plantedUrls.quoteDocument),
+      ])
+    )
+    await expectServed(context.request, urls)
+    await context.close()
+  })
+
+  test('an inspection shows its check photo and its overview photo', async ({ browser }) => {
+    const { context, page } = await customer(browser)
+    await page.goto(`/share/inspection/${organizationId}/${planted?.inspectionToken}`)
+    await expect(page.getByText('Brakes').filter({ visible: true }).first()).toBeVisible()
+    await expectPicturesLoaded(page)
+
+    const token = planted?.inspectionToken ?? ''
+    const urls = await publicFileUrls(page)
+    expect(urls).toContain(publicUrl(token, plantedUrls.inspectionOverview))
+    // The check's own photo opens in the lightbox, which fetches it on a
+    // click rather than drawing it on the sheet.
+    await expectServed(context.request, [...urls, publicUrl(token, plantedUrls.inspectionPhoto)])
+    await context.close()
+  })
+
+  test('a status report plays its video', async ({ browser }) => {
+    const { context, page } = await customer(browser)
+    await page.goto(`/share/status-report/${organizationId}/${planted?.reportToken}`)
+    const token = planted?.reportToken ?? ''
+    const video = publicUrl(token, plantedUrls.statusVideo)
+    await expect(page.locator(`source[src="${video}"], video[src="${video}"]`)).toHaveCount(1)
+
+    const response = await context.request.get(video)
+    expect(response.status()).toBe(200)
+    expect(response.headers()['content-type']).toBe('video/mp4')
+    await context.close()
+  })
+
+  test('a link opens no file its document does not show', async ({ browser }) => {
+    const { context } = await customer(browser)
+    const jobToken = jobShareUrl.split('/').pop() ?? ''
+    const quoteToken = planted?.quoteToken ?? ''
+    const inspectionToken = planted?.inspectionToken ?? ''
+    const reportToken = planted?.reportToken ?? ''
+
+    // Each is a real file of this workshop, under a valid link of this
+    // workshop, and still not the link's to open.
+    const refused = [
+      publicUrl(jobToken, plantedUrls.quotePhoto),
+      publicUrl(quoteToken, plantedUrls.inspectionPhoto),
+      publicUrl(inspectionToken, plantedUrls.inspectionHidden),
+      publicUrl(inspectionToken, plantedUrls.statusVideo),
+      publicUrl(reportToken, plantedUrls.inspectionPhoto),
+    ]
+    const missing = await context.request.get(
+      `/api/public/files/${jobToken}/quotes/${randomUUID()}.png`
+    )
+    expect(missing.status()).toBe(404)
+    const missingBody = await missing.text()
+
+    for (const url of refused) {
+      const response = await context.request.get(url)
+      expect(response.status(), `${url} is refused`).toBe(404)
+      expect(await response.text(), 'exactly as a missing file').toBe(missingBody)
+    }
+    await context.close()
+  })
+})

+ 101 - 0
e2e/support/db.ts

@@ -2215,3 +2215,104 @@ export async function setKeyboardShortcuts(
     )
   })
 }
+
+export interface SharedDocumentFiles {
+  quotePhoto: string
+  quoteDocument: string
+  inspectionPhoto: string
+  inspectionOverview: string
+  /** On the inspection, kept off the report. */
+  inspectionHidden: string
+  statusVideo: string
+}
+
+export interface PlantedSharedDocuments {
+  vehicleId: string
+  quoteToken: string
+  inspectionToken: string
+  reportToken: string
+}
+
+/**
+ * A quote, an inspection and a status report, each shared with a link and
+ * carrying the files its page shows, on a vehicle of their own. For the
+ * spec that checks a share link opens its own document's files and no other.
+ */
+export async function plantSharedDocuments(
+  organizationId: string,
+  userId: string,
+  files: SharedDocumentFiles,
+  label: string
+): Promise<PlantedSharedDocuments> {
+  return withDb(async (db) => {
+    const id = () => randomBytes(12).toString('hex')
+    const vehicleId = id()
+    const quoteId = id()
+    const inspectionId = id()
+    const quoteToken = id()
+    const inspectionToken = id()
+    const reportToken = id()
+    await db.query(
+      `insert into vehicles (id, make, model, year, "userId", "organizationId", "updatedAt")
+       values ($1, 'E2E', $2, 2020, $3, $4, now())`,
+      [vehicleId, label, userId, organizationId]
+    )
+    await db.query(
+      `insert into quotes (id, title, "userId", "organizationId", "vehicleId", "publicToken", "sharedAt", "updatedAt")
+       values ($1, $2, $3, $4, $5, $6, now(), now())`,
+      [quoteId, `${label} quote`, userId, organizationId, vehicleId, quoteToken]
+    )
+    for (const [fileUrl, fileName, fileType, category] of [
+      [files.quotePhoto, 'damage.png', 'image/png', 'image'],
+      [files.quoteDocument, 'estimate.pdf', 'application/pdf', 'document'],
+    ]) {
+      await db.query(
+        `insert into quote_attachments (id, "quoteId", "fileName", "fileUrl", "fileType", "fileSize", category)
+         values ($1, $2, $3, $4, $5, 10, $6)`,
+        [id(), quoteId, fileName, fileUrl, fileType, category]
+      )
+    }
+
+    const template = await db.query<{ id: string }>(
+      `select id from inspection_templates where "organizationId" = $1 limit 1`,
+      [organizationId]
+    )
+    if (!template.rows[0]) throw new Error('The seeded workshop has no inspection template')
+    await db.query(
+      `insert into inspections (id, "vehicleId", "organizationId", "templateId", status, "publicToken", "sharedAt", "updatedAt")
+       values ($1, $2, $3, $4, 'completed', $5, now(), now())`,
+      [inspectionId, vehicleId, organizationId, template.rows[0].id, inspectionToken]
+    )
+    await db.query(
+      `insert into inspection_items (id, "inspectionId", name, section, condition, "imageUrls")
+       values ($1, $2, 'Brakes', 'Checks', 'fail', $3)`,
+      [id(), inspectionId, [files.inspectionPhoto]]
+    )
+    for (const [fileUrl, fileName, fileType, category, shown] of [
+      [files.inspectionOverview, 'overview.png', 'image/png', 'image', true],
+      [files.inspectionHidden, 'paperwork.pdf', 'application/pdf', 'document', false],
+    ]) {
+      await db.query(
+        `insert into inspection_attachments (id, "inspectionId", "fileName", "fileUrl", "fileType", "fileSize", category, "includeInReport")
+         values ($1, $2, $3, $4, $5, 10, $6, $7)`,
+        [id(), inspectionId, fileName, fileUrl, fileType, category, shown]
+      )
+    }
+
+    await db.query(
+      `insert into status_reports (id, "publicToken", "organizationId", "inspectionId", "videoUrl", "videoFileName", status, "updatedAt")
+       values ($1, $2, $3, $4, $5, 'walkaround.mp4', 'sent', now())`,
+      [id(), reportToken, organizationId, inspectionId, files.statusVideo]
+    )
+    return { vehicleId, quoteToken, inspectionToken, reportToken }
+  })
+}
+
+/** Removes what `plantSharedDocuments` made. */
+export async function removeSharedDocuments(planted: PlantedSharedDocuments): Promise<void> {
+  await withDb(async (db) => {
+    await db.query('delete from quotes where "vehicleId" = $1', [planted.vehicleId])
+    await db.query('delete from inspections where "vehicleId" = $1', [planted.vehicleId])
+    await db.query('delete from vehicles where id = $1', [planted.vehicleId])
+  })
+}

+ 434 - 0
src/__tests__/lib/shared-files.test.ts

@@ -0,0 +1,434 @@
+/**
+ * @vitest-environment node
+ *
+ * A share link opens the files its document shows the customer, and nothing
+ * else of the workshop: not another job's photos, not another workshop's,
+ * even with a valid token and a real file name. And it does so cheaply: a
+ * share page asks once per picture, so each file is one lookup of the token
+ * and one narrow question, never a load of everything the document holds.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    statusReport: { findFirst: vi.fn() },
+    serviceAttachment: { findFirst: vi.fn() },
+    quoteAttachment: { findFirst: vi.fn() },
+    inspectionItem: { findFirst: vi.fn() },
+    inspectionAttachment: { findFirst: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+  },
+}))
+vi.mock('@/lib/share-link.server', () => ({ findSharedDocumentOfAnyKind: vi.fn() }))
+
+import { NextRequest } from 'next/server'
+import { db } from '@/lib/db'
+import { findSharedDocumentOfAnyKind } from '@/lib/share-link.server'
+import {
+  isSharedFile,
+  resolveSharedFileToken,
+  type SharedFileDocument,
+  storedFileKey,
+  storedFileUrls,
+} from '@/lib/shared-files.server'
+import { GET } from '@/app/api/public/files/[token]/[...path]/route'
+
+const ORG = 'org_a'
+const OTHER_ORG = 'org_b'
+const url = (category: string, file: string, org = ORG) =>
+  `/api/protected/files/${org}/${category}/${file}`
+
+type Row = Record<string, unknown>
+
+/** Every link of the two workshops: which document a token opens, and whether it is open. */
+const shared: Record<
+  string,
+  { kind: 'invoice' | 'quote' | 'inspection'; id: string; organizationId: string; open: boolean }
+> = {
+  'job-token': { kind: 'invoice', id: 'job', organizationId: ORG, open: true },
+  'other-job-token': { kind: 'invoice', id: 'other-job', organizationId: ORG, open: true },
+  'closed-job-token': { kind: 'invoice', id: 'closed-job', organizationId: ORG, open: false },
+  'stranger-job-token': {
+    kind: 'invoice',
+    id: 'stranger-job',
+    organizationId: OTHER_ORG,
+    open: true,
+  },
+  'quote-token': { kind: 'quote', id: 'quote', organizationId: ORG, open: true },
+  'inspection-token': { kind: 'inspection', id: 'inspection', organizationId: ORG, open: true },
+}
+
+const serviceAttachments: Row[] = [
+  { serviceRecordId: 'job', fileUrl: url('services', 'job-photo.jpg'), includeInInvoice: true },
+  { serviceRecordId: 'job', fileUrl: url('services', 'job-report.pdf'), includeInInvoice: true },
+  { serviceRecordId: 'job', fileUrl: url('tire-hotel', 'tire-set.jpg'), includeInInvoice: true },
+  { serviceRecordId: 'job', fileUrl: url('services', 'job-video.mp4'), includeInInvoice: true },
+  // Kept off the invoice by the workshop: the page does not list it.
+  {
+    serviceRecordId: 'job',
+    fileUrl: url('services', 'job-internal.jpg'),
+    includeInInvoice: false,
+  },
+  {
+    serviceRecordId: 'other-job',
+    fileUrl: url('services', 'other-job-photo.jpg'),
+    includeInInvoice: true,
+  },
+  {
+    serviceRecordId: 'stranger-job',
+    fileUrl: url('services', 'stranger-photo.jpg', OTHER_ORG),
+    includeInInvoice: true,
+  },
+]
+
+const quoteAttachments: Row[] = [
+  { quoteId: 'quote', fileUrl: url('quotes', 'quote-photo.jpg'), category: 'image' },
+  { quoteId: 'quote', fileUrl: url('quotes', 'quote-terms.pdf'), category: 'document' },
+  // A category the share page does not list.
+  { quoteId: 'quote', fileUrl: url('quotes', 'quote-other.jpg'), category: 'internal' },
+]
+
+const inspectionItems: Row[] = [
+  {
+    inspectionId: 'inspection',
+    imageUrls: [url('inspections', 'brake-pads.jpg'), url('inspections', 'noise.mp4')],
+  },
+  // The older address form is still on records.
+  { inspectionId: 'inspection', imageUrls: [`/api/files/${ORG}/inspections/tyre-tread.jpg`] },
+]
+
+const inspectionAttachments: Row[] = [
+  { inspectionId: 'inspection', fileUrl: url('documents', 'overview.jpg'), includeInReport: true },
+  {
+    inspectionId: 'inspection',
+    fileUrl: url('documents', 'hidden-paperwork.pdf'),
+    includeInReport: false,
+  },
+]
+
+const statusReports: Record<
+  string,
+  { id: string; organizationId: string; videoUrl: string | null; expiresAt: Date | null }
+> = {
+  'report-token': {
+    id: 'report',
+    organizationId: ORG,
+    videoUrl: url('services', 'walkaround.mp4'),
+    expiresAt: null,
+  },
+  'expired-report-token': {
+    id: 'old-report',
+    organizationId: ORG,
+    videoUrl: url('services', 'old-walkaround.mp4'),
+    expiresAt: new Date('2000-01-01'),
+  },
+}
+
+const settings = [
+  { organizationId: ORG, key: 'workshop.logo', value: url('logos', 'company.png') },
+  { organizationId: ORG, key: 'quote.logo', value: ` ${url('logos', 'quote-letterhead.png')} ` },
+  {
+    organizationId: OTHER_ORG,
+    key: 'workshop.logo',
+    value: url('logos', 'stranger.png', OTHER_ORG),
+  },
+]
+
+/** Applies a Prisma `where` of the shapes the helper uses to one row. */
+function matches(row: Row, where: Record<string, unknown>): boolean {
+  return Object.entries(where).every(([key, condition]) => {
+    const actual = row[key]
+    if (condition && typeof condition === 'object') {
+      if ('in' in condition) return (condition.in as unknown[]).includes(actual)
+      if ('hasSome' in condition) {
+        return (condition.hasSome as unknown[]).some((value) =>
+          (actual as unknown[]).includes(value)
+        )
+      }
+    }
+    return actual === condition
+  })
+}
+
+/** A `findFirst` over fixture rows that honours the query's filters. */
+function findFirstIn(rows: Row[]) {
+  return (async (args: { where: Record<string, unknown> }) =>
+    rows.find((row) => matches(row, args.where)) ? { id: 'row' } : null) as never
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(findSharedDocumentOfAnyKind).mockImplementation(async (token: string) => {
+    const doc = shared[token]
+    return doc ? ({ ...doc, expiry: {} } as never) : null
+  })
+  vi.mocked(db.statusReport.findFirst).mockImplementation(
+    (async (args: { where: { publicToken: string } }) =>
+      statusReports[args.where.publicToken] ?? null) as never
+  )
+  vi.mocked(db.serviceAttachment.findFirst).mockImplementation(findFirstIn(serviceAttachments))
+  vi.mocked(db.quoteAttachment.findFirst).mockImplementation(findFirstIn(quoteAttachments))
+  vi.mocked(db.inspectionItem.findFirst).mockImplementation(findFirstIn(inspectionItems))
+  vi.mocked(db.inspectionAttachment.findFirst).mockImplementation(
+    findFirstIn(inspectionAttachments)
+  )
+  vi.mocked(db.appSetting.findMany).mockImplementation((async (args: {
+    where: { organizationId: string; key: { in: string[] } }
+  }) =>
+    settings.filter(
+      (row) =>
+        row.organizationId === args.where.organizationId && args.where.key.in.includes(row.key)
+    )) as never)
+})
+
+async function opens(token: string, category: string, file: string) {
+  const resolved = await resolveSharedFileToken(token)
+  return resolved.status === 'open' && (await isSharedFile(resolved.document, category, file))
+}
+
+describe('stored addresses', () => {
+  it('reads both address forms of this workshop', () => {
+    expect(storedFileKey(url('services', 'a.jpg'), ORG)).toBe('services/a.jpg')
+    expect(storedFileKey(`/api/files/${ORG}/services/a.jpg`, ORG)).toBe('services/a.jpg')
+  })
+
+  it('refuses another workshop’s address and anything that is not an upload', () => {
+    expect(storedFileKey(url('services', 'a.jpg', OTHER_ORG), ORG)).toBeNull()
+    expect(storedFileKey('https://example.com/a.jpg', ORG)).toBeNull()
+    expect(storedFileKey('/uploads/services/a.jpg', ORG)).toBeNull()
+    expect(storedFileKey(null, ORG)).toBeNull()
+  })
+
+  it('asks the database for exactly the addresses that read back as the file', () => {
+    for (const stored of storedFileUrls(ORG, 'services', 'a.jpg')) {
+      expect(storedFileKey(stored, ORG)).toBe('services/a.jpg')
+    }
+  })
+})
+
+describe('a work order or invoice link', () => {
+  it('opens every file the invoice lists, in every folder they live in', async () => {
+    expect(await opens('job-token', 'services', 'job-photo.jpg')).toBe(true)
+    expect(await opens('job-token', 'services', 'job-report.pdf')).toBe(true)
+    expect(await opens('job-token', 'services', 'job-video.mp4')).toBe(true)
+    expect(await opens('job-token', 'tire-hotel', 'tire-set.jpg')).toBe(true)
+  })
+
+  it('opens the workshop’s logos, a stored value with stray spaces included', async () => {
+    expect(await opens('job-token', 'logos', 'company.png')).toBe(true)
+    expect(await opens('job-token', 'logos', 'quote-letterhead.png')).toBe(true)
+  })
+
+  it('does not open a file the workshop kept off the invoice', async () => {
+    expect(await opens('job-token', 'services', 'job-internal.jpg')).toBe(false)
+  })
+
+  it('does not open another job’s file of the same workshop', async () => {
+    expect(await opens('job-token', 'services', 'other-job-photo.jpg')).toBe(false)
+  })
+
+  it('does not open a file under another folder than the one it was stored in', async () => {
+    expect(await opens('job-token', 'inventory', 'job-photo.jpg')).toBe(false)
+  })
+
+  it('does not open another workshop’s file or logo', async () => {
+    expect(await opens('job-token', 'services', 'stranger-photo.jpg')).toBe(false)
+    expect(await opens('job-token', 'logos', 'stranger.png')).toBe(false)
+  })
+})
+
+describe('a quote link', () => {
+  it('opens its photos, its documents and the logos', async () => {
+    expect(await opens('quote-token', 'quotes', 'quote-photo.jpg')).toBe(true)
+    expect(await opens('quote-token', 'quotes', 'quote-terms.pdf')).toBe(true)
+    expect(await opens('quote-token', 'logos', 'quote-letterhead.png')).toBe(true)
+  })
+
+  it('opens nothing the page does not list, and no job’s files', async () => {
+    expect(await opens('quote-token', 'quotes', 'quote-other.jpg')).toBe(false)
+    expect(await opens('quote-token', 'services', 'job-photo.jpg')).toBe(false)
+    expect(await opens('quote-token', 'services', 'stranger-photo.jpg')).toBe(false)
+  })
+})
+
+describe('an inspection link', () => {
+  it('opens every check’s photos and videos, in either address form', async () => {
+    expect(await opens('inspection-token', 'inspections', 'brake-pads.jpg')).toBe(true)
+    expect(await opens('inspection-token', 'inspections', 'noise.mp4')).toBe(true)
+    expect(await opens('inspection-token', 'inspections', 'tyre-tread.jpg')).toBe(true)
+  })
+
+  it('opens the files shown on the report, and the logos', async () => {
+    expect(await opens('inspection-token', 'documents', 'overview.jpg')).toBe(true)
+    expect(await opens('inspection-token', 'logos', 'company.png')).toBe(true)
+  })
+
+  it('opens nothing the workshop kept back, and no other document’s files', async () => {
+    expect(await opens('inspection-token', 'documents', 'hidden-paperwork.pdf')).toBe(false)
+    expect(await opens('inspection-token', 'services', 'job-photo.jpg')).toBe(false)
+    expect(await opens('inspection-token', 'logos', 'stranger.png')).toBe(false)
+  })
+})
+
+describe('a status report link', () => {
+  it('opens its video and the logos', async () => {
+    expect(await opens('report-token', 'services', 'walkaround.mp4')).toBe(true)
+    expect(await opens('report-token', 'logos', 'company.png')).toBe(true)
+  })
+
+  it('opens no other file of the workshop', async () => {
+    expect(await opens('report-token', 'services', 'job-photo.jpg')).toBe(false)
+    expect(await opens('report-token', 'services', 'stranger-photo.jpg')).toBe(false)
+  })
+
+  it('is closed once the report has expired', async () => {
+    expect(await resolveSharedFileToken('expired-report-token')).toEqual({ status: 'expired' })
+  })
+})
+
+describe('a token no document carries', () => {
+  it('opens nothing', async () => {
+    expect(await resolveSharedFileToken('no-such-token')).toEqual({ status: 'unknown' })
+  })
+})
+
+describe('what one file costs', () => {
+  const invoice: SharedFileDocument = { kind: 'invoice', id: 'job', organizationId: ORG }
+
+  it('asks one narrow question for a document’s own file, and reads no logos', async () => {
+    expect(await isSharedFile(invoice, 'services', 'job-photo.jpg')).toBe(true)
+    expect(db.serviceAttachment.findFirst).toHaveBeenCalledTimes(1)
+    expect(db.appSetting.findMany).not.toHaveBeenCalled()
+    // Only the addresses that name the file, on this document, shown on it.
+    expect(vi.mocked(db.serviceAttachment.findFirst).mock.calls[0][0]).toEqual({
+      where: {
+        serviceRecordId: 'job',
+        includeInInvoice: true,
+        fileUrl: { in: storedFileUrls(ORG, 'services', 'job-photo.jpg') },
+      },
+      select: { id: true },
+    })
+  })
+
+  it('reads the logos first for a logo, and nothing of the document', async () => {
+    expect(await isSharedFile(invoice, 'logos', 'company.png')).toBe(true)
+    expect(db.appSetting.findMany).toHaveBeenCalledTimes(1)
+    expect(db.serviceAttachment.findFirst).not.toHaveBeenCalled()
+  })
+
+  it('asks an inspection about the one file, never for every check’s photos', async () => {
+    const inspection: SharedFileDocument = {
+      kind: 'inspection',
+      id: 'inspection',
+      organizationId: ORG,
+    }
+    expect(await isSharedFile(inspection, 'inspections', 'brake-pads.jpg')).toBe(true)
+    expect(vi.mocked(db.inspectionItem.findFirst).mock.calls[0][0]).toEqual({
+      where: {
+        inspectionId: 'inspection',
+        imageUrls: { hasSome: storedFileUrls(ORG, 'inspections', 'brake-pads.jpg') },
+      },
+      select: { id: true },
+    })
+    expect(db.inspectionAttachment.findFirst).not.toHaveBeenCalled()
+  })
+
+  it('needs no query at all for a status report’s video', async () => {
+    const resolved = await resolveSharedFileToken('report-token')
+    vi.mocked(db.statusReport.findFirst).mockClear()
+    expect(resolved.status).toBe('open')
+    if (resolved.status !== 'open') return
+    expect(await isSharedFile(resolved.document, 'services', 'walkaround.mp4')).toBe(true)
+    expect(db.statusReport.findFirst).not.toHaveBeenCalled()
+  })
+})
+
+describe('the public file route', () => {
+  let root: string
+  const previousRoot = process.env.DATA_ROOT
+
+  beforeAll(() => {
+    root = mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'shared-files-'))
+    process.env.DATA_ROOT = root
+    const write = (org: string, category: string, file: string, body: string) => {
+      mkdirSync(path.join(root, 'uploads', org, category), { recursive: true })
+      writeFileSync(path.join(root, 'uploads', org, category, file), body)
+    }
+    write(ORG, 'services', 'job-photo.jpg', 'job photo')
+    write(ORG, 'services', 'other-job-photo.jpg', 'other job photo')
+    write(ORG, 'services', 'old-walkaround.mp4', 'old video')
+    write(ORG, 'logos', 'company.png', 'logo')
+    write(OTHER_ORG, 'services', 'stranger-photo.jpg', 'stranger photo')
+  })
+
+  afterAll(() => {
+    rmSync(root, { recursive: true, force: true })
+    if (previousRoot === undefined) delete process.env.DATA_ROOT
+    else process.env.DATA_ROOT = previousRoot
+  })
+
+  const get = (token: string, category: string, file: string) =>
+    GET(new NextRequest(`http://localhost/api/public/files/${token}/${category}/${file}`), {
+      params: Promise.resolve({ token, path: [category, file] }),
+    })
+
+  it('serves the document’s own file, never cached, looking the token up once', async () => {
+    const response = await get('job-token', 'services', 'job-photo.jpg')
+    expect(response.status).toBe(200)
+    expect(await response.text()).toBe('job photo')
+    expect(response.headers.get('content-type')).toBe('image/jpeg')
+    expect(response.headers.get('cache-control')).toBe('private, no-store')
+    expect(findSharedDocumentOfAnyKind).toHaveBeenCalledTimes(1)
+  })
+
+  it('answers another job’s real file exactly as a missing one', async () => {
+    const refused = await get('job-token', 'services', 'other-job-photo.jpg')
+    const missing = await get('job-token', 'services', 'never-uploaded.jpg')
+    expect(refused.status).toBe(404)
+    expect(missing.status).toBe(404)
+    expect(await refused.json()).toEqual(await missing.json())
+  })
+
+  it('does not serve a file of another workshop', async () => {
+    const response = await get('job-token', 'services', 'stranger-photo.jpg')
+    expect(response.status).toBe(404)
+  })
+
+  it('serves the workshop logo on any of its links', async () => {
+    for (const token of ['job-token', 'quote-token', 'inspection-token', 'report-token']) {
+      const response = await get(token, 'logos', 'company.png')
+      expect(response.status, token).toBe(200)
+    }
+  })
+
+  it('says a closed link is closed, for a document and a status report alike', async () => {
+    const closedJob = await get('closed-job-token', 'logos', 'company.png')
+    const closedReport = await get('expired-report-token', 'services', 'old-walkaround.mp4')
+    expect(closedJob.status).toBe(410)
+    expect(closedReport.status).toBe(410)
+    expect(await closedReport.json()).toEqual(await closedJob.json())
+  })
+
+  it('serves a stored SVG logo only as a sandboxed download', async () => {
+    mkdirSync(path.join(root, 'uploads', ORG, 'logos'), { recursive: true })
+    writeFileSync(path.join(root, 'uploads', ORG, 'logos', 'mark.svg'), '<svg/>')
+    settings.push({ organizationId: ORG, key: 'invoice.logo', value: url('logos', 'mark.svg') })
+    try {
+      const response = await get('job-token', 'logos', 'mark.svg')
+      expect(response.status).toBe(200)
+      expect(response.headers.get('content-disposition')).toBe('attachment')
+      expect(response.headers.get('content-security-policy')).toContain('sandbox')
+      expect(response.headers.get('cache-control')).toBe('private, no-store')
+    } finally {
+      settings.pop()
+    }
+  })
+
+  it('opens nothing for a token no document carries', async () => {
+    const response = await get('no-such-token', 'logos', 'company.png')
+    expect(response.status).toBe(404)
+  })
+})

+ 10 - 45
src/app/api/public/files/[token]/[...path]/route.ts

@@ -1,7 +1,7 @@
 import { NextRequest, NextResponse } from 'next/server'
-import { refuseExpiredShareToken } from '@/lib/share-link-route'
+import { shareLinkExpiredResponse } from '@/lib/share-link-route'
 import { svgDownloadHeaders } from '@/lib/upload-url'
-import { db } from '@/lib/db'
+import { isSharedFile, resolveSharedFileToken } from '@/lib/shared-files.server'
 import { readFile, stat } from 'fs/promises'
 import path from 'path'
 import { uploadsRoot } from '@/lib/upload-root'
@@ -55,51 +55,16 @@ export async function GET(
     return NextResponse.json({ error: 'Invalid filename' }, { status: 400 })
   }
 
-  // A document's pictures close with its link.
-  const closed = await refuseExpiredShareToken(token)
-  if (closed) return closed
-
-  // Validate token and get org (check both invoice and quote tokens)
-  let orgId: string | undefined
-
-  const serviceRecord = await db.serviceRecord.findUnique({
-    where: { publicToken: token },
-    select: { organizationId: true },
-  })
-
-  if (serviceRecord?.organizationId) {
-    orgId = serviceRecord.organizationId
-  } else {
-    const quote = await db.quote.findFirst({
-      where: { publicToken: token },
-      select: { organizationId: true },
-    })
-    if (quote?.organizationId) {
-      orgId = quote.organizationId
-    } else {
-      const inspection = await db.inspection.findFirst({
-        where: { publicToken: token },
-        select: { organizationId: true },
-      })
-      if (inspection?.organizationId) {
-        orgId = inspection.organizationId
-      }
-    }
-  }
-
-  if (!orgId) {
-    const statusReport = await db.statusReport.findFirst({
-      where: { publicToken: token },
-      select: { organizationId: true },
-    })
-    if (statusReport?.organizationId) {
-      orgId = statusReport.organizationId
-    }
-  }
-
-  if (!orgId) {
+  // One lookup of the token answers both whether its link is still open and
+  // which document's files it opens. A document's pictures close with its
+  // link. A file the document does not show answers exactly as a missing one
+  // does, so the route never says whether a name exists.
+  const shared = await resolveSharedFileToken(token)
+  if (shared.status === 'expired') return shareLinkExpiredResponse()
+  if (shared.status !== 'open' || !(await isSharedFile(shared.document, category, filename))) {
     return NextResponse.json({ error: 'Not found' }, { status: 404 })
   }
+  const orgId = shared.document.organizationId
   const filePath = path.join(uploadsRoot(), orgId, category, filename)
 
   try {

+ 4 - 6
src/lib/share-link-route.ts

@@ -1,7 +1,7 @@
 import 'server-only'
 import { NextResponse } from 'next/server'
 import type { ShareKind } from '@/lib/share-expiry'
-import { findSharedDocument, findSharedDocumentOfAnyKind } from '@/lib/share-link.server'
+import { findSharedDocument } from '@/lib/share-link.server'
 
 const NOT_FOUND = { error: 'Not found' }
 const EXPIRED = { error: 'This link has expired', expired: true }
@@ -22,9 +22,7 @@ export async function refuseClosedShareLink(
   return null
 }
 
-/** The same for a route that only has the token, whichever document it names. */
-export async function refuseExpiredShareToken(token: string): Promise<NextResponse | null> {
-  const shared = await findSharedDocumentOfAnyKind(token)
-  if (shared && !shared.open) return NextResponse.json(EXPIRED, { status: 410 })
-  return null
+/** The answer a route behind a share link gives once the link has expired. */
+export function shareLinkExpiredResponse(): NextResponse {
+  return NextResponse.json(EXPIRED, { status: 410 })
 }

+ 180 - 0
src/lib/shared-files.server.ts

@@ -0,0 +1,180 @@
+import 'server-only'
+import { db } from '@/lib/db'
+import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
+import type { ShareKind } from '@/lib/share-expiry'
+import { findSharedDocumentOfAnyKind } from '@/lib/share-link.server'
+
+/**
+ * Which uploads a share link's token opens.
+ *
+ * A token stands for one document, so it opens what that document shows the
+ * customer and nothing else of the workshop: the files the page draws, read
+ * from the same columns and with the same filters the page uses. The
+ * workshop's logos are the one exception, since they head every document a
+ * workshop sends and any of its links may show them.
+ *
+ * Each share page turns a stored address into `/api/public/files/<token>/
+ * <category>/<file>`. When a page starts drawing a new file, add its column
+ * here too, or the customer sees a broken image.
+ *
+ * A share page with fifty photos asks this fifty times, so the token is
+ * looked up once per request, that one lookup also answers whether the link
+ * is still open, and each file is a single narrow question ("is this address
+ * on this document") rather than a load of everything the document holds.
+ */
+
+/** The settings that hold a logo a shared page or its sheet draws. */
+const LOGO_SETTING_KEYS = [
+  SETTING_KEYS.COMPANY_LOGO,
+  SETTING_KEYS.INVOICE_LOGO,
+  SETTING_KEYS.QUOTE_LOGO,
+  SETTING_KEYS.CERTIFICATE_LOGO,
+  SETTING_KEYS.WORK_ORDER_LOGO,
+]
+
+/** The quote attachments the share page lists: its photos and its documents. */
+const SHOWN_QUOTE_CATEGORIES = ['image', 'document']
+
+/** Both forms a stored upload address has had: `/api/protected/files/` and `/api/files/`. */
+const STORED_FILE_URL = /^\/api\/(?:protected\/)?files\/([^/]+)\/([^/]+)\/([^/]+)$/
+
+/** The document behind an open link, as much of it as the file check needs. */
+export type SharedFileDocument =
+  | { kind: ShareKind; id: string; organizationId: string }
+  | { kind: 'statusReport'; id: string; organizationId: string; videoUrl: string | null }
+
+export type SharedFileToken =
+  | { status: 'unknown' }
+  | { status: 'expired' }
+  | { status: 'open'; document: SharedFileDocument }
+
+/**
+ * The `<category>/<file>` a stored address names, or null when it is not an
+ * upload of this workshop. An address under another workshop's folder is
+ * never one of this document's files, whatever its file name.
+ */
+export function storedFileKey(
+  url: string | null | undefined,
+  organizationId: string
+): string | null {
+  const match = url ? STORED_FILE_URL.exec(url) : null
+  if (!match) return null
+  const [, owner, category, file] = match
+  if (owner !== organizationId) return null
+  return `${category}/${file}`
+}
+
+/**
+ * Every stored address that names this file: exactly the addresses
+ * `storedFileKey` reads back as `<category>/<file>` for this workshop.
+ */
+export function storedFileUrls(organizationId: string, category: string, file: string): string[] {
+  return [
+    `/api/protected/files/${organizationId}/${category}/${file}`,
+    `/api/files/${organizationId}/${category}/${file}`,
+  ]
+}
+
+/**
+ * The document a token stands for, and whether its link is open. One lookup
+ * serves both the expiry check and the file check. Invoices are tried first,
+ * being what most links lead to; a status report, which keeps its expiry in
+ * a column of its own, last.
+ */
+export async function resolveSharedFileToken(token: string): Promise<SharedFileToken> {
+  const shared = await findSharedDocumentOfAnyKind(token)
+  if (shared) {
+    if (!shared.open) return { status: 'expired' }
+    return {
+      status: 'open',
+      document: { kind: shared.kind, id: shared.id, organizationId: shared.organizationId },
+    }
+  }
+
+  const report = await db.statusReport.findFirst({
+    where: { publicToken: token },
+    select: { id: true, organizationId: true, videoUrl: true, expiresAt: true },
+  })
+  if (!report?.organizationId) return { status: 'unknown' }
+  // A report's video closes with the report's own page, and says so the way
+  // every other closed link does.
+  if (report.expiresAt !== null && report.expiresAt < new Date()) return { status: 'expired' }
+  return {
+    status: 'open',
+    document: {
+      kind: 'statusReport',
+      id: report.id,
+      organizationId: report.organizationId,
+      videoUrl: report.videoUrl,
+    },
+  }
+}
+
+/** Whether the document itself shows a file stored under any of these addresses. */
+async function documentShows(document: SharedFileDocument, urls: string[]): Promise<boolean> {
+  switch (document.kind) {
+    case 'invoice': {
+      // A work order or invoice: the files the workshop attached for the customer.
+      const row = await db.serviceAttachment.findFirst({
+        where: { serviceRecordId: document.id, includeInInvoice: true, fileUrl: { in: urls } },
+        select: { id: true },
+      })
+      return row !== null
+    }
+    case 'quote': {
+      // A quote: its photos and documents.
+      const row = await db.quoteAttachment.findFirst({
+        where: {
+          quoteId: document.id,
+          category: { in: SHOWN_QUOTE_CATEGORIES },
+          fileUrl: { in: urls },
+        },
+        select: { id: true },
+      })
+      return row !== null
+    }
+    case 'inspection': {
+      // An inspection: every check's photos and videos, and the files on the
+      // inspection as a whole that the workshop chose to show.
+      const item = await db.inspectionItem.findFirst({
+        where: { inspectionId: document.id, imageUrls: { hasSome: urls } },
+        select: { id: true },
+      })
+      if (item) return true
+      const attachment = await db.inspectionAttachment.findFirst({
+        where: { inspectionId: document.id, includeInReport: true, fileUrl: { in: urls } },
+        select: { id: true },
+      })
+      return attachment !== null
+    }
+    case 'statusReport':
+      // A status report: its video.
+      return document.videoUrl !== null && urls.includes(document.videoUrl)
+  }
+}
+
+/** Whether the file is one of the workshop's logos. */
+async function isWorkshopLogo(organizationId: string, key: string): Promise<boolean> {
+  const logos = await db.appSetting.findMany({
+    where: { organizationId, key: { in: LOGO_SETTING_KEYS } },
+    select: { value: true },
+  })
+  return logos.some((setting) => storedFileKey(setting.value.trim(), organizationId) === key)
+}
+
+/** Whether the shared document shows this file. */
+export async function isSharedFile(
+  document: SharedFileDocument,
+  category: string,
+  filename: string
+): Promise<boolean> {
+  const { organizationId } = document
+  const urls = storedFileUrls(organizationId, category, filename)
+  const key = `${category}/${filename}`
+  // A logo is asked about on every page of every link; anything else is a
+  // file of the document. Both are tried either way, in the likelier order.
+  if (category === 'logos') {
+    return (await isWorkshopLogo(organizationId, key)) || (await documentShows(document, urls))
+  }
+  return (await documentShows(document, urls)) || (await isWorkshopLogo(organizationId, key))
+}