Files
ipal-kit/src/modules/forms/attachments/submitHandler.ts
T
2026-11-13 16:24:27 +01:00

294 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'server-only'
import type { BasePayload, PayloadRequest } from 'payload'
import busboy from 'busboy'
import { Readable } from 'node:stream'
import type { FormNotificationTexts } from '../../notifications/types.js'
import type { SubmitActionResult } from '../createSubmitAction.js'
import type { SubmitFormResult } from '../submitForm.js'
import type { FileGate } from './fileGate.js'
import { mailAttachmentLimit } from '../../email/attachmentLimit.js'
import { getNotificationTexts } from '../../notifications/getNotificationTexts.js'
import { resolveFormMessage } from '../../notifications/resolveFormMessage.js'
import { clientIp } from '../../shared/rateLimit.js'
import { HONEYPOT_FIELD, isHoneypotTripped } from '../honeypot.js'
import {
cleanAttemptKey,
fileFailure,
findSubmitAttempt,
passRateLimit,
passTurnstile,
storeSubmission,
validateSubmitFields,
} from '../submitForm.js'
import { getFormAttachments } from './config.js'
import { canCarryFiles } from './delivery.js'
import { createFileGate } from './fileGate.js'
import { MB } from './fileTypes.js'
/** Room for the text parts and the multipart envelope, on top of the files. */
const ENVELOPE_BYTES = 256 * 1024
/** The answers as JSON: every field is capped at 5000 characters by validation; this is the outer ceiling. */
const VALUES_BYTES = 128 * 1024
const STATUS: Record<string, number> = { consent: 422, delivery: 502, error: 500, not_found: 404, rate_limited: 429, turnstile: 403, validation: 422 }
/** File submissions in flight in this process — the concurrency guard. */
let active = 0
/** Attempt keys being handled right now → their outcome, so a duplicate request waits instead of sending twice. */
const inflight = new Map<string, Promise<SubmitFormResult>>()
function originAllowed(req: PayloadRequest, allowed: readonly string[] = []): boolean {
const headers = req.headers
const origin = headers.get('origin')
if (origin && allowed.some((a) => a.replace(/\/$/, '') === origin)) {return true}
const site = headers.get('sec-fetch-site')
if (site) {return site === 'same-origin'}
if (!origin) {return true} // not a browser — the gates below still apply
try {
const host = new URL(origin).host
return host === (headers.get('x-forwarded-host') ?? headers.get('host'))
} catch {
return false
}
}
function localeOf(payload: BasePayload, value: unknown): string | undefined {
if (typeof value !== 'string' || !value) {return undefined}
const localization = payload.config.localization
if (!localization) {return undefined}
return localization.localeCodes.includes(value) ? value : undefined
}
/**
* The submit endpoint for forms with files. The request body is read as a
* stream, and every step runs before the next starts:
*
* origin → rate limit → declared size → concurrency guard → the answers
* (honeypot, Turnstile, validation, consent) → is there an e-mail to carry a
* file → per file: field, count, name → size while reading, signature on the
* first bytes → whole-file checks, scan → e-mail → the buffers are dropped.
*
* After a refusal nothing more is kept: the rest of the body is read and
* thrown away (so the browser gets the answer instead of a broken connection),
* and past the hard ceiling the connection is cut.
*/
export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const { payload } = req
const options = getFormAttachments(payload)
if (!options) {return Response.json({ success: false }, { status: 404 })}
const submit = options.submit
let locale = localeOf(payload, new URL(req.url ?? 'http://localhost').searchParams.get('locale'))
let texts: FormNotificationTexts | undefined
const respond = async (result: SubmitFormResult, status?: number): Promise<Response> => {
texts ??= (await getNotificationTexts({ locale, payload })).form
const body: SubmitActionResult = result.success
? { message: resolveFormMessage(result, texts), success: true }
: {
message: resolveFormMessage(result, texts),
reason: result.reason,
success: false,
...('field' in result && result.field ? { field: result.field } : {}),
}
return Response.json(body, { headers: { 'Cache-Control': 'no-store' }, status: status ?? (result.success ? 200 : (STATUS[result.reason] ?? 400)) })
}
// 1. Same origin, the right kind of request.
if (!originAllowed(req, submit.allowedOrigins)) {return respond({ reason: 'error', success: false }, 403)}
const contentType = req.headers.get('content-type') ?? ''
if (!/^multipart\/form-data/i.test(contentType) || !req.body) {return respond({ reason: 'error', success: false }, 415)}
// 2. Rate limit — from the headers alone, before a byte of the body.
const ip = clientIp(req.headers, submit.clientIp) || undefined
const limited = await passRateLimit({ ip, maxPerMinute: submit.maxPerMinute })
if (limited) {return respond(limited)}
// 3. A body that declares itself too large is refused unread.
const hardCap = Math.floor(options.maxTotalMB * MB) + ENVELOPE_BYTES
const declared = Number(req.headers.get('content-length'))
if (Number.isFinite(declared) && declared > hardCap) {return respond({ reason: 'error', success: false }, 413)}
// 4. Concurrency guard — each file submission holds its files in memory.
if (options.maxConcurrent > 0 && active >= options.maxConcurrent) {return respond({ reason: 'rate_limited', success: false })}
active++
let registered: string | undefined
let settle: ((result: SubmitFormResult) => void) | undefined
let final: SubmitFormResult = { reason: 'error', success: false }
try {
final = await new Promise<SubmitFormResult>((resolve) => {
const fields: Record<string, string> = {}
/** Set once → nothing more is kept; the rest of the body is discarded. */
let outcome: null | SubmitFormResult = null
let gate: FileGate | null = null
let stored: null | Parameters<typeof storeSubmission>[0] = null
let pre: null | Promise<void> = null
let chain: Promise<void> = Promise.resolve()
let received = 0
const source = Readable.fromWeb(req.body as never)
const parser = busboy({
headers: { 'content-type': contentType },
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
})
const stop = (result: SubmitFormResult) => {
outcome ??= result
}
/** 5–8: everything that must hold before the first file byte is accepted. */
const beforeFiles = async () => {
locale = localeOf(payload, fields._locale) ?? locale
const formId = fields._form
let values: unknown
try {
values = JSON.parse(fields._values ?? '')
} catch {
values = null
}
if (!formId || !values || typeof values !== 'object' || Array.isArray(values)) {return stop({ reason: 'error', success: false })}
const data = values as Record<string, unknown>
// Honeypot: a fake success, nothing checked further, nothing kept.
const honeypot = submit.honeypotField ?? HONEYPOT_FIELD
if (isHoneypotTripped(data, honeypot)) {return stop({ submissionId: '', success: true })}
const { [honeypot]: _honeypot, ...answers } = data
const token = fields._token?.trim() || undefined
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
if (blocked) {return stop(blocked)}
const checked = await validateSubmitFields({ data: answers, formId, locale, payload })
if ('failure' in checked) {return stop(checked.failure)}
// A repeated request (same attempt key) gets the first answer; nothing is sent twice.
const attemptKey = cleanAttemptKey(fields._attempt)
if (attemptKey) {
const running = inflight.get(attemptKey)
if (running) {return stop(await running)}
// Registered before the next await, so a twin request arriving now waits for this one.
registered = attemptKey
inflight.set(attemptKey, new Promise<SubmitFormResult>((done) => (settle = done)))
const earlier = await findSubmitAttempt(payload, attemptKey)
if (earlier) {return stop(earlier)}
}
if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })}
gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes: await mailAttachmentLimit(payload) })
stored = { attemptKey, formId, locale, payload, validation: checked.validation }
}
const receiveFile = async (name: string, stream: { truncated?: boolean } & Readable, filename: string) => {
pre ??= beforeFiles()
await pre
if (outcome || !gate || !stored) {return void stream.resume()}
const { formId } = stored
const refuse = async (failure: Parameters<typeof fileFailure>[2]) => stop(await fileFailure(payload, formId, failure, locale))
// 9–10. Field, count and name — before any byte of this file.
const started = gate.begin(name, filename)
if ('failure' in started) {
stream.resume()
return refuse(started.failure)
}
const { slot, token } = started
let chunks: Buffer[] = []
let size = 0
let headChecked = false
for await (const chunk of stream as AsyncIterable<Buffer>) {
if (outcome) {continue} // refused: read on and keep nothing
size += chunk.length
// 11. Size, counted while reading.
if (size > slot.maxBytes) {
chunks = []
await refuse(slot.tooLarge())
continue
}
chunks.push(chunk)
// 12. Signature, as soon as the first bytes are here.
if (!headChecked && size >= 16) {
headChecked = true
const wrong = slot.checkStart(chunks.length === 1 ? chunk : Buffer.concat(chunks))
if (wrong) {
chunks = []
await refuse(wrong)
}
}
}
if (outcome) {return}
if (stream.truncated) {return refuse(slot.tooLarge())}
// 13–14. Whole-file checks and the optional scan.
const failure = await gate.finish(token, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
if (failure) {await refuse(failure)}
}
parser.on('field', (name, value, info) => {
if (info.valueTruncated || info.nameTruncated) {return stop({ reason: 'error', success: false })}
fields[name] = value
})
parser.on('file', (name, stream, info) => {
chain = chain.then(() => receiveFile(name, stream, info.filename ?? '')).catch((err) => {
stream.resume()
payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
})
})
for (const event of ['fieldsLimit', 'filesLimit', 'partsLimit'] as const) {
parser.on(event, () => stop({ kind: 'unknown_fields', reason: 'validation', success: false }))
}
const finish = async () => {
try {
await chain
if (!outcome) {
pre ??= beforeFiles() // a request without a file part still runs every gate
await pre
}
if (!outcome && gate && stored) {
const missing = (gate as FileGate).end()
if (missing) {stop(await fileFailure(payload, (stored as { formId: string }).formId, missing, locale))}
}
// 15. Store the answers and the file metadata, e-mail the files, drop the buffers.
if (!outcome && gate && stored) {stop(await storeSubmission({ ...(stored as Parameters<typeof storeSubmission>[0]), files: (gate as FileGate).accepted }))}
} catch (err) {
payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
}
resolve(outcome ?? { reason: 'error', success: false })
}
let done = false
const once = (run: () => void) => () => {
if (done) {return}
done = true
run()
}
parser.on('close', once(() => void finish()))
const broken = once(() => {
stop({ reason: 'error', success: false })
void finish()
})
parser.on('error', broken)
source.on('error', broken)
// Hard ceiling on what is read at all, whatever Content-Length said.
source.on('data', (chunk: Buffer) => {
received += chunk.length
if (received > hardCap) {
stop({ reason: 'error', success: false })
source.destroy(new Error('request body over the limit'))
}
})
source.pipe(parser)
})
} finally {
active--
if (registered) {inflight.delete(registered)}
settle?.(final)
}
return respond(final)
}