diff --git a/docs/deployment.md b/docs/deployment.md index ea41b94..8e88aeb 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -400,6 +400,23 @@ With R2 (recommended) media live outside the container and survive redeploys and the container disk → add a Coolify **Persistent Storage** volume for the upload directory (the upload collection's `staticDir` — by default a folder named after the slug, e.g. `media`; check the absolute path inside the container), otherwise every redeploy deletes them. See storage.md. +### Form files (`forms.attachments`) + +Files on forms are e-mailed, not stored — **no volume and no bucket** for them. What the deploy needs: + +- **Request size.** The browser posts a form with a file to `/api/ipal/forms/submit` (up to `maxTotalMB`, 10 MB by + default, plus the answers). Coolify's Traefik and Caddy have no body limit by default. An nginx in front needs + `client_max_body_size 12m;`. Cloudflare (proxied) allows 100 MB. Next's Server Action limit does not apply, and + the i18n proxy must keep `/api` out of its matcher (the default one does). +- **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. +- **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 + ([email.md](./email.md) "Attachments"). + ### Integrations in the panel Mail (SMTP/Graph) and Turnstile errors are visible in the panel after deploy: an alert on the dashboard and a banner on @@ -418,6 +435,7 @@ media in R2 or on a persistent disk. - [ ] Home page `/` redirects to a locale (`/pl`) - [ ] Panel `/admin` works, login OK - [ ] The form sends (test from the panel: Send test) +- [ ] Forms with a File field: the test e-mail with the 10 MB file arrives; a real submission with a file arrives with the attachment - [ ] Media display — through the app: `curl -sI https://klient.pl/api/media/file/` → 200; media domain: no 403 - [ ] Coolify: health check green, a scheduled backup exists (§4.4, §4.6) - [ ] Favicon in `` (see seo.md — Google caches it slowly) diff --git a/docs/email.md b/docs/email.md index 855ad9f..0519a82 100644 --- a/docs/email.md +++ b/docs/email.md @@ -139,8 +139,9 @@ GRAPH_SENDER=forms@intecion.pl # one mailbox for all projects (no name → the `from` field is omitted, Graph uses the mailbox's default name), - `smtpFromAddress` → **Reply-To** (unless the message has its own `replyTo`). -Options `graphAdapter({ fallbackFromAddress, fallbackFromName })` — only placeholders -Payload requires at startup. +Options `graphAdapter({ fallbackFromAddress, fallbackFromName, largeAttachments, cleanupDelaysMs })` — +the first two are placeholders Payload requires at startup; the other two are for attachments ("Attachments" below). +`fetchImpl` is for tests. ### Wiring — choosing the transport (recommended: `mailAdapter`) @@ -188,9 +189,80 @@ email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter() The adapter does **not** send from the address in the panel — From is always the `GRAPH_SENDER` address (only the display name changes), and `smtpFromAddress` from the panel goes into Reply-To. So Exchange does not need Send-As on other domains; replies go -to the client's address. The OAuth token is fetched on every send (no cache), +to the client's address. The OAuth token is cached in the process until a minute before it expires, `saveToSentItems: false`. +## Attachments + +`payload.sendEmail({ …, attachments: [{ filename, content: Buffer, contentType }] })` works on both transports +(nodemailer's shape). Form files use it: a file a visitor attaches is e-mailed and never stored +([forms.md](./forms.md) "Files"). Base64 adds 37 %: a 10 MB file is a 13.7 MB message. + +### SMTP + +The adapter passes attachments straight to nodemailer; the plugin sets no limit. The limit is the **mail server's**, +and it counts the encoded message: a server limit of 10 MB carries about a 7 MB file, 25 MB about 18 MB, 35 MB +about 25 MB. The recipient's mailbox has its own limit too. Do not trust a table — **measure**: Site integrations → +E-mail sending → **Test e-mail** with **Attach a 10 MB test file** ticked (endpoint: `POST /api/ipal/test-email`, +body `{ to, attachmentMB }`, 1–25). A server that refuses the size answers at send time (`552 …`); the adapter +reports `{ sent: false, detail }`. + +### Microsoft Graph + +| Attachments in one message | How it is sent | Permission | Left in the mailbox | +|---|---|---|---| +| under 3,000,000 bytes in total | inside the one `sendMail` call | `Mail.Send` | nothing (`saveToSentItems: false`) | +| more | a **draft** is created in the sender mailbox, files are added (an **upload session** for files of 3 MiB and more, in pieces of 3.2 MB), the draft is sent | `Mail.ReadWrite` | a copy passes through Drafts and Sent Items; **the plugin deletes it** | + +The large path, step by step, and what happens when it fails: + +- Any failure before the send (creating the draft, an upload, the send call) → the draft is deleted at once and the + result is `{ sent: false, code: 'graph-error' }`. Nothing with the file stays in the mailbox. +- After a successful send the copy in Sent Items is deleted: the plugin looks at the message after 2 s, 5 s, 15 s and + 60 s (`cleanupDelaysMs`), and deletes it once it has left Drafts — never earlier, so the send is not cancelled. + It uses `permanentDelete`, and a plain delete when that is not available. If the copy could not be removed, the + server log says `delete it by hand (it holds a form file)`. +- The app's token lacks `Mail.ReadWrite` → nothing is created; the result is `code: 'graph-permission'` and the + log names the permission. With `mailAdapter()`: + - the panel has SMTP settings → the message goes **over SMTP** instead; + - no SMTP settings → the send fails, and the form's file limit drops to about 2.8 MB so visitors are not offered + more than can be sent; the panel shows "Microsoft Graph cannot send files of 3 MB and more here…". +- **Turn it off:** `mailAdapter({ graph: { largeAttachments: false } })` (or `graphAdapter({ largeAttachments: false })`) + — Graph keeps to small attachments; larger ones go over SMTP when the panel has SMTP settings, else the limit + is about 2.8 MB. +- `mailAttachmentLimit(payload)` (root) → the ceiling in bytes the current transport can carry, or `null`. + +#### Azure / Exchange steps for large attachments (one-time, outside the code) + +1. **Azure portal → App registrations → the app → API permissions → Add → Microsoft Graph → Application + permissions → `Mail.ReadWrite` → Grant admin consent.** Keep `Mail.Send`. `Mail.Read` is not used by the + plugin — remove it if nothing else needs it. +2. **Limit the app to the forms mailbox.** Application permissions cover *every* mailbox of the tenant, and the + app's secret sits in the environment of every project. In Exchange Online PowerShell: + ```powershell + # a mail-enabled security group that holds only the sender mailbox + New-DistributionGroup -Name "ipal-forms-mailbox" -Type Security -Members forms@intecion.pl + New-ApplicationAccessPolicy -AppId -PolicyScopeGroupId ipal-forms-mailbox ` + -AccessRight RestrictAccess -Description "ipal-kit: only the forms mailbox" + Test-ApplicationAccessPolicy -AppId -Identity forms@intecion.pl # AccessCheckResult: Granted + Test-ApplicationAccessPolicy -AppId -Identity someone.else@intecion.pl # AccessCheckResult: Denied + ``` + A new policy can take up to an hour to apply. (Microsoft is moving this to "RBAC for Applications" in + Exchange Online; a management scope limited to the same mailbox does the same job.) +3. Nothing changes in the project: the same four `GRAPH_*` variables. + +**Verify on the real tenant** (the plugin's tests run against a mocked Graph — no test touched a real mailbox): + +- [ ] Test e-mail with the 10 MB file, transport = Microsoft Graph → arrives with the file intact. +- [ ] After a minute, **Drafts and Sent Items of the sender mailbox do not contain the message** (also check + Deleted Items and Recoverable Items — whether `permanentDelete` is honoured on your tenant). +- [ ] `GRAPH_SENDER` is a **shared mailbox**: Microsoft lists a known issue with upload sessions on shared + mailboxes. If the test fails with an access or "item not found" error, use `largeAttachments: false` + (large files then go over SMTP) and report it. +- [ ] With the access policy in place, the send still works, and `Test-ApplicationAccessPolicy` denies other mailboxes. +- [ ] A file of 2.9–3.1 MB (both sides of the switch) arrives. +- [ ] Server log after a send: no `delete it by hand`. + ## Transport switch — mailAdapter `mailAdapter()` is a dispatcher: one adapter wired in the config, it picks the transport @@ -211,8 +283,9 @@ secrets are missing in .env → log + fallback to SMTP (no silent failure). ## Test send — button in the panel The E-mail sending tab has a **Send test** button: enter an address, click, and a test -mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error). Endpoint -`POST /api/ipal/test-email`, body `{ to }` (`admin` role only — needs roles from the `access` option: +mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error). +Tick **Attach a 10 MB test file** to check that the mail server takes a file of that size ("Attachments" above). Endpoint +`POST /api/ipal/test-email`, body `{ to, attachmentMB? }` (`admin` role only — needs roles from the `access` option: not logged in → 401, other role → 403, bad address → 400, failed send → 502). Save your changes before the test — the endpoint reads from the database, not from the field on screen. @@ -246,6 +319,7 @@ send (e.g. **Send test**) the current one appears. - **Choosing the transport:** `mailAdapter()` (the panel decides) or a fixed `panelSmtpAdapter()` / `graphAdapter()`; any other Payload adapter (e.g. `@payloadcms/email-nodemailer`) also works — then you skip the panel SMTP and the send status. -- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph`. +- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph` + (`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments"). - **Extend:** form mail content is modified by `forms.beforeEmail` (see [forms.md](./forms.md)); your own mail — `sendEmail` (SMTP) or `payload.sendEmail` (through the wired adapter). diff --git a/docs/forms.md b/docs/forms.md index fa3f55b..256d97a 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -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 `` 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` (``) | 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 `` 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-* + + +{field.help ?

{field.help}

: null} +{f.getFiles(field).map((file, i) => ( + +))} +``` + +`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.: false`. + Single field types: `forms.fields.: 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`: diff --git a/docs/notifications.md b/docs/notifications.md index 2913014..6eaf347 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -57,6 +57,22 @@ if (!result.success) { This replaces a hardcoded `Error: ${result.reason}` — now a friendly text from the panel, per language. +## File field texts + +With `forms.attachments` ([forms.md](./forms.md) "Files") the **Files** group of Form messages holds: + +| Key | Placeholders | English default | +|---|---|---| +| `fileTooLarge` | `{file}`, `{max}` (MB) | `"{file}" is too large. The limit is {max} MB.` | +| `fileType` | `{file}`, `{types}` | `"{file}" is not an accepted file type. Accepted: {types}.` | +| `fileCount` | `{field}`, `{max}` | `Attach at most {max} files in "{field}".` | +| `fileNotSent` | — | `We could not send your file. Try again, or send it by e-mail.` | +| `fileRemove` | `{file}` | `Remove {file}` | + +Polish defaults ship too; any other language is filled in the panel. `resolveFormMessage` maps +`kind: 'file_too_large' | 'file_type' | 'file_count'` and `reason: 'delivery'` to them; a texts object without these +keys falls back to `validation` / `error`. + ## {field} interpolation The `validation` text may contain `{field}` — it is replaced with the **technical name** of the field with diff --git a/docs/security.md b/docs/security.md index 8b4aa5b..33fd232 100644 --- a/docs/security.md +++ b/docs/security.md @@ -483,6 +483,25 @@ data access, not just the UI. - Uploads: `buildUploadSecurityHeaders()` in `next.config.ts` (an SVG cannot run a script on the site's domain). - `users`: the plugin injects an auth collection when the project has none (roles and 2FA always attach). +## Form files (`forms.attachments`) + +Files attached to a form are **never stored and cannot be downloaded**: they are checked in memory, attached to +the company e-mail and dropped. The checks, in order — origin, rate limit, declared size, concurrency guard, +honeypot, Turnstile, field validation and consent, then per file: count, name (double and refused extensions), +size while reading, content signature, container and macro checks, an optional `scan` hook — are listed in +[forms.md](./forms.md) "The security wall". + +- There is **no antivirus**. The checks stop the wrong kind of file; they do not prove a file is harmless. Plug a + scanner into `forms.attachments.scan` when the client needs one. The macro check for legacy `.doc` / `.xls` is + best-effort. +- Programs, scripts, macro-enabled Office files, archives, HTML and SVG are refused unless the project lists + the extension in `allowRisky`. +- The submit endpoint (`POST /api/ipal/forms/submit`) accepts same-origin requests only + (`attachments.submit.allowedOrigins` adds others) and runs the same gates as the server action; REST creation + of submissions stays "logged-in users only". +- Microsoft Graph: files of 3 MB and more need `Mail.ReadWrite` — limit the app to the forms mailbox + ([email.md](./email.md) "Attachments"). + ## Access control (since the version after 1.12.3) - Injected auth collection with roles: a `user` account reads and edits only itself; only an diff --git a/docs/storage.md b/docs/storage.md index 8f70e2a..7c45283 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -8,6 +8,10 @@ and configures the adapter. > `.env` — like DATABASE_URI, PAYLOAD_SECRET, GRAPH_*. NOT into the admin panel (they are agency > secrets, bound at startup, the editor does not change them). +> **Form files are not stored.** A file a visitor attaches to a form (`forms.attachments`) is checked, e-mailed to the +> company and dropped — it never becomes a Media record and never reaches R2 or the disk. Nothing on this page +> applies to it; see [forms.md](./forms.md) "Files". + ## .env variables Where to get the values: Cloudflare → R2 → bucket (name), Overview → S3 API (endpoint `https://.r2.cloudflarestorage.com`), Manage R2 API Tokens → "Object Read & Write" (a key pair; the secret is shown once). All 4 variables → R2; any missing → local disk (partial configuration = a warning in the log). diff --git a/src/modules/forms/BuilderForm.tsx b/src/modules/forms/BuilderForm.tsx index 1b25eb3..cf5cb00 100644 --- a/src/modules/forms/BuilderForm.tsx +++ b/src/modules/forms/BuilderForm.tsx @@ -9,7 +9,6 @@ import type { BuilderField } from './builderTypes.js' import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js' import { formatFileSize } from './attachments/fileTypes.js' -import { honeypotInputProps } from './honeypot.js' import { useBuilderForm } from './useBuilderForm.js' /** @@ -228,7 +227,7 @@ export function BuilderForm({ return (
- + {f.total > 1 && progress ?

{progress}

: null}
{step.title ?

{step.title}

: null} diff --git a/src/modules/forms/useBuilderForm.ts b/src/modules/forms/useBuilderForm.ts index fc0a088..0aca667 100644 --- a/src/modules/forms/useBuilderForm.ts +++ b/src/modules/forms/useBuilderForm.ts @@ -10,6 +10,7 @@ import { safeHref } from '../links/resolveLinkHref.js' import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js' import { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js' import { formAnalyticsOnSuccess } from './formAnalytics.js' +import { HONEYPOT_FIELD, honeypotInputProps } from './honeypot.js' import { useForm } from './useForm.js' export type UseBuilderFormOptions = { @@ -67,12 +68,17 @@ export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, // browser or a proxy) carries the same key and the server sends nothing twice. // A new key only once the server has answered. const attemptKey = useRef('') + // The honeypot input is not part of the form values; its content is read at submit + // and sent along, so the server can drop a bot that filled it. + const honeypot = useRef(null) const submitAction = useCallback( async (values: Record, token?: string) => { const shownFields = visibleInputs(values) const shown = new Set(shownFields.map((field) => field.name)) const fileNames = new Set(shownFields.filter((field) => field.blockType === 'file').map((field) => field.name)) - const answers = Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name) && !fileNames.has(name))) + const answers: Record = Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name) && !fileNames.has(name))) + const trap = honeypot.current + if (trap?.value) {answers[trap.name || HONEYPOT_FIELD] = trap.value} const files = [...fileNames].flatMap((name) => (Array.isArray(values[name]) ? (values[name] as File[]) : []).map((file) => ({ name, file }))) let result: Awaited> @@ -276,6 +282,17 @@ export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, [f, getFieldProps, textValue], ) + /** Props of the hidden honeypot input — render one `` inside the form. */ + const getHoneypotProps = useCallback( + (name?: string) => ({ + ...honeypotInputProps(name), + ref: (input: HTMLInputElement | null) => { + honeypot.current = input + }, + }), + [], + ) + const helpId = useCallback((field: BuilderField) => `${fieldId(field)}-help`, [fieldId]) // File fields: the selected files live in the form values (File[]); the native @@ -390,6 +407,7 @@ export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, getFieldProps, getFileProps, getFiles, + getHoneypotProps, getInputProps, getOptionProps, getSelectProps,