shared-files.spec.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import { randomUUID } from 'node:crypto'
  2. import { mkdir, rm, writeFile } from 'node:fs/promises'
  3. import path from 'node:path'
  4. import { type APIRequestContext, type Browser, expect, type Page, test } from '@playwright/test'
  5. import { attach } from '../../support/attachments'
  6. import {
  7. ownerOrganizationId,
  8. type PlantedSharedDocuments,
  9. plantSharedDocuments,
  10. removeSharedDocuments,
  11. userIdFor,
  12. } from '../../support/db'
  13. import { sharesDiskWithServer, uploadPath } from '../../support/files'
  14. import { makePdf, TINY_PNG } from '../../support/pdf'
  15. import {
  16. addPart,
  17. newWorkOrder,
  18. saveWorkOrder,
  19. seededVehicleUrl,
  20. shareLink,
  21. } from '../../support/work-order'
  22. /**
  23. * What a share link opens on the public file route.
  24. *
  25. * Every page a customer reaches through a link draws its pictures, videos
  26. * and documents through `/api/public/files/<token>/...`. Each one has to
  27. * load, on every kind of shared document, for a reader with no session at
  28. * all. And a link opens its own document's files only: the token of one job
  29. * is no key to the rest of the workshop's uploads, and a file it does not
  30. * show answers exactly as a file that does not exist.
  31. */
  32. test.describe.configure({ mode: 'serial' })
  33. const stamp = Date.now()
  34. const PHOTO = `e2e-shared-photo-${stamp}.png`
  35. const REPORT = `e2e-shared-report-${stamp}.pdf`
  36. let organizationId = ''
  37. let jobShareUrl = ''
  38. let planted: PlantedSharedDocuments | null = null
  39. const plantedFiles: string[] = []
  40. const plantedUrls: Record<string, string> = {}
  41. /** A file under the workshop's uploads with the URL a row would hold for it. */
  42. async function plant(folder: string, ext: string, body: Buffer): Promise<string> {
  43. const name = `${randomUUID()}.${ext}`
  44. const file = uploadPath(organizationId, folder, name)
  45. await mkdir(path.dirname(file), { recursive: true })
  46. await writeFile(file, body)
  47. plantedFiles.push(file)
  48. return `/api/protected/files/${organizationId}/${folder}/${name}`
  49. }
  50. /** The public address a share page gives a stored file under this token. */
  51. function publicUrl(token: string, storedUrl: string): string {
  52. return storedUrl.replace(/^\/api\/protected\/files\/[^/]+\//, `/api/public/files/${token}/`)
  53. }
  54. /** A browser with nobody signed in, as the customer opens the link. */
  55. async function customer(browser: Browser) {
  56. const context = await browser.newContext({ storageState: { cookies: [], origins: [] } })
  57. return { context, page: await context.newPage() }
  58. }
  59. /** Every public file address the page draws or links to. */
  60. async function publicFileUrls(page: Page): Promise<string[]> {
  61. const urls = await page.evaluate(() =>
  62. [...document.querySelectorAll('img[src], video[src], source[src], a[href]')]
  63. .map((el) => el.getAttribute('src') ?? el.getAttribute('href') ?? '')
  64. .filter((url) => url.startsWith('/api/public/files/'))
  65. )
  66. return [...new Set(urls)]
  67. }
  68. /** Every picture from the file route on the page has decoded. */
  69. async function expectPicturesLoaded(page: Page) {
  70. await expect(async () => {
  71. const broken = await page.evaluate(() =>
  72. [...document.querySelectorAll<HTMLImageElement>('img')]
  73. .filter((img) => (img.getAttribute('src') ?? '').startsWith('/api/public/files/'))
  74. .filter((img) => !img.complete || img.naturalWidth === 0)
  75. .map((img) => img.getAttribute('src'))
  76. )
  77. expect(broken, 'every picture on the shared page loaded').toEqual([])
  78. }).toPass({ timeout: 15_000 })
  79. }
  80. /** Each address answers with the file, to a client with no cookies. */
  81. async function expectServed(request: APIRequestContext, urls: string[]) {
  82. for (const url of urls) {
  83. const response = await request.get(url)
  84. expect(response.status(), `${url} is served`).toBe(200)
  85. expect(response.headers()['cache-control']).toBe('private, no-store')
  86. }
  87. }
  88. test.beforeAll(async ({ browser }) => {
  89. test.setTimeout(180_000)
  90. organizationId = await ownerOrganizationId()
  91. // A job made the way a workshop makes one: a photo and a report on it,
  92. // then shared.
  93. const page = await browser.newPage({ storageState: 'e2e/.auth/owner.json' })
  94. const vehicleUrl = await seededVehicleUrl(page)
  95. await newWorkOrder(page, vehicleUrl, `E2E shared files ${stamp}`)
  96. await addPart(page, { name: `E2E filter ${stamp}`, quantity: 1, unitPrice: 100 })
  97. await saveWorkOrder(page)
  98. await attach(page, 'Photos', { name: PHOTO, mimeType: 'image/png', buffer: TINY_PNG })
  99. await attach(page, 'Documents', {
  100. name: REPORT,
  101. mimeType: 'application/pdf',
  102. buffer: await makePdf(['E2E SHARED REPORT']),
  103. })
  104. jobShareUrl = await shareLink(page)
  105. await page.close()
  106. // The other documents a link can lead to, planted with their files when
  107. // the suite shares a disk with the server.
  108. if (!sharesDiskWithServer()) return
  109. const files = {
  110. quotePhoto: await plant('quotes', 'png', TINY_PNG),
  111. quoteDocument: await plant('quotes', 'pdf', await makePdf(['E2E QUOTE TERMS'])),
  112. inspectionPhoto: await plant('inspections', 'png', TINY_PNG),
  113. inspectionOverview: await plant('inspections', 'png', TINY_PNG),
  114. inspectionHidden: await plant('inspections', 'pdf', await makePdf(['E2E PAPERWORK'])),
  115. statusVideo: await plant('services', 'mp4', Buffer.from('e2e video')),
  116. }
  117. Object.assign(plantedUrls, files)
  118. planted = await plantSharedDocuments(
  119. organizationId,
  120. await userIdFor('demo@torqvoice.com'),
  121. files,
  122. `Shared files ${stamp}`
  123. )
  124. })
  125. test.afterAll(async () => {
  126. if (planted) await removeSharedDocuments(planted)
  127. await Promise.all(plantedFiles.map((file) => rm(file, { force: true })))
  128. })
  129. test.describe('a shared invoice', () => {
  130. test('shows its photo and its report to a customer with no session', async ({ browser }) => {
  131. const { context, page } = await customer(browser)
  132. await page.goto(jobShareUrl)
  133. await expect(page.getByText(REPORT).first()).toBeVisible()
  134. await expectPicturesLoaded(page)
  135. const urls = await publicFileUrls(page)
  136. expect(urls.length, 'the photo and the report are drawn through the file route').toBe(2)
  137. await expectServed(context.request, urls)
  138. await context.close()
  139. })
  140. })
  141. test.describe('the other shared documents', () => {
  142. test.beforeEach(() => {
  143. test.skip(!planted, 'the suite does not share a disk with the app server')
  144. })
  145. test('a quote shows its photo and its document', async ({ browser }) => {
  146. const { context, page } = await customer(browser)
  147. await page.goto(`/share/quote/${organizationId}/${planted?.quoteToken}`)
  148. await expect(page.getByText('estimate.pdf').first()).toBeVisible()
  149. await expectPicturesLoaded(page)
  150. const token = planted?.quoteToken ?? ''
  151. const urls = await publicFileUrls(page)
  152. expect(urls).toEqual(
  153. expect.arrayContaining([
  154. publicUrl(token, plantedUrls.quotePhoto),
  155. publicUrl(token, plantedUrls.quoteDocument),
  156. ])
  157. )
  158. await expectServed(context.request, urls)
  159. await context.close()
  160. })
  161. test('an inspection shows its check photo and its overview photo', async ({ browser }) => {
  162. const { context, page } = await customer(browser)
  163. await page.goto(`/share/inspection/${organizationId}/${planted?.inspectionToken}`)
  164. await expect(page.getByText('Brakes').filter({ visible: true }).first()).toBeVisible()
  165. await expectPicturesLoaded(page)
  166. const token = planted?.inspectionToken ?? ''
  167. const urls = await publicFileUrls(page)
  168. expect(urls).toContain(publicUrl(token, plantedUrls.inspectionOverview))
  169. // The check's own photo opens in the lightbox, which fetches it on a
  170. // click rather than drawing it on the sheet.
  171. await expectServed(context.request, [...urls, publicUrl(token, plantedUrls.inspectionPhoto)])
  172. await context.close()
  173. })
  174. test('a status report plays its video', async ({ browser }) => {
  175. const { context, page } = await customer(browser)
  176. await page.goto(`/share/status-report/${organizationId}/${planted?.reportToken}`)
  177. const token = planted?.reportToken ?? ''
  178. const video = publicUrl(token, plantedUrls.statusVideo)
  179. await expect(page.locator(`source[src="${video}"], video[src="${video}"]`)).toHaveCount(1)
  180. const response = await context.request.get(video)
  181. expect(response.status()).toBe(200)
  182. expect(response.headers()['content-type']).toBe('video/mp4')
  183. await context.close()
  184. })
  185. test('a link opens no file its document does not show', async ({ browser }) => {
  186. const { context } = await customer(browser)
  187. const jobToken = jobShareUrl.split('/').pop() ?? ''
  188. const quoteToken = planted?.quoteToken ?? ''
  189. const inspectionToken = planted?.inspectionToken ?? ''
  190. const reportToken = planted?.reportToken ?? ''
  191. // Each is a real file of this workshop, under a valid link of this
  192. // workshop, and still not the link's to open.
  193. const refused = [
  194. publicUrl(jobToken, plantedUrls.quotePhoto),
  195. publicUrl(quoteToken, plantedUrls.inspectionPhoto),
  196. publicUrl(inspectionToken, plantedUrls.inspectionHidden),
  197. publicUrl(inspectionToken, plantedUrls.statusVideo),
  198. publicUrl(reportToken, plantedUrls.inspectionPhoto),
  199. ]
  200. const missing = await context.request.get(
  201. `/api/public/files/${jobToken}/quotes/${randomUUID()}.png`
  202. )
  203. expect(missing.status()).toBe(404)
  204. const missingBody = await missing.text()
  205. for (const url of refused) {
  206. const response = await context.request.get(url)
  207. expect(response.status(), `${url} is refused`).toBe(404)
  208. expect(await response.text(), 'exactly as a missing file').toBe(missingBody)
  209. }
  210. await context.close()
  211. })
  212. })