WIP: form attachments docs (forms, email, security, storage, deployment, notifications), honeypot value sent

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:30:44 +01:00
co-authored by Claude Fable 5.2
parent 701bb420c1
commit 344574d6bd
8 changed files with 335 additions and 16 deletions
+178 -7
View File
@@ -54,6 +54,7 @@ ipalKit({
| Option | Default | Description |
|---|---|---|
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
| `attachments` | `false` | files on forms: adds the **File** field; a file is checked, e-mailed to the company and dropped — never stored ("Files" below) |
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default ipal block |
| `redirectRelationships` | — | collections a form can redirect to |
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
@@ -87,7 +88,7 @@ import { RenderForm } from '@intecion/ipal-kit/rsc'
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required, fixed`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
next, submit, success, required, fixed, file, help, fileList, fileItem, fileRemove`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
(default `'page'`), `values` (below).
@@ -99,7 +100,8 @@ a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Under
### Field types in the panel
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state as text). Turning a type off: `forms.fields: { date: false }`.
message, **Step** (+ country/state as text), and **File** when `forms.attachments` is on ("Files" below).
Turning a type off: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
@@ -112,6 +114,7 @@ the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payl
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | a real date |
| time | `HH:MM` (`<input type="time">`) | a time 00:00–23:59 |
| File | files (never a text value) | field, count, size, type by content — "Files" below |
| Step | — (split) | not a field |
### Multi-step form
@@ -174,12 +177,179 @@ pass the raw form document to the browser.
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Example: `ipal-form/resources/CustomForm.example.tsx`.
`TurnstileWidget`; for a File field `getFileProps`, `getFiles`, `removeFile`, `helpId`. Example: `ipal-form/resources/CustomForm.example.tsx`.
3. Pure logic (also on the server / in tests): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name).
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name),
`fileFieldRules`, `fileFieldError`, `formatFileSize` (File field).
`useOptionalTurnstile()` — like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing.
## Files — sent by e-mail, never stored (`attachments`)
A visitor attaches a file (a CV, a specification); the company gets it **as an attachment of the notification
e-mail**. The site does not keep it: no upload collection, no bucket, no disk, no download route. The submission
records only the file's name, type and size and whether the mail server took the message.
### Set up
```ts
// payload.config.ts
ipalKit({ forms: { attachments: true } }) // adds the File field to the form builder
```
1. Turn the option on (above). Postgres / SQLite projects: `pnpm payload migrate:create` (new block and submission
columns). MongoDB: nothing. Then `pnpm generate:types`.
2. In the panel (or the form seed) add a **File** field to the form: field key, label, help text, required, allowed
file types, maximum size (MB), maximum files, "Show only when".
3. The form needs an e-mail whose **To / CC / BCC are fixed addresses** (Forms → the form → E-mails) — that e-mail
carries the file. The panel refuses to save a form with a File field and no such e-mail.
4. Nothing else: `RenderForm` / `BuilderForm` render the field, and the plugin registers the endpoint the browser
posts files to (`POST /api/ipal/forms/submit`). No route file, no `next.config` change, no env variable.
5. Check that your mail server takes the size: **Site integrations → E-mail sending → Test e-mail** with
"Attach a 10 MB test file" ticked ([email.md](./email.md) "Attachments").
**Verify:** submit the form with a PDF → the confirmation shows; the company e-mail has the file attached and the
line "…was not checked for viruses"; the confirmation e-mail to the visitor has no file; Form Submissions shows
**Files** (name, type, size) and **File delivery: Handed to the mail server**. Rename a `.exe` to `.pdf` and submit →
the field shows "…is not an accepted file type", nothing is stored or sent.
### Options (`FormAttachmentsOption`)
| Option | Default | Description |
|---|---|---|
| `maxSizeMB` | `10` | ceiling for a field's "Maximum size (MB)" — the editor cannot set more |
| `maxTotalMB` | = `maxSizeMB` | ceiling for all files of one submission together (= one e-mail) |
| `maxFiles` | `3` | ceiling for a field's "Maximum files" |
| `fileTypes` | built-in | add a type (`{ dwg: { label, extensions, mimeType, detect } }`), replace one, or remove one (`{ rtf: false }`) |
| `allowRisky` | `[]` | extensions from the refused list this project accepts after all, e.g. `['zip']` (the type must also exist in `fileTypes`) |
| `scan` | — | antivirus hook: `async ({ name, type, size, data, field }) => ({ ok })` — `ok: false` (or a throw) refuses the file |
| `strictPdf` | `false` | refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search) |
| `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) |
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.
### The security wall — in this order
Each step runs before the next; a failure ends the request and nothing after it happens.
1. Same origin (`Origin` / `Sec-Fetch-Site`), `multipart/form-data`.
2. **Rate limit** per IP — from the headers, before any of the body is read.
3. A request that declares a body over the limit is refused unread.
4. Concurrency guard (`maxConcurrent`).
5. The answers are read (they come first in the request): **honeypot** → fake success; **Turnstile**; **field
validation and GDPR consent** — exactly the checks of a text-only form.
6. The form has a visible File field under that key, and an e-mail that can carry a file.
7. Per file, before its bytes: **count**, then the **name** — the last extension must be one of the field's types;
a refused extension anywhere in the name (`cv.pdf.exe`, `cv.exe.pdf`) or a second known extension
(`cv.pdf.docx`) is refused.
8. **Size** is counted while the file is read (per file and per submission); the read stops keeping data at the limit.
9. **Signature** of the first bytes must match the type the extension claims; programs (Windows, Linux, macOS,
`#!` scripts) are refused under any name.
10. Whole-file checks: DOCX / XLSX / ODT must be a ZIP whose directory lists the entries that type requires
(read without unpacking — no zip-bomb exposure), with no macro project, no encrypted entry and no program
inside; DOC / XLS must not carry a VBA macro storage.
11. `scan`, when the project provides one.
12. The e-mail is sent, the buffers are released.
**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.
**What this is not.** It is **not an antivirus**. The checks stop the wrong *kind* of file; they cannot tell a
harmful PDF or DOC from a harmless one. The macro check for legacy `.doc` / `.xls` is **best-effort**: it finds
ordinary macro-enabled documents, not one built to hide. Need scanning → plug a scanner into `scan`. The e-mail
says so to the recipient ("This file came from a public form and was not checked for viruses.").
The attachment's name is rebuilt, never passed through: no path, no control or bidi characters, at most 80
characters, the extension of the detected type (`CV Jan Kowalski.pdf`; an empty name becomes `attachment.pdf`).
### Limits
- The limit a visitor sees and the server enforces is the lowest of: the field's value, `attachments.maxSizeMB`,
and what the e-mail transport can carry. On Microsoft Graph without the large-file path and without SMTP
settings that is about 2.8 MB ([email.md](./email.md) "Attachments"). The form document read through Payload
carries the result per File field in `resolved` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`,
`typeLabels`) and `fileSubmitUrl` — `RenderForm` passes them on; nothing to wire.
- **Request size:** files do not go through the Server Action, so `serverActions.bodySizeLimit` (1 MB by default)
does not apply. The proxy from `createProxy` does not match `/api` (its buffer limit of 10 MB would otherwise
apply — keep `/api` out of your matcher). Coolify's Traefik has no body limit by default; an nginx in front
needs `client_max_body_size 12m`. [deployment.md](./deployment.md) "Form files".
- Memory: a file is held in memory while it is checked and sent (about 2.4 × its size during the send); nothing
touches the disk.
### E-mails
- The file is attached to **every e-mail of the form whose To, CC and BCC are fixed addresses from the panel**.
An e-mail addressed with a placeholder (`{{email}}` — the confirmation to the visitor) **never** gets it.
- The answers get a text row per File field — `CV Jan Kowalski.pdf (2.1 MB)` — so `{{attachment}}`, `{{*}}`,
`{{*:table}}` and the readable summary of `emailLayout` show the file name in every e-mail.
- `forms.beforeEmail` still runs on every e-mail (before the files are attached). A custom e-mail adapter must
support `attachments` (nodemailer's shape); `mailAdapter()` does on both transports.
### When the e-mail cannot be sent
The file is not kept, so there is nothing to retry with. Then:
- the **visitor** sees an error — Form messages → **File not sent** ("We could not send your file. Try again, or
send it by e-mail.") — keeps their answers and the selected file, and can try again. No confirmation e-mail goes out;
- **staff** get the notification once more **without** the file: "The visitor attached a file: … but it could not
be sent. Ask them to send it again.";
- the **submission** is stored and marked **File delivery: Not sent**, with a note (the mail server's reason). The
Form Submissions list shows the "File delivery" column.
"Handed to the mail server" means the mail server accepted the message. A later bounce (the recipient's server
refuses it) cannot be seen by the site; it arrives in the sender mailbox.
**No duplicates:** each submit carries an attempt key from the browser; a repeated request with the same key
(double click, a resend by the browser or a proxy) gets the first answer and sends nothing again. The plugin sends
each e-mail once — there is no automatic resend.
### Result codes and messages
`reason: 'validation'` with `kind: 'file_too_large' | 'file_type' | 'file_count'` (+ `field`, `label`, `file`,
`max`, `types`), `kind: 'required'` for a required File field without a file, and `reason: 'delivery'` when the
e-mail could not be sent. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileCount`, `fileNotSent`,
`fileRemove`), defaults in English and Polish, per language in the panel ([notifications.md](./notifications.md)).
### Your own markup
`BuilderForm` renders a native `<input type="file">` with its label, the help text, the list of selected files
(`aria-live`) and a "Remove {file}" button per file. On `useBuilderForm`:
```tsx
const props = f.getFileProps(field) // id, name, type, accept, multiple, onChange, ref, aria-*
<label htmlFor={props.id}>{field.label}</label>
<input {...props} />
{field.help ? <p id={f.helpId(field)}>{field.help}</p> : null}
{f.getFiles(field).map((file, i) => (
<button key={file.name} onClick={() => f.removeFile(field, i)} type="button">Remove {file.name} ({formatFileSize(file.size)})</button>
))}
```
`fileFieldRules(field)` gives the limits in the browser, `fileFieldError(field, files, texts)` the first problem as
the visitor's message. `isSubmitting` is the pending state (there is no upload percentage).
### Your own transfer path
`submitForm({ data, files })` takes files as whole buffers (`{ [fieldKey]: [{ name, data }] }`) and runs the same
checks and the same delivery — for an action or route that receives files itself. `splitFormFiles(values)`
(`/server`) splits `File` values from the answers; `createSubmitAction` already does it, so a hand-built form may
pass `File`s through the action (then raise `experimental.serverActions.bodySizeLimit` in `next.config.ts`).
`mailAttachmentLimit(payload)` returns the transport's ceiling in bytes (or `null`).
### Turn off, override, extend
- Off: leave `attachments` out. Only the block: `forms.fields: { file: false }`. Your own block:
`forms.fields: { file: buildFileBlock({ maxSizeMB: 5 }) }` (`fileBlock` = the default one).
- The endpoint's gates and path: `attachments.submit`, `attachments.path`; the browser can post elsewhere with
`BuilderForm fileSubmitUrl`.
- Submission fields (`submissionFiles`, `filesDelivery`, `filesDeliveryNote`, `attemptKey`) are appended to the
default fields — change them in `formSubmissionOverrides.fields`.
## Front end — submitForm (server)
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
@@ -216,7 +386,7 @@ const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, f
```
`submitForm` result: `{ success: true, submissionId }` or `{ success: false, reason, … }`
(codes below). Options: `payload`, `formId`, `data` (required), `ip`, `locale`, `turnstileToken`,
(codes below). Options: `payload`, `formId`, `data` (required), `files`, `attemptKey` ("Files" above), `ip`, `locale`, `turnstileToken`,
`maxPerMinute` (default 5, `0` turns it off; without `ip` — the shared `unknown-ip` bucket, below),
`consentFieldName` (default from `ipalKit({ forms })`, then `'consent'`), `turnstileOnConfigError`
(`'allow'` | `'reject'`, default `'allow'`), `turnstileHostnames` (see [turnstile.md](./turnstile.md)).
@@ -386,7 +556,8 @@ type SubmitFormResult =
| { success: true; submissionId: string | number }
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_count'; file?: string; max?: number; types?: string }
| { success: false; reason: 'delivery'; submissionId?: string | number } // the file could not be e-mailed
| { success: false; reason: 'not_found' }
| { success: false; reason: 'consent'; field?: string }
| { success: false; reason: 'error' }
@@ -638,7 +809,7 @@ filter it out on the client.
## Turn off, override, extend
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
Single field types: `forms.fields.<type>: false`.
Single field types: `forms.fields.<type>: false`. Files: `forms.attachments` is off unless you set it ("Files").
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`: