Co-Authored-By: Claude Fable 5.2 <[email protected]>
167 lines
6.4 KiB
TypeScript
167 lines
6.4 KiB
TypeScript
import type { FileFieldConfig, ResolvedFormAttachments } from './config.js'
|
|
|
|
import { fileFieldLimits } from './config.js'
|
|
import { checkFileContent, looksExecutable, matchFileType, SIGNATURE_BYTES, signatureMatches } from './fileChecks.js'
|
|
import { describeFileTypes, MB, safeFileName, UNSAFE_NAME_CHARACTERS } from './fileTypes.js'
|
|
|
|
/** A file that passed every check — in memory, ready for the e-mail. */
|
|
export type AcceptedFormFile = {
|
|
data: Uint8Array
|
|
/** Field key of the File field. */
|
|
field: string
|
|
mimeType: string
|
|
/** Cleaned name with the extension of the detected type. */
|
|
name: string
|
|
size: number
|
|
/** Type key, e.g. 'pdf'. */
|
|
type: string
|
|
}
|
|
|
|
/** Why a file was refused — a code for resolveFormMessage, never text. */
|
|
export type FormFileFailure = {
|
|
field: string
|
|
/** The file's name as the visitor knows it (cleaned of control characters). */
|
|
file?: string
|
|
kind: 'file_count' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
|
|
/** The limit: MB for file_too_large, a count for file_count. */
|
|
max?: number
|
|
/** "PDF, DOC, DOCX" — for file_type. */
|
|
types?: string
|
|
}
|
|
|
|
type FileField = { name: string; required?: boolean | null } & FileFieldConfig
|
|
|
|
/** One file being received. */
|
|
export type FileSlot = {
|
|
/** Feed the first bytes as they arrive (any chunking). Returns a failure as soon as the signature is wrong. */
|
|
checkStart: (head: Uint8Array) => FormFileFailure | null
|
|
/** Bytes this file may have; reading must stop past it. */
|
|
maxBytes: number
|
|
/** Call when a read went past `maxBytes`. */
|
|
tooLarge: () => FormFileFailure
|
|
}
|
|
|
|
const displayName = (name: string) => (name.split(/[/\\]/).pop() ?? '').replace(UNSAFE_NAME_CHARACTERS, '').slice(0, 120)
|
|
|
|
/** A limit in MB for a message: whole number, or one decimal rounded DOWN (never promise more). */
|
|
export const limitInMB = (bytes: number) => {
|
|
const mb = bytes / MB
|
|
return Number.isInteger(mb) ? mb : Math.floor(mb * 10) / 10
|
|
}
|
|
|
|
/**
|
|
* The file checks of one submission, in the order the wall needs them:
|
|
* `begin` (field, count, name — before any byte), the slot (size while reading,
|
|
* signature on the first bytes), `finish` (whole-file checks, scan), `end`
|
|
* (required fields). Used by the streaming endpoint and, with whole buffers,
|
|
* by submitForm({ files }).
|
|
*/
|
|
export function createFileGate({
|
|
fields,
|
|
options,
|
|
transportMaxBytes,
|
|
}: {
|
|
/** The form's File fields the visitor could see. */
|
|
fields: FileField[]
|
|
options: ResolvedFormAttachments
|
|
/** What the e-mail transport can carry, when it has a ceiling. */
|
|
transportMaxBytes?: null | number
|
|
}) {
|
|
const byName = new Map(fields.map((f) => [f.name, f]))
|
|
const counts = new Map<string, number>()
|
|
const accepted: AcceptedFormFile[] = []
|
|
let total = 0
|
|
|
|
const begin = (fieldName: string, rawName: string): { failure: FormFileFailure } | { slot: FileSlot; token: BeginToken } => {
|
|
const field = byName.get(fieldName)
|
|
if (!field) {return { failure: { field: fieldName, kind: 'unknown_fields' } }}
|
|
const limits = fileFieldLimits(field, options, transportMaxBytes)
|
|
const file = displayName(rawName)
|
|
const count = (counts.get(fieldName) ?? 0) + 1
|
|
counts.set(fieldName, count)
|
|
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles } }}
|
|
|
|
const types = describeFileTypes(limits.allowedTypes, options.types).labels
|
|
const typeFailure: FormFileFailure = { field: fieldName, file, kind: 'file_type', types }
|
|
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
|
|
if ('refused' in match) {return { failure: typeFailure }}
|
|
|
|
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
|
|
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes) })
|
|
let checked = false
|
|
return {
|
|
slot: {
|
|
checkStart: (head) => {
|
|
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
|
|
checked = true
|
|
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? typeFailure : null
|
|
},
|
|
maxBytes,
|
|
tooLarge,
|
|
},
|
|
token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure },
|
|
}
|
|
}
|
|
|
|
const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => {
|
|
if (data.length > token.maxBytes) {return token.tooLarge()}
|
|
const type = options.types[token.key]
|
|
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.typeFailure}
|
|
const file: AcceptedFormFile = {
|
|
name: safeFileName(token.rawName, type.extensions[0]),
|
|
type: token.key,
|
|
data,
|
|
field: token.field,
|
|
mimeType: type.mimeType,
|
|
size: data.length,
|
|
}
|
|
if (options.scan) {
|
|
try {
|
|
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
|
|
if (!verdict?.ok) {return token.typeFailure}
|
|
} catch {
|
|
return token.typeFailure
|
|
}
|
|
}
|
|
total += data.length
|
|
accepted.push(file)
|
|
return null
|
|
}
|
|
|
|
/** After the last file: a required File field without a file. */
|
|
const end = (): FormFileFailure | null => {
|
|
for (const field of fields) {
|
|
if (field.required && !accepted.some((f) => f.field === field.name)) {return { field: field.name, kind: 'required' }}
|
|
}
|
|
return null
|
|
}
|
|
|
|
return { accepted, begin, end, finish }
|
|
}
|
|
|
|
type BeginToken = {
|
|
field: string
|
|
file: string
|
|
key: string
|
|
maxBytes: number
|
|
rawName: string
|
|
tooLarge: () => FormFileFailure
|
|
typeFailure: FormFileFailure
|
|
}
|
|
|
|
export type FileGate = ReturnType<typeof createFileGate>
|
|
|
|
/** Whole buffers through the same checks, in order. */
|
|
export async function checkBufferedFiles(gate: FileGate, files: Record<string, { data: Uint8Array; name: string }[]>): Promise<FormFileFailure | null> {
|
|
for (const [field, list] of Object.entries(files)) {
|
|
for (const file of list) {
|
|
const started = gate.begin(field, file.name)
|
|
if ('failure' in started) {return started.failure}
|
|
if (file.data.length > started.slot.maxBytes) {return started.slot.tooLarge()}
|
|
const failure = started.slot.checkStart(file.data.subarray(0, 64)) ?? (await gate.finish(started.token, file.data))
|
|
if (failure) {return failure}
|
|
}
|
|
}
|
|
return gate.end()
|
|
}
|