All files / src/server/files upload.ts

100% Statements 26/26
100% Branches 17/17
100% Functions 6/6
100% Lines 24/24

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63          10x               10x   10x 10x       10x       371x   81x       64x 23x   41x 1x   40x 1x   39x 30x   9x               61x 2x   59x 4x   55x 55x 4x   51x    
// Checks an uploaded file before it is stored. The type comes from the
// file's first bytes, not from the browser's Content-Type or the file name,
// so a renamed file can't pass as a receipt image.
 
/** Uploads above this are refused (receipts are resized in the browser). */
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024
 
export type UploadType =
  'image/jpeg' | 'image/png' | 'image/webp' | 'application/pdf'
 
export type UploadProblem = 'empty' | 'too_large' | 'unsupported_type'
 
export class UploadError extends Error {
  override name = 'UploadError'
 
  constructor(readonly problem: UploadProblem) {
    super(`Upload refused: ${problem}`)
  }
}
 
const startsWith = (
  bytes: Uint8Array,
  signature: ArrayLike<number>,
  offset = 0,
) => Array.from(signature).every((byte, i) => bytes[offset + i] === byte)
 
const ascii = (text: string) => new TextEncoder().encode(text)
 
/** The file type by its signature ("magic bytes"), if it is one we accept. */
export function detectType(bytes: Uint8Array): UploadType | undefined {
  if (startsWith(bytes, [0xff, 0xd8, 0xff])) {
    return 'image/jpeg'
  }
  if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
    return 'image/png'
  }
  if (startsWith(bytes, ascii('RIFF')) && startsWith(bytes, ascii('WEBP'), 8)) {
    return 'image/webp'
  }
  if (startsWith(bytes, ascii('%PDF-'))) {
    return 'application/pdf'
  }
  return undefined
}
 
/** The checked type and size of an upload, or an UploadError. */
export function checkUpload(bytes: Uint8Array): {
  contentType: UploadType
  size: number
} {
  if (bytes.byteLength === 0) {
    throw new UploadError('empty')
  }
  if (bytes.byteLength > MAX_UPLOAD_BYTES) {
    throw new UploadError('too_large')
  }
  const contentType = detectType(bytes)
  if (!contentType) {
    throw new UploadError('unsupported_type')
  }
  return { contentType, size: bytes.byteLength }
}