diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index a177cf8..6eb4f5d 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -18,7 +18,9 @@ once there are more than 20.
the submission keeps the file's name, type and size and whether the mail server took the message.
- **Checks, in order, before a file is accepted:** same origin, rate limit, declared size, a concurrency guard,
honeypot, Turnstile, field validation and GDPR consent, then per file: count, name (double and refused
- extensions), size while reading, content signature, container and macro checks. Programs, scripts,
+ extensions), size while reading, content signature, container and macro checks. An upload that breaks off,
+ stalls (`submit.idleTimeoutMs`, 30 s) or runs too long (`submit.timeoutMs`, 5 minutes) is given up and frees
+ everything it held. Programs, scripts,
macro-enabled Office files, archives, HTML and SVG are refused unless the project allows the extension
(`allowRisky`). **No antivirus is built in** — `attachments.scan` is the hook for one.
- **E-mail:** the file goes to every e-mail of the form whose recipients are fixed addresses from the panel; an
diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md
index c25aad9..5a2dc9a 100644
--- a/docs/agent/skills/ipal-form/SKILL.md
+++ b/docs/agent/skills/ipal-form/SKILL.md
@@ -90,7 +90,8 @@ Never build this by hand (your own ``, upload route or upload
1. Config: `forms: { attachments: true }` (defaults: 10 MB per file and per submission, at most 3 files per field).
Options (`FormAttachmentsOption`): `maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes` (add / replace / `false`),
`allowRisky`, `scan` (antivirus hook), `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`
- (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`).
+ (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`,
+ `idleTimeoutMs` 30 s, `timeoutMs` 5 min — a stalled or dropped upload is given up and frees its slot).
Postgres: `pnpm payload migrate:create`; then `pnpm generate:types`.
2. Form: a **File** field — in the seed
`{ blockType: 'file', name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], maxSizeMB: 10, maxFiles: 1, label: {…}, help: {…} }`
diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md
index 51abbcc..1d9b900 100644
--- a/docs/agent/skills/ipal-reference/SKILL.md
+++ b/docs/agent/skills/ipal-reference/SKILL.md
@@ -68,7 +68,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
-| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
+| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles |
diff --git a/docs/deployment.md b/docs/deployment.md
index 8e88aeb..c7a0ea5 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -411,7 +411,9 @@ Files on forms are e-mailed, not stored — **no volume and no bucket** for them
- **Time.** The request stays open while the file uploads and the e-mail is sent. On a slow connection a 10 MB
upload can take over a minute — check the proxy's read timeout (Traefik: `respondingTimeouts.readTimeout` of the
entry point) if visitors on mobile networks report failures. Not measured by the plugin's tests; verify once on
- the real server with a throttled upload.
+ the real server with a throttled upload. The plugin itself gives an upload up after 30 s without a byte and
+ after 5 minutes in total (`attachments.submit.idleTimeoutMs` / `timeoutMs`), so a dropped connection never
+ holds a slot.
- **Memory.** A file is held in memory while it is checked and sent (about 2.4 × its size); at most two file
submissions run at once per instance (`attachments.maxConcurrent`).
- **Mail.** Send the test e-mail with the 10 MB file after every change of mail provider
diff --git a/docs/forms.md b/docs/forms.md
index 91b2e58..535b52b 100644
--- a/docs/forms.md
+++ b/docs/forms.md
@@ -227,7 +227,7 @@ the File field shows "The file … was refused: …", nothing is stored or sent.
| `notice` | built-in text | the "not checked for viruses" line in the e-mail: `false` = none, a string or `(locale) => string` = your own |
| `maxConcurrent` | `2` | file submissions handled at once per instance (each holds its files in memory); more get the "too many attempts" message; `0` = no guard |
| `path` | `'/ipal/forms/submit'` | endpoint path under the API route |
-| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, and `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain) |
+| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) |
Built-in types (`FORM_FILE_TYPES`): PDF, DOC, DOCX, ODT, RTF, XLS, XLSX, JPG, PNG, WebP. A new field has PDF, DOC and
DOCX ticked.
@@ -255,6 +255,12 @@ Each step runs before the next; a failure ends the request and nothing after it
11. `scan`, when the project provides one.
12. The e-mail is sent, the buffers are released.
+**An upload that breaks off, stalls or never ends** is given up at once: the connection dropped (400), no byte
+arrived for `submit.idleTimeoutMs` (408), the whole request ran past `submit.timeoutMs` (408), or a body without a
+declared length went over the ceiling (413 — the read stops there). On every way out the endpoint lets go of what
+it held: the buffered bytes, its slot in the concurrency guard and the attempt key, so the next upload — and the
+browser's retry — work.
+
**Refused by default whatever the field allows** (`RISKY_FILE_EXTENSIONS`): programs and scripts (`exe`, `dll`,
`msi`, `bat`, `js`, `ps1`, `sh`, `jar`…), macro-enabled Office files (`docm`, `xlsm`, `pptm`…), archives and disk
images (`zip`, `rar`, `7z`, `iso`…), HTML, SVG and XML.
diff --git a/src/modules/email/graphAttachments.ts b/src/modules/email/graphAttachments.ts
index f20ff27..0a1a981 100644
--- a/src/modules/email/graphAttachments.ts
+++ b/src/modules/email/graphAttachments.ts
@@ -100,7 +100,8 @@ const permissionDetail =
*/
export async function sendLargeGraphMail(attachments: GraphAttachment[], { cleanupDelaysMs = [2000, 5000, 15_000, 60_000], fetchImpl, log, message, sender, token }: LargeArgs): Promise {
const base = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(sender)}`
- const auth = { Authorization: `Bearer ${token}` }
+ // Every call on the draft asks for (and addresses it by) its immutable id — the id that survives the move to Sent Items.
+ const auth = { Authorization: `Bearer ${token}`, Prefer: 'IdType="ImmutableId"' }
const json = { ...auth, 'Content-Type': 'application/json' }
const describe = async (res: Response) => `${res.status} ${(await res.text().catch(() => '')).slice(0, 300)}`
@@ -121,7 +122,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean
// An immutable id stays the same when the draft moves to Sent Items — that is how the copy is found again.
const created = await fetchImpl(`${base}/messages`, {
body: JSON.stringify(message),
- headers: { ...json, Prefer: 'IdType="ImmutableId"' },
+ headers: json,
method: 'POST',
})
if (created.status === 401 || created.status === 403) {
@@ -180,7 +181,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean
for (const delay of cleanupDelaysMs) {
await sleep(delay)
try {
- const look = await fetchImpl(`${base}/messages/${encodeURIComponent(sentId)}?$select=isDraft`, { headers: { ...auth, Prefer: 'IdType="ImmutableId"' } })
+ const look = await fetchImpl(`${base}/messages/${encodeURIComponent(sentId)}?$select=isDraft`, { headers: auth })
if (look.status === 404) {return 'deleted'}
if (look.ok && ((await look.json()) as { isDraft?: boolean }).isDraft === false) {
if (await remove(sentId)) {return 'deleted'}
diff --git a/src/modules/forms/attachments/config.ts b/src/modules/forms/attachments/config.ts
index f8d2a5a..7a5af65 100644
--- a/src/modules/forms/attachments/config.ts
+++ b/src/modules/forms/attachments/config.ts
@@ -71,8 +71,18 @@ export type FormSubmitEndpointOptions = {
clientIp?: ClientIpOptions
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
+ /**
+ * A stalled upload: no byte of the request body for this long (ms) and the request is given up (408).
+ * Default 30000; 0 = no idle limit.
+ */
+ idleTimeoutMs?: number
/** Max submissions per IP per minute. Default 5; 0 turns it off. */
maxPerMinute?: number
+ /**
+ * Ceiling for the whole request — upload, checks and e-mail (ms). Past it the request is answered 408 and
+ * everything it held is released. Default 300000 (5 minutes); 0 = no ceiling.
+ */
+ timeoutMs?: number
turnstileHostnames?: string[]
turnstileOnConfigError?: 'allow' | 'reject'
}
diff --git a/src/modules/forms/attachments/fileGate.ts b/src/modules/forms/attachments/fileGate.ts
index dee2be3..72838ee 100644
--- a/src/modules/forms/attachments/fileGate.ts
+++ b/src/modules/forms/attachments/fileGate.ts
@@ -97,7 +97,9 @@ export function createFileGate({
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))
- const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes), optional })
+ // 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: {
diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts
index 5383f36..bcc3719 100644
--- a/src/modules/forms/attachments/submitHandler.ts
+++ b/src/modules/forms/attachments/submitHandler.ts
@@ -41,6 +41,14 @@ let active = 0
/** Attempt keys being handled right now → their outcome, so a duplicate request waits instead of sending twice. */
const inflight = new Map>()
+/** No byte of the body for this long → the upload is given up (a stalled or dropped connection). */
+const IDLE_TIMEOUT_MS = 30_000
+/** The whole request — upload, checks and e-mail — may take this long. */
+const REQUEST_TIMEOUT_MS = 300_000
+
+/** What the endpoint is holding right now — for monitoring and tests: both are 0 when nothing is in flight. */
+export const formSubmitState = () => ({ active, inflight: inflight.size })
+
function originAllowed(req: PayloadRequest, allowed: readonly string[] = []): boolean {
const headers = req.headers
const origin = headers.get('origin')
@@ -75,6 +83,11 @@ function localeOf(payload: BasePayload, value: unknown): string | undefined {
* 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.
+ *
+ * A body that breaks off, stalls (`submit.idleTimeoutMs`) or runs past the
+ * request ceiling (`submit.timeoutMs`) is aborted: streams torn down, buffers
+ * dropped, the request answered. On EVERY way out the slot of the concurrency
+ * guard and the attempt key are released.
*/
export async function handleFormSubmit(req: PayloadRequest): Promise {
const { payload } = req
@@ -119,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
let registered: string | undefined
let settle: ((result: SubmitFormResult) => void) | undefined
let final: SubmitFormResult = { reason: 'error', success: false }
+ /** HTTP status of an aborted request (413 over the ceiling, 408 timed out, 400 broken body). */
+ let abortStatus: number | undefined
try {
final = await new Promise((resolve) => {
const fields: Record = {}
@@ -142,6 +157,44 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
outcome ??= result
}
+ /** File parts not read to their end yet — torn down when the request is aborted. */
+ const open = new Set()
+ let settled = false
+ /** The parser reached the end of the body, or the request was aborted — no second ending. */
+ let done = false
+ /** The submission is being stored and e-mailed: its files must stay until that is over. */
+ let storing = false
+ let idleTimer: ReturnType | undefined
+ let requestTimer: ReturnType | undefined
+ /** The one way out: answers the request and stops the timers. Later calls do nothing. */
+ const conclude = (result: SubmitFormResult) => {
+ if (settled) {return}
+ settled = true
+ clearTimeout(idleTimer)
+ clearTimeout(requestTimer)
+ resolve(result)
+ }
+ /**
+ * Gives the request up NOW — a body that broke off (the visitor's connection dropped), stalled, or went
+ * over the ceiling. Waiting for the parser would wait forever: a file part of a broken body never ends.
+ * So everything is torn down here — the file streams (their read loops throw and let go of what they
+ * hold), the parser, the body — the buffers are dropped, and the request is answered. The slot of the
+ * concurrency guard and the attempt key are released by the `finally` below, as on every other way out.
+ */
+ const abort = (status: number) => {
+ if (settled) {return}
+ done = true
+ stop({ reason: 'error', success: false })
+ abortStatus = status
+ source.unpipe(parser)
+ for (const stream of open) {stream.destroy(new Error('upload aborted'))}
+ open.clear()
+ parser.destroy()
+ source.destroy()
+ if (gate && !storing) {gate.accepted.length = 0}
+ conclude(outcome ?? { reason: 'error', success: false })
+ }
+
/** 5–8: everything that must hold before the first file byte is accepted. */
const beforeFiles = async () => {
locale = localeOf(payload, fields._locale) ?? locale
@@ -201,6 +254,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
let chunks: Buffer[] = []
let size = 0
let headChecked = false
+ // An aborted request destroys this stream: the loop throws and `chunks` goes with it.
for await (const chunk of stream as AsyncIterable) {
if (outcome) {continue} // refused: read on and keep nothing
size += chunk.length
@@ -221,6 +275,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
}
}
}
+ open.delete(stream)
if (outcome) {return}
if (stream.truncated) {return refuse(slot.tooLarge())}
// 13–14. Whole-file checks and the optional scan.
@@ -233,7 +288,11 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
fields[name] = value
})
parser.on('file', (name, stream, info) => {
+ open.add(stream)
+ stream.on('error', () => undefined) // a torn-down part must not become an unhandled stream error
chain = chain.then(() => receiveFile(name, stream, info.filename ?? '')).catch((err) => {
+ open.delete(stream)
+ if (settled) {return} // aborted: already answered, nothing to add
stream.resume()
payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
@@ -255,34 +314,45 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
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), files: (gate).accepted }))}
+ if (!outcome && !settled && gate && stored) {
+ storing = true
+ stop(await storeSubmission({ ...(stored), files: (gate).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 })
+ conclude(outcome ?? { reason: 'error', success: false })
}
- let done = false
- const once = (run: () => void) => () => {
+ parser.on('close', () => {
if (done) {return}
done = true
- run()
- }
- parser.on('close', once(() => void finish()))
- const broken = once(() => {
- stop({ reason: 'error', success: false })
void finish()
})
+ // A body that breaks off mid-upload (or a parser error) never reaches 'close' on its own: abort.
+ const broken = () => {
+ if (!done) {abort(400)}
+ }
parser.on('error', broken)
source.on('error', broken)
- // Hard ceiling on what is read at all, whatever Content-Length said.
+
+ // A stalled upload: no byte for too long while the body is still coming. And a ceiling on the whole request.
+ const idleMs = submit.idleTimeoutMs ?? IDLE_TIMEOUT_MS
+ const requestMs = submit.timeoutMs ?? REQUEST_TIMEOUT_MS
+ const watchIdle = () => {
+ clearTimeout(idleTimer)
+ if (idleMs > 0 && !settled && !done) {idleTimer = setTimeout(() => !done && abort(408), idleMs)}
+ }
+ watchIdle()
+ if (requestMs > 0) {requestTimer = setTimeout(() => abort(408), requestMs)}
+ source.on('end', () => clearTimeout(idleTimer)) // the body is in; from here only the request ceiling applies
+
source.on('data', (chunk: Buffer) => {
+ watchIdle()
+ // Hard ceiling on what is read at all, whatever Content-Length said (or did not say: a chunked body).
received += chunk.length
- if (received > hardCap) {
- stop({ reason: 'error', success: false })
- source.destroy(new Error('request body over the limit'))
- }
+ if (received > hardCap) {abort(413)}
})
source.pipe(parser)
})
@@ -291,5 +361,5 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
if (registered) {inflight.delete(registered)}
settle?.(final)
}
- return respond(final)
+ return respond(final, abortStatus)
}
diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts
index bf9f5b7..01fb9d4 100644
--- a/src/modules/forms/submitForm.ts
+++ b/src/modules/forms/submitForm.ts
@@ -366,9 +366,17 @@ export async function submitForm(args: SubmitFormArgs): Promise list.length > 0)
const attachments = getFormAttachments(payload)
- if (!attachments || (!hasFiles && validation.fileFields.length === 0)) {
+ if (!attachments || validation.fileFields.length === 0) {
// A file without the feature (or without a File field) is an unknown field.
- if (hasFiles) {return { kind: 'unknown_fields', reason: 'validation', success: false }}
+ if (hasFiles) {
+ // Never dropped silently: the caller sent files this site (or this form) does not take.
+ payload.logger.warn(
+ attachments
+ ? `[ipal] submitForm: files were sent to form ${formId}, which has no File field — refused.`
+ : '[ipal] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in ipalKit({ forms: { attachments: true } }).',
+ )
+ return { kind: 'unknown_fields', reason: 'validation', success: false }
+ }
return storeSubmission({ attemptKey, formId, locale, payload, validation })
}
diff --git a/test/emailAttachments.test.ts b/test/emailAttachments.test.ts
index aa75b63..5ac0aa7 100644
--- a/test/emailAttachments.test.ts
+++ b/test/emailAttachments.test.ts
@@ -216,7 +216,10 @@ describe('attachments', () => {
])
// The draft is addressed and labelled like any message, and asks for an id that survives the move to Sent Items.
expect(graph.calls[0].body).toMatchObject({ subject: 'Application', toRecipients: [{ emailAddress: { address: 'jobs@example.com' } }] })
- expect(graph.calls[0].headers.Prefer).toBe('IdType="ImmutableId"')
+ // every call on the draft carries the immutable-id preference (the pre-authenticated upload URL takes no headers of ours)
+ const onGraph = graph.calls.filter((c) => c.url.startsWith('https://graph.microsoft.com/'))
+ expect(onGraph.length).toBeGreaterThanOrEqual(6)
+ expect(onGraph.every((c) => c.headers.Prefer === 'IdType="ImmutableId"')).toBe(true)
expect((graph.calls[1].body as { AttachmentItem: unknown }).AttachmentItem).toMatchObject({ name: 'cv.pdf', attachmentType: 'file', size: 10 * MB })
// Every byte, in order, in pieces under 4 MB, without the bearer token on the pre-authenticated URL.
expect(Buffer.compare(Buffer.concat(graph.uploaded), bytes(10 * MB))).toBe(0)
diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts
index 953fff2..6d5a4f8 100644
--- a/test/formAttachments.test.ts
+++ b/test/formAttachments.test.ts
@@ -20,7 +20,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vite
import type { FormFileScanInput } from '../src/modules/forms/attachments/config.js'
import { getFormAttachments } from '../src/modules/forms/attachments/config.js'
-import { handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
+import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
@@ -738,7 +738,7 @@ describe('options a project can set', () => {
await slowScan
return { ok: true }
},
- submit: { allowedOrigins: ['https://app.example'], maxPerMinute: 0 },
+ submit: { allowedOrigins: ['https://app.example'], idleTimeoutMs: 300, maxPerMinute: 0, timeoutMs: 1500 },
},
},
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
@@ -801,4 +801,154 @@ describe('options a project can set', () => {
expect((await first).status).toBe(200)
expect((await send([{ name: 'cv.pdf', data: PDF }])).status).toBe(200) // the slot is free again
})
+
+ // ---- uploads that break off, never end, or stall (security review of 1.16.0) ----------------------------
+ // The request body is built by hand, so the test decides what arrives and when — like a real connection.
+ const BOUNDARY = 'ipalTestBoundary'
+ const part = (name: string, value: string) => `--${BOUNDARY}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`
+ const prelude = (attempt?: string) =>
+ Buffer.from(
+ `${part('_form', otherForm)}${attempt ? part('_attempt', attempt) : ''}${part('_values', '{}')}` +
+ `--${BOUNDARY}\r\nContent-Disposition: form-data; name="files"; filename="cv.pdf"\r\nContent-Type: application/pdf\r\n\r\n`,
+ )
+ const closing = Buffer.from(`\r\n--${BOUNDARY}--\r\n`)
+ const raw = (body: ReadableStream) => {
+ const request = new Request('http://localhost/api/custom/files', {
+ body,
+ duplex: 'half',
+ headers: { 'content-type': `multipart/form-data; boundary=${BOUNDARY}`, 'sec-fetch-site': 'same-origin' },
+ method: 'POST',
+ } as RequestInit)
+ return handleFormSubmit(Object.assign(request, { payload: other }) as unknown as PayloadRequest)
+ }
+ const within = (promise: Promise, ms: number) =>
+ Promise.race([promise, new Promise<'HUNG'>((resolve) => setTimeout(() => resolve('HUNG'), ms))])
+ /** Nothing is held, and the endpoint still works: a normal upload goes through (also with the same attempt key). */
+ const backToNormal = async (attempt?: string) => {
+ expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
+ const whole = new ReadableStream({
+ start(controller) {
+ controller.enqueue(Buffer.concat([prelude(attempt), PDF, closing]))
+ controller.close()
+ },
+ })
+ const response = await within(raw(whole), 5000)
+ expect(response).not.toBe('HUNG')
+ expect((response as Response).status).toBe(200)
+ expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
+ }
+
+ test('the connection drops in the middle of a file: the request ends, nothing stays held, the retry works', async () => {
+ const before = (await other.count({ collection: 'form-submissions' as never })).totalDocs
+ const attempt = 'attempt-dropped-00000001'
+ const dropped = new ReadableStream({
+ start(controller) {
+ controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)]))
+ setTimeout(() => controller.error(new Error('ECONNRESET')), 50)
+ },
+ })
+ const response = await within(raw(dropped), 3000)
+ expect(response).not.toBe('HUNG')
+ expect((response as Response).status).toBe(400)
+ expect((await other.count({ collection: 'form-submissions' as never })).totalDocs).toBe(before)
+ await backToNormal(attempt) // the browser's retry with the same attempt key is not left waiting
+ })
+
+ test('two dropped uploads do not use up the concurrency slots (maxConcurrent: 1 here)', async () => {
+ for (let i = 0; i < 2; i++) {
+ const dropped = new ReadableStream({
+ start(controller) {
+ controller.enqueue(Buffer.concat([prelude(), PDF.subarray(0, 500)]))
+ setTimeout(() => controller.error(new Error('ECONNRESET')), 20)
+ },
+ })
+ expect(await within(raw(dropped), 3000)).not.toBe('HUNG')
+ }
+ await backToNormal() // 200, not "too many attempts"
+ })
+
+ test('a chunked body with no declared length that never stops: cut off at the ceiling', async () => {
+ let sent = 0
+ let cancelled = false
+ const megabyte = Buffer.alloc(MB, 0x20)
+ const endless = new ReadableStream({
+ cancel() {
+ cancelled = true
+ },
+ pull(controller) {
+ controller.enqueue(sent === 0 ? Buffer.concat([prelude('attempt-endless-00000001'), Buffer.from('%PDF-1.7\n')]) : megabyte)
+ sent++
+ },
+ })
+ const response = await within(raw(endless), 10_000)
+ expect(response).not.toBe('HUNG')
+ expect((response as Response).status).toBe(413)
+ expect(cancelled).toBe(true) // the plugin stopped reading; it did not drain an endless body
+ expect(sent).toBeLessThan(20) // about 10 MB + the envelope, not more
+ await backToNormal('attempt-endless-00000001')
+ }, 20_000)
+
+ test('a stalled upload (no bytes, connection open) is given up after the idle timeout', async () => {
+ const stalled = new ReadableStream({
+ start(controller) {
+ controller.enqueue(Buffer.concat([prelude('attempt-stalled-00000001'), PDF.subarray(0, 1000)]))
+ // …and then nothing: never closed, never errored
+ },
+ })
+ const started = Date.now()
+ const response = await within(raw(stalled), 5000)
+ expect(response).not.toBe('HUNG')
+ expect((response as Response).status).toBe(408)
+ expect(Date.now() - started).toBeLessThan(2000) // idleTimeoutMs: 300 in this config
+ expect(((await (response as Response).json()) as { message: string }).message).toBe('The form could not be sent. Please try again in a moment.')
+ await backToNormal('attempt-stalled-00000001')
+ })
+
+ test('a slow trickle that keeps sending is not cut off by the idle timeout', async () => {
+ const body = Buffer.concat([prelude(), PDF, closing])
+ let offset = 0
+ const trickle = new ReadableStream({
+ async pull(controller) {
+ await new Promise((resolve) => setTimeout(resolve, 60)) // well under the idle limit, over many chunks
+ const next = body.subarray(offset, offset + Math.ceil(body.length / 10))
+ offset += next.length
+ if (next.length) {controller.enqueue(next)}
+ else {controller.close()}
+ },
+ })
+ const response = await within(raw(trickle), 5000)
+ expect((response as Response).status).toBe(200)
+ expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
+ })
+
+ test('the request ceiling: checks that never finish do not hold the request or its slot', async () => {
+ let release = () => {}
+ slowScan = new Promise((resolve) => (release = resolve))
+ const started = Date.now()
+ const response = await within(send([{ name: 'cv.pdf', data: PDF }]), 5000)
+ expect(response).not.toBe('HUNG')
+ expect((response as Response).status).toBe(408)
+ expect(Date.now() - started).toBeGreaterThanOrEqual(1400) // timeoutMs: 1500 in this config
+ expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
+ release()
+ slowScan = null
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ await backToNormal()
+ })
+})
+
+describe('files without the feature', () => {
+ test('submitForm({ files }) on a form without a File field is refused and logged, never dropped silently', async () => {
+ const plain = await payload.create({
+ collection: 'forms' as never,
+ data: { confirmationMessage: text('ok'), fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'No file field' } as never,
+ })
+ const warn = vi.spyOn(payload.logger, 'warn')
+ const before = await count()
+ const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: PDF }] }, formId: String(plain.id), maxPerMinute: 0, payload })
+ expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false })
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('has no File field'))
+ expect(await count()).toBe(before)
+ warn.mockRestore()
+ })
})
diff --git a/test/formFileField.test.ts b/test/formFileField.test.ts
index 59f1923..6c2eb6c 100644
--- a/test/formFileField.test.ts
+++ b/test/formFileField.test.ts
@@ -8,14 +8,16 @@ import { fileFieldLimits, resolveFormAttachments } from '../src/modules/forms/at
import { canCarryFiles, emailAddresses, fixedRecipients, mayCarryFiles } from '../src/modules/forms/attachments/delivery.js'
import { buildFileBlock } from '../src/modules/forms/attachments/fileBlock.js'
import { checkFileContent, matchFileType, oleHasMacros, pdfHasActiveContent, zipEntries } from '../src/modules/forms/attachments/fileChecks.js'
-import { limitInMB } from '../src/modules/forms/attachments/fileGate.js'
+import { createFileGate, limitInMB } from '../src/modules/forms/attachments/fileGate.js'
import { describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from '../src/modules/forms/attachments/fileTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { fileFieldError, fileFieldRules, initialBuilderValues, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { splitFormFiles } from '../src/modules/forms/createSubmitAction.js'
import { publicForm } from '../src/modules/forms/RenderForm.js'
+import { submitForm } from '../src/modules/forms/submitForm.js'
import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
+import { fakePayload } from './helpers.js'
vi.mock('server-only', () => ({}))
@@ -125,6 +127,22 @@ describe('limits', () => {
expect(limitInMB(2_999_999)).toBe(2.8) // rounded down — never promise more than can be sent
})
+ test('when earlier files used part of the submission total, the message names what is left', async () => {
+ const pdf = (size: number) => Buffer.concat([Buffer.from('%PDF-1.7\n'), Buffer.alloc(size - 9, 0x20)])
+ const gate = createFileGate({ fields: [{ name: 'files', allowedTypes: ['pdf'], maxFiles: 3, maxSizeMB: 10 }], options })
+ const first = gate.begin('files', 'a.pdf')
+ if ('failure' in first) {throw new Error('unexpected')}
+ expect(await gate.finish(first.token, pdf(6 * MB))).toBeNull()
+ const second = gate.begin('files', 'b.pdf')
+ if ('failure' in second) {throw new Error('unexpected')}
+ expect(second.slot.maxBytes).toBe(4 * MB)
+ expect(second.slot.tooLarge()).toMatchObject({ file: 'b.pdf', kind: 'file_too_large', max: 4 }) // not the per-file 10
+ expect(await gate.finish(second.token, pdf(4 * MB))).toBeNull()
+ const third = gate.begin('files', 'c.pdf')
+ if ('failure' in third) {throw new Error('unexpected')}
+ expect(third.slot.tooLarge()).toMatchObject({ max: 10 }) // nothing left: the submission's total
+ })
+
test('sizes read naturally', () => {
expect([formatFileSize(512), formatFileSize(64_000), formatFileSize(2.14 * MB), formatFileSize(10 * MB)]).toEqual(['512 B', '63 KB', '2.1 MB', '10 MB'])
})
@@ -272,4 +290,12 @@ describe('messages and helpers', () => {
expect(files?.single).toHaveLength(1)
expect(await splitFormFiles({ name: 'Jan', empty: [] })).toEqual({ fields: { name: 'Jan', empty: [] } })
})
+
+ test('submitForm({ files }) without forms.attachments: refused and logged, the submission is not stored', async () => {
+ const { create, payload } = fakePayload({ forms: { f: { fields: [{ name: 'name', blockType: 'text' }] } } })
+ const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: new Uint8Array([37, 80, 68, 70]) }] }, formId: 'f', maxPerMinute: 0, payload })
+ expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false })
+ expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('forms.attachments is off'))
+ expect(create).not.toHaveBeenCalled()
+ })
})