Files
ipal-kit/src/modules/forms/attachments/fileGate.ts
T
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00

179 lines
7.3 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
/**
* - `file_too_large` — over the limit (`max`, MB)
* - `file_type` — a format the field does not accept (`types`)
* - `file_refused` — the right extension but not acceptable: the content does not match it, macros, a
* program, an archive, a doubled extension, or the project's scanner said no
* - `file_count` — more files than the field takes (`max`)
*/
kind: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
/** The limit: MB for file_too_large, a count for file_count. */
max?: number
/** True when the field is not required — the visitor may send the form without the file. */
optional?: boolean
/** "PDF, DOC, DOCX" — the formats the field accepts. */
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)
const optional = !field.required
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles, optional } }}
const types = describeFileTypes(limits.allowedTypes, options.types).labels
const refusedFailure: FormFileFailure = { field: fieldName, file, kind: 'file_refused', optional, types }
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
if ('refused' in match) {return { failure: match.refused === 'type' ? { ...refusedFailure, kind: 'file_type' } : refusedFailure }}
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
// The limit the message names is what this file may really have: the per-file limit, or what is left of
// the submission's total when other files used part of it (the whole total when nothing is left).
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(maxBytes > 0 ? maxBytes : limits.maxTotalBytes), optional })
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 ? refusedFailure : null
},
maxBytes,
tooLarge,
},
token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
}
}
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.refusedFailure}
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.refusedFailure}
} catch {
return token.refusedFailure
}
}
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
refusedFailure: FormFileFailure
tooLarge: () => 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()
}