All files / src/features/documents document-response.server.ts

100% Statements 14/14
100% Branches 8/8
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                                  1x 4x                   6x 1x   5x 5x 1x   4x 4x 1x   3x 3x 1x   2x          
// Serves a document's file after checking that the signed-in user has access
// to its flat (openspec: documents, "Viewing and downloading a document").
// Everything else is 404, so the address reveals nothing: no session, no
// document, no access, or a file missing from storage.
import type { SharingRepository } from '#/features/sharing/sharing.repository.server'
import { fileResponse } from '#/server/files/response'
import type { FileStorage } from '#/server/files/storage'
import type { DocumentRepository } from './document.repository.server'
 
export interface DocumentResponseDeps {
  /** The signed-in user, if any. */
  userId: string | undefined
  documents: DocumentRepository
  sharing: SharingRepository
  storage: FileStorage
}
 
const notFound = () =>
  new Response('Not found', {
    status: 404,
    headers: { 'Cache-Control': 'private, no-store' },
  })
 
export async function documentResponse(
  deps: DocumentResponseDeps,
  documentId: string,
  options: { download: boolean },
): Promise<Response> {
  if (!deps.userId) {
    return notFound()
  }
  const document = await deps.documents.findForAccess(documentId)
  if (!document) {
    return notFound()
  }
  const role = await deps.sharing.roleOf(deps.userId, document.propertyId)
  if (!role) {
    return notFound()
  }
  const file = await deps.storage.get(document.key)
  if (!file) {
    return notFound()
  }
  return fileResponse(file, {
    filename: document.filename,
    download: options.download,
  })
}