Form attachments proposal: e-mail only, no storage (revision 2)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:01:18 +01:00
co-authored by Claude Fable 5.2
parent d2caf8c2ae
commit 62bed415ed
+241 -246
View File
@@ -1,221 +1,215 @@
# Form attachments — design proposal # Form attachments — design proposal (revision 2: e-mail only)
> **Status:** proposal, nothing built. Branch `claude/form-attachments-9694cb`, cut from `755f510` (v1.15.5). > **Status:** proposal, nothing built. Branch `claude/form-attachments-9694cb`, cut from `755f510` (v1.15.5).
> **Request:** `vanstevpl-web/docs/plugin-requests/2026-11-13-candidate-form-attachments.md` — an optional > **Request:** `vanstevpl-web/docs/plugin-requests/2026-11-13-candidate-form-attachments.md`.
> CV (PDF/DOC/DOCX, 10 MB) on the Careers form; the owner chose to build it in the plugin. > **Owner's decision (2026-11-13), which replaces the storage part of that request and of revision 1:**
> **Next step:** the owner answers the four decisions in §10; the build follows §11. > "files are not stored at all. just send on e-mail. up to 10MB, filetypes, add security wall."
> **Next step:** the owner answers the three decisions in §10; the build follows §11.
## 1. Summary ## 1. Summary
A new opt-in option, `forms.attachments`, adds: A new opt-in option, `forms.attachments`, adds a **File** field to the form builder. A file a visitor attaches:
- a **File** field type in the form builder (`file` block), 1. passes every existing gate and a set of file checks,
- a **private upload collection** (`form-uploads`) that only staff with submission access can read, 2. is held in memory for that one request,
- file handling inside the existing submit pipeline — one request, same gates, no upload endpoint, 3. is attached to the company notification e-mail through the project's e-mail adapter,
- the files on the submission in the admin panel, a readable filename in e-mails, and a staff link. 4. is dropped. Nothing is written to disk, a bucket, the database or a Media record. There is no download route.
Without `forms.attachments` nothing changes: no new block, collection, field, table or route. The submission keeps only **metadata**: file name, type, size, and whether the e-mail was handed to the mail server.
The customer confirmation never carries the file.
Without `forms.attachments` nothing changes: no new block, field, table or route.
```ts ```ts
ipalKit({ ipalKit({
forms: { forms: {
attachments: true, // or { maxSizeMB, maxTotalMB, maxFiles, fileTypes, storage, retentionDays, scan, collectionOverrides } attachments: true, // or { maxSizeMB, maxTotalMB, maxFiles, fileTypes, allowRisky, scan, maxConcurrent }
}, },
}) })
``` ```
## 2. What the form-builder already has, and what we reuse Not used: form-builder 3.90.2 has its own `upload` block and `submissionUploads` field. Both exist to store files
in an upload collection, so they stay off.
`@payloadcms/plugin-form-builder` 3.90.2 already ships an `upload` block, a `uploadCollections` option, a ## 2. Transfer
`submissionUploads` field on submissions (`{ field, value: upload[] }`) and a `handleUploads` hook. ipal-kit
turns none of it on today (it already labels `submissionUploads` as "Files").
| Upstream piece | Use it? | Why | **Forms with a file post to one plugin endpoint that reads the request as a stream.** Text-only forms keep
using the Server Action exactly as today.
- Endpoint: `POST /api/ipal/forms/submit`, registered by the plugin when `attachments` is on (the same way the
cookie-scan endpoints are). **No route file and no `next.config` change in the project.**
- `useBuilderForm` picks the path: a file selected → `multipart/form-data` to the endpoint, text fields first,
files last; no file → the bound Server Action. Both end in the same `submitForm` and return the same result
shape, with the visitor message in the page's language.
- Why not the Server Action for files: Next receives and buffers the whole body before the action runs, so no
gate can act before the file is on the server, and the default body limit is 1 MB. A stream lets the wall in §3
stand in front of the file.
- Why not a separate "upload first" route: there is nothing to upload to. One request carries the answers and
the file; nothing can be referenced later by an ID.
**Body limits for 10 MB, end to end:**
| Layer | Limit | Action |
|---|---|---| |---|---|---|
| `uploadCollections` + the `submissionUploads` field | **Yes** | Upstream data shape; the admin panel shows the files on the submission with Payload's own upload field. No custom admin component. | | The endpoint (Payload's `/api` route handler) | none from Next; ours: `maxTotalMB` + 64 KB of fields, enforced while reading | — |
| The `upload` block | No — stays off | The editor would pick a collection slug, type raw MIME strings and a size in bytes; no help text, no file count, no "Show only when". | | Next.js Server Actions `bodySizeLimit` (1 MB) | does not apply — files never go through the action | — |
| The `handleUploads` hook | No — it never runs for our block | It trusts the browser's MIME type, returns English-only errors, and accepts **client-supplied media IDs** ("pre-uploaded files"), which the request forbids. It only acts on `blockType: 'upload'`, so a block named `file` bypasses it. | | Next.js proxy buffer `proxyClientMaxBodySize` (10 MB) | does not apply — the standard proxy matcher excludes `/api` | `ipal-doctor` warns when a project's matcher covers `/api/ipal` |
| Coolify's Traefik or Caddy | no body limit by default | to confirm on a real deploy: the read timeout on a slow mobile upload |
| Cloudflare, when proxied | 100 MB | — |
| nginx, if a project adds one | 1 MB | `client_max_body_size 12m` |
So: our own `file` block and our own validation, written into upstream's `submissionUploads`. A project that A `Content-Length` over the limit is refused before a byte is read; a body that lies about its length is cut off
wants upstream's block can still pass `forms.fields.upload: <Block>`. at the limit.
## 3. Private storage ## 3. The security wall
One architecture serves every option: `form-uploads` is an ordinary Payload upload collection, so the storage Every step runs before the next one starts. A failure stops the request; nothing after it runs.
backend is whatever storage adapter the project attaches to it. Payload's file route
(`/api/form-uploads/file/<key>`) checks the collection's `read` access before it streams a byte, on every backend.
There is never a public URL and never a Media record.
| | Private R2 bucket | App disk + Coolify volume | MongoDB GridFS | | # | Check | Before any file byte is accepted? |
|---|---|---|---|
| What the project configures | A second bucket + `R2_PRIVATE_BUCKET`; the `s3Storage` adapter most projects already inject | A Persistent Storage volume on the app for the upload directory | Nothing |
| Survives redeploy | Yes | Only with the volume — a forgotten volume loses files silently | Yes |
| Backups | Outside the database dump; a deleted file is really gone | Separate from the database; needs its own backup | Inside every `mongodump` — deleted CVs live on in old backups |
| Code to maintain | None new (`@payloadcms/storage-s3`) | None | A custom adapter (Payload has no official one); MongoDB only |
| Dev machine on the production database | File records visible, files not downloadable | Same | Files downloadable on every developer machine |
| Download | Streamed by the app after the access check | Same | Same |
**Recommended default: a private R2 bucket in production, local disk in development.** The team already runs
R2 for media, the adapter is already a known dependency, the files stay out of database backups (which matters
for GDPR erasure), and nothing depends on remembering a volume.
It must be a **separate bucket**, not a prefix in the media bucket: with a media domain attached
(`R2_PUBLIC_URL`), every object in the media bucket is public.
What a project configures:
```bash
# .env / Coolify — the bucket has NO custom domain and NO r2.dev access
R2_PRIVATE_BUCKET=klient-form-uploads
# R2_ENDPOINT / R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY are reused; the API token must cover both buckets
```
```ts
plugins: [
ipalKit({ forms: { attachments: true } }),
buildR2Storage(['media'], { s3Storage }),
buildPrivateR2Storage({ s3Storage }), // new; collections default to ['form-uploads']
]
```
Behaviour, same pattern as `buildR2Storage`:
- `R2_PRIVATE_BUCKET` + the three shared variables → files in the private bucket.
- None → local disk (development works with zero configuration).
- **Production without a private bucket → startup fails with a clear message**, unless the project states
`attachments: { storage: 'disk' }`. That value means "we mounted a volume"; the docs give the Coolify steps and
the directory. A silent write to the container disk is the failure we refuse to ship.
- Any other backend: attach your own storage adapter to `form-uploads` and set `storage: 'custom'`.
- `ipalEnvRules({ formAttachments: true })` requires `R2_PRIVATE_BUCKET`; `ipal-doctor` gets a rule for the same.
GridFS is not in the first build (see decision 1). It fits the same collection later as one more adapter.
## 4. Transfer
**One request: the file travels with the submission through the existing Server Action.** No upload route.
- The browser keeps `File` objects in the form state. `useBuilderForm` passes them inside `values`
(`{ attachment: [File] }`); React 19 sends `File` arguments of a Server Action as multipart parts, binary, with
the filename. The action signature `sendForm(formId, locale, values, turnstileToken?)` does not change.
*To prove first in the build:* a `File` nested in `values` arrives intact through Next 16.4. Fallback with the
same design: a `FormData` argument.
- `createSubmitAction` splits files from text values and calls `submitForm({ data, files })`. `files` is a new
optional argument; `splitFormFiles(values)` is exported for hand-written actions.
- Why not a separate upload route: a file uploaded before the submit has to be referenced by an ID the client
sends back (forbidden), leaves orphans from every abandoned form, and needs the gates duplicated. With one
request nothing is stored until every gate and every check has passed.
**Body limits — what makes 10 MB work end to end:**
| Layer | Default | What to do |
|---|---|---| |---|---|---|
| Next.js Server Actions (`experimental.serverActions.bodySizeLimit`) | **1 MB** | Raise it. Without this a 10 MB field is a lie. | | 1 | Method, same-origin (`Origin` / `Sec-Fetch-Site`), content type | Yes — headers only |
| Next.js proxy/middleware buffer (`experimental.proxyClientMaxBodySize`, Next 16) | 10 MB | Raise it — every site runs `createProxy`, and 10 MB of file plus the multipart envelope is over 10 MB. | | 2 | **Rate limit** per IP (the existing limiter and bucket) | Yes — headers only |
| Coolify's Traefik (or Caddy) | no body limit | Nothing. To check on a real deploy: the proxy's read timeout on a slow mobile upload. | | 3 | Declared size over the limit → refused | Yes — headers only |
| Cloudflare, when proxied | 100 MB | Nothing. | | 4 | Concurrency guard: at most `maxConcurrent` (default 2) file submissions at once per instance; more get "try again in a moment" | Yes |
| nginx, if a project adds one | 1 MB | `client_max_body_size`. | | 5 | Text fields read (small, capped). **Honeypot** → fake success, connection closed | Yes |
| 6 | **Turnstile** verified | Yes |
| 7 | Form loaded; **field validation and GDPR consent**, as today | Yes |
| 8 | The form has a file field under this key, the field is visible ("Show only when"), and an e-mail can carry it (§5) | Yes |
| 9 | File name: path parts and control characters removed; **double extensions** (`cv.pdf.exe`) and blocked extensions refused; extension must be one of the field's allowed types | Yes — part header only |
| 10 | **Count** per field (`maxFiles`) | Yes |
| 11 | **Size** per file (`maxSizeMB`) and per submission (`maxTotalMB`), counted **while reading**; the read stops at the limit | During the read |
| 12 | **Signature** of the first bytes must match the type the extension claims | On the first chunk |
| 13 | Whole-file checks: container structure, macros, encrypted archives (table below) | After the read, in memory |
| 14 | Optional `scan` hook (antivirus) | After the read |
| 15 | E-mail built and sent; buffers released | — |
The plugin makes the two Next values one line and keeps them honest: A file part that arrives before the text fields, a file under a key that is not a file field, or text under a file
key is refused. The endpoint is not a bypass: it runs the same `submitForm` gates, and REST creation of
submissions stays "logged-in users only".
```ts **Type checks — by content, never by name or browser MIME alone:**
// next.config.ts
experimental: { ...formUploadLimits({ maxTotalMB: 10 }) } // → both limits at 11 MB
```
- `attachments.maxSizeMB` (default 10) and `attachments.maxTotalMB` (default 10, all files of one submission) are | Type | Check |
**ceilings set in code**. The editor's values in the panel cannot exceed them, so the panel can never promise |---|---|
more than the server accepts. | PDF | starts with `%PDF-` |
- `ipal-doctor` compares `next.config` with `maxTotalMB` and reports a limit that is too low. | DOCX, XLSX, ODT | ZIP signature **and** the archive directory lists the entries that type must have (`[Content_Types].xml` + `word/document.xml` for DOCX). The directory is read without unpacking, so there is no zip-bomb exposure. Refused: a macro project inside (`vbaProject.bin`), an encrypted entry, an executable entry. |
- A request over the limit is cut off by Next before the action runs; the visitor sees the form's general error. | DOC, XLS | OLE signature `D0 CF 11 E0 A1 B1 1A E1`; refused when the file carries a VBA macro storage (decision 3) |
The browser checks size before sending, so a normal visitor gets the specific message instead. | RTF, JPG, PNG, WebP | their signatures |
Known cost, stated plainly: Next reads the request body before the action runs, so the rate limit cannot refuse **Refused by default, whatever the field allows:** executables and scripts (`exe, dll, msi, bat, cmd, com, scr,
a large body before it is received. The body limit caps the damage; the rate limit still stops anything from js, vbs, ps1, sh, jar, apk, app, dmg, lnk, hta` and the like, by extension and by signature: MZ, ELF, Mach-O,
being stored. `#!`), macro-enabled Office files (`docm, xlsm, pptm, dotm`), archives (`zip, rar, 7z, tar, gz`), disk images,
HTML and SVG. A project that really needs one states it: `attachments.allowRisky: ['zip']`. A project adds its
own type with `attachments.fileTypes: { dwg: { label, extensions, mimeType, detect } }`.
## 5. Validation and safety **Further cheap checks included:**
Order in `submitForm` — unchanged gates first, files last, storage only after everything passed: - The attachment's name is rebuilt, never passed through: the cleaned stem (letters, digits, space, `.-_`, 80
characters) + the extension of the **detected** type; an empty result becomes `attachment-<id>.<ext>`.
- The attachment's content type is set from the detected type, with `Content-Disposition: attachment`.
- An empty file is refused. A password-protected Office file is refused (its container does not match).
- The company e-mail gets one line: "This file came from a public form and was not checked for viruses."
- Optional, off by default: `strictPdf` refuses PDFs that declare JavaScript, launch actions or embedded files
(a byte search; it can miss compressed objects and can refuse a harmless file).
1. Honeypot (in `createSubmitAction`) → fake success, nothing read or stored. **No antivirus.** The plugin does not scan files for malware. These checks stop the wrong *kind* of file; they do
2. Rate limit → 3. Turnstile → 4. field validation and GDPR consent — exactly as today. not prove a PDF or DOC is safe. A project that needs scanning plugs it in:
5. **File checks** (new), all in memory, before anything is written. `attachments.scan: async ({ name, type, size, data }) => ({ ok, reason? })` (ClamAV, a scanning API). A refusal
6. Store files → create the submission → on any failure delete what was stored. is reported to the visitor as a file-type error.
There is no second entry point, so there is nothing to bypass: REST `create` on `form-uploads` is closed, and New result codes, additive: `reason: 'validation'` with `kind: 'file_too_large' | 'file_type' | 'file_count'`,
REST `create` on submissions stays "logged-in users only". and `reason: 'delivery'` (§6).
File checks, all server-side: ## 4. E-mail size — the real maximum per path
- **Field:** a file may only arrive under the key of a `file` field of this form; anything else is Base64 adds 37%: a 10 MB file is a 13.7 MB message. `maxTotalMB` (default 10) caps one submission, so one e-mail
`unknown_fields`. A field hidden by "Show only when" drops its files. Text values under a file key, or files never exceeds about 14 MB.
under a text key, are rejected.
- **Count:** at most `maxFiles` per field; `required` needs at least one.
- **Size:** each file ≤ the field's `maxSizeMB`, the submission ≤ `maxTotalMB`; an empty file is rejected.
- **Type by content, not by name or browser MIME.** The extension picks the expected type; the bytes must match:
| Type | Check | **SMTP** (`panelSmtpAdapter`, nodemailer): attachments already pass through the adapter; no size limit of our own.
|---|---| The limit is the mail server's, and it counts the encoded message:
| PDF | starts with `%PDF-` |
| DOC (and XLS) | OLE compound-file signature `D0 CF 11 E0 A1 B1 1A E1` |
| DOCX | ZIP signature **and** the archive's directory lists `[Content_Types].xml` and `word/document.xml`; an archive with `word/vbaProject.bin` (macros) is refused. The directory is read without unpacking, so there is no zip-bomb exposure. |
| XLSX, ODT | same container check with their own entries |
| RTF, JPG, PNG, WebP | their signatures |
A wrong extension, a renamed file, or an unknown type is `file_type`. The type list is a registry a project can | Server limit (typical — check the provider) | Largest file |
extend: `attachments.fileTypes: { dwg: { label, extensions, mimeType, detect } }`. |---|---|
- **Storage key:** generated (`<uuid>.<ext of the detected type>`); the visitor's filename never reaches the | 10 MB (some shared hosting, Postmark) | about 7 MB — **a 10 MB field would fail** |
storage layer or a URL. | 25 MB (Google Workspace, Mailgun) | about 18 MB |
- **Display name:** the original name with path parts, control and bidi characters removed, trimmed to 120 | 35 MB (Microsoft 365 default) | about 25 MB |
characters; stored as text, shown escaped.
- **Download headers**, set by the collection itself (no `next.config` wiring): `Content-Disposition: attachment`
with the display name, `X-Content-Type-Options: nosniff`, a sandbox CSP, `Cache-Control: private, no-store`,
`X-Robots-Tag: noindex`. Image resizing and cropping are off for this collection.
- **Malware scanning:** not built in. `attachments.scan(file)` is a hook for a project that runs ClamAV or a
scanning service; a refusal returns `file_type`. See decision 4.
New result codes, additive: `reason: 'validation'` with `kind: 'file_too_large' | 'file_type' | 'file_count'` The recipient's mailbox has its own limit as well. The values above are from memory, not measured; the build adds
and `field`. `required` is reused for a missing file. a real test instead of trusting them: **Send test e-mail** in the panel gets "with a 10 MB attachment".
## 6. Access **Microsoft Graph** (`graphAdapter`), checked against Microsoft's documentation on 2026-11-13:
- `form-uploads` access: `read` = **the same rule as reading submissions** (default `editor+`; when the project - `sendMail` with the file inline works for attachments **under 3 MB**, with today's `Mail.Send` permission and
overrides `formSubmissionOverrides.access.read`, files follow it automatically). `create` and `update` = closed `saveToSentItems: false`.
for REST and GraphQL (the Local API in `submitForm` writes). `delete` = the submissions' delete rule (default `admin`). - **3 MB to 150 MB needs an upload session**: create a draft in the sender mailbox, upload the file in chunks,
All of it overridable through `attachments.collectionOverrides`. send the draft. That needs the **`Mail.ReadWrite`** application permission, which lets the app read mailboxes
- A row-level submissions rule (one that returns a query, e.g. "only submissions of my forms") is honoured too: unless it is scoped to the one sender mailbox. The draft is sent *from the mailbox*, so a copy passes through
the download checks that this user can read the file's own submission. Drafts and lands in Sent Items, and must be deleted afterwards. Microsoft lists a known issue with upload
- A download URL carries only the generated key. Anonymous requests and accounts without submission access get sessions on shared mailboxes, and `GRAPH_SENDER` is one.
403/404 whatever URL or ID they try; access is decided by who asks, never by what the link contains. Swapping a - So the real maximum on Graph **today is under 3 MB**; 10 MB needs either the upload session or SMTP (decision 1).
submission ID cannot attach another submission's file: submissions cannot be updated through the API, and
the upload relation is written only by `submitForm`.
- The collection is not in the navigation (`admin.group: false`, "one entry per feature"): staff open a
submission and see **Files** there.
## 7. Lifecycle **The limit the visitor sees is the limit that works.** The effective maximum is the lowest of: the field's
`maxSizeMB`, the plugin cap `attachments.maxSizeMB`, and the transport's cap (3 MB on Graph without a large-file
path). The form uses that number for its check and its message, and the panel shows a notice on a form whose
field asks for more than the current e-mail settings can send.
- **No pre-upload, so no abandoned-form orphans.** A file exists on the server only as part of a submission **When the mail provider rejects the message:**
that passed every check.
- **Failure cleanup:** if storing a file or creating the submission fails, every file stored for that request is
deleted before the error is returned. The visitor keeps their selection and can retry; the retry starts clean,
so there are **no duplicates**. On success the form is replaced by the confirmation (or reset), and the submit
button is disabled while sending.
- **Crash between the two writes** (no transactions on a standalone MongoDB): the file record has no submission.
An **orphan sweep** deletes such records older than one hour. It runs at most once an hour, triggered by a
submission with files, and is exported as `cleanupFormUploads({ payload })`.
- **Deleting a submission deletes its files** (`afterDelete` hook; Payload removes the stored object with the
record), including bulk deletes in the panel.
- **Deleting only a file** (admin, e.g. an erasure request): allowed; the submission keeps the filename as text.
- **Retention:** `attachments.retentionDays` — files older than that are deleted by the same sweep; the
submission's answer row then reads "CV.pdf (removed)". Off by default (decision 2). For sites with few
submissions the docs show a Coolify Scheduled Task that calls the cleanup, like the scheduled cookie crawl.
Whole-submission retention (name, e-mail, message) is the same GDPR question but a separate feature; listed as a
follow-up, not built here.
- Docs state what the plugin cannot reach: database and bucket backups keep deleted files until they rotate.
## 8. Builder and renderer - *At send time* (SMTP `552`/size refusal, Graph `4xx`, timeout, wrong credentials): the adapter reports it, and
§6 applies. The site's e-mail status in the panel turns "degraded", as today.
- *After acceptance* (the recipient's server bounces it, Exchange refuses it after `202 Accepted`): the site
cannot know. The bounce goes to the sender mailbox. The submission therefore says **"Handed to the mail
server"**, never "delivered". The docs say this plainly.
**Panel block `file`** — labels in English and Polish, wording per `admin-ux.md`: ## 5. Which e-mail carries the file
- The file is attached to every e-mail of the form whose **To, CC and BCC are fixed addresses written in the
panel**. An e-mail addressed with a placeholder (`{{email}}`) never gets a file — that is the customer
confirmation, and no setting can change it.
- A form with a file field and no fixed-recipient e-mail cannot deliver anything. The panel refuses to save it:
"Add an e-mail with a fixed recipient. Files are sent by e-mail only." At submit time the same condition
refuses the file before it is read (wall step 8).
- 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 a filename in every e-mail, never `[object File]`.
- Mechanics: the files travel in the request context to form-builder's `beforeEmail`. The plugin's hook takes the
file-carrying e-mails out, sends them itself to see the result, and hands the rest back only after success.
`forms.beforeEmail` still runs on all of them. A custom e-mail adapter must support `attachments`.
## 6. Failure handling — the file is lost by design
If the e-mail cannot be sent, the file is gone: there is no copy to retry with. The design makes that visible to
both sides (decision 2):
**The visitor** sees an error, not the confirmation — "We could not send your file. Try again, or send it by
e-mail." (`fileNotSent`, per language) — and keeps their answers and selected file, so one click retries.
The customer confirmation is **not** sent for a failed attempt.
**Staff** get a notification *without* the file, sent once: the answers plus "The visitor attached CV.pdf
(9.8 MB), but it could not be sent. Ask them to send it again." If the mail system is down entirely, that
notice fails too, and the panel is the record.
**The submission** is stored with the answers and:
| Field | Value |
|---|---|
| Files | name, type, size per file |
| File delivery | "Handed to the mail server" / "Not sent" |
| Note | the reason, in plain words ("The mail server refused the message: too large.") |
"Not sent" submissions are marked in the list, so staff can find them and ask again.
**Retries without duplicate e-mails:**
- Each submit carries an **attempt key** from the browser. The key changes only after the server has answered.
A double click, a browser resend or a proxy retry carries the same key: the server answers with the first
result and sends nothing again. The key is stored on the submission, so this holds across instances and restarts.
- The plugin sends each e-mail **once** — no automatic resend, no background queue (there is no file to resend).
- A visitor's retry after "Not sent" is a new attempt: one new submission, one staff e-mail with the file, one
customer confirmation. The failed attempt stays in the panel, marked.
## 7. Builder and renderer
**Panel block `file`** — English and Polish, wording per `admin-ux.md`:
| Field | Type | Default | Label (en / pl) | | Field | Type | Default | Label (en / pl) |
|---|---|---|---| |---|---|---|---|
@@ -224,107 +218,108 @@ and `field`. `required` is reused for a missing file.
| `help` | text, localized | — | Help text / Tekst pomocy — "Shown under the field, e.g. accepted types and size." | | `help` | text, localized | — | Help text / Tekst pomocy — "Shown under the field, e.g. accepted types and size." |
| `width`, `required` | as other blocks | | | | `width`, `required` | as other blocks | | |
| `allowedTypes` | select, many | PDF, DOC, DOCX | Allowed file types / Dozwolone typy plików | | `allowedTypes` | select, many | PDF, DOC, DOCX | Allowed file types / Dozwolone typy plików |
| `maxSizeMB` | number, 1…ceiling | 10 | Maximum size (MB) / Maksymalny rozmiar (MB) | | `maxSizeMB` | number, 1…cap | 10 | Maximum size (MB) / Maksymalny rozmiar (MB) |
| `maxFiles` | number, 1…ceiling | 1 | Maximum files / Maksymalna liczba plików | | `maxFiles` | number, 1…cap | 1 | Maximum files / Maksymalna liczba plików |
| `showWhen` | as other blocks | | | | `showWhen` | as other blocks | | |
Block name: **File / Plik** ("File fields / Pola pliku"). `forms.fields.file: false` hides the block; Block name: **File / Plik**. `forms.fields.file: false` hides it; `forms.fields.file: <Block>` replaces it;
`forms.fields.file: <Block>` replaces it; `fileBlock` is exported. `fileBlock` is exported. Caps in code: `attachments.maxSizeMB` (10), `maxTotalMB` (10), `maxFiles` (3) — the
editor cannot promise more than the server accepts.
**Types:** `FormsOption.attachments`, `FormsOption.fields.file`; `BuilderField` gains `help`, `allowedTypes`, **Types:** `FormsOption.attachments`, `FormsOption.fields.file`; `BuilderField` gains `help`, `allowedTypes`,
`maxSizeMB`, `maxFiles`; `publicForm` passes them to the browser. `maxSizeMB`, `maxFiles`; `publicForm` passes them to the browser.
**`useBuilderForm`** — a file field's value is `File[]`: **`useBuilderForm`** — a file field's value is `File[]`:
- `getFileProps(field)` → `id`, `name`, `type: 'file'`, `accept` (extensions and MIME types of the allowed - `getFileProps(field)` → `id`, `name`, `type: 'file'`, `accept`, `multiple`, `required`, `onChange`,
types), `multiple`, `required`, `onChange`, `aria-invalid`, `aria-describedby` (help + error), `ref`. `aria-invalid`, `aria-describedby` (help + error), `ref`.
- `getFiles(field)` → `{ name, size }[]`; `removeFile(field, index)` — clears the native input and returns focus to it. - `getFiles(field)` → `{ name, size }[]`; `removeFile(field, index)` clears the native input and returns focus to it.
- `helpId(field)`; client checks for count, size and extension with the same messages the server uses. - `helpId(field)`; browser checks for count, size and extension with the server's messages.
- The existing `isSubmitting` is the pending state. A Server Action gives no upload percentage; the docs say so. - `isSubmitting` is the pending state; the input is cleared on success and kept after an error.
**`BuilderForm` / `RenderForm`** — a native `<input type="file">` with a real `<label>`, the help text, a list of **`BuilderForm` / `RenderForm`** — a native `<input type="file">` with a real `<label>`, the help text, the
selected files (`aria-live="polite"`), and per file a **Remove** button named "Remove {file}". Keyboard and selected files in a list (`aria-live="polite"`), and a **Remove** button per file named "Remove {file}". Every
touch work because every control is native. New `classNames` keys: `file`, `help`, `fileList`, `fileItem`, control is native, so keyboard and touch work. New `classNames` keys: `file`, `help`, `fileList`, `fileItem`,
`fileRemove`; `data-type="file"`. Files survive moving between steps. `renderField` and custom markup on the hook `fileRemove`; `data-type="file"`. Files survive moving between steps. `renderField` and custom markup work as for
work as for any field. any field. `RenderForm` needs no new prop; a hand-built form on the hook gets the endpoint path from the prepared form.
**Visitor texts** — new keys in Form messages (`notifications.form`), defaults in English and Polish, each **Visitor texts** — new keys in Form messages, defaults in English and Polish, editable per language in the panel
editable per language in the panel (that is where DE and NL come from; labels and help are localized panel fields): (that is where DE and NL come from; label and help are localized panel fields):
| Key | English default | Polish default | | Key | English default | Polish default |
|---|---|---| |---|---|---|
| `fileTooLarge` | "{file}" is too large. The limit is {max} MB. | Plik „{file}” jest za duży. Limit to {max} MB. | | `fileTooLarge` | "{file}" is too large. The limit is {max} MB. | Plik „{file}” jest za duży. Limit to {max} MB. |
| `fileType` | "{file}" is not an accepted file type. Accepted: {types}. | Plik „{file}” ma niedozwolony typ. Dozwolone: {types}. | | `fileType` | "{file}" is not an accepted file type. Accepted: {types}. | Plik „{file}” ma niedozwolony typ. Dozwolone: {types}. |
| `fileCount` | Attach at most {max} files in "{field}". | W polu „{field}” można dodać najwyżej {max} plików. | | `fileCount` | Attach at most {max} files in "{field}". | W polu „{field}” można dodać najwyżej {max} plików. |
| `fileNotSent` | We could not send your file. Try again, or send it by e-mail. | Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem. |
| `fileRemove` | Remove {file} | Usuń {file} | | `fileRemove` | Remove {file} | Usuń {file} |
`resolveFormMessage` maps the new codes; an empty panel field falls back to the default of that language. ## 8. What the submission keeps, and GDPR
## 9. E-mail and compatibility - Kept: the answers (with the filename row), the file metadata, the delivery state and note, the attempt key.
- Not kept: the file. After the response there is no copy on the server, in the database, in a bucket or in a
backup. Memory use is about 2.4 × the file while sending; the concurrency guard bounds it.
- The file then lives in the recipients' mailboxes. Its retention is the company's mailbox policy, not the
site's; the docs say so, for the client's privacy notice.
**E-mail** ## 9. Compatibility
- The submission's answers get a text row for each file field: `CV Jan Kowalski.pdf (2.1 MB)`. So
`{{attachment}}`, `{{*}}`, `{{*:table}}` and the readable summary of `emailLayout` show a filename — never a
storage key, an ID or `[object File]` — with no template change.
- **Staff link:** a new placeholder, `{{*:files}}`, renders the file names with a link to the submission in the
admin panel (`<serverURL>/admin/collections/form-submissions/<id>`). The link asks for a login and then shows
the files; a direct file URL would show a bare 403 to anyone not yet logged in. The editor puts the placeholder
into the company notification only (decision 3). Without `serverURL` it renders the names without a link.
- **No binary attachment** in any e-mail in this build. The confirmation to the visitor gets, at most, the
filename through the table. Mailing CVs would copy personal data into mailboxes the retention rule cannot reach.
- The seed template's company e-mail includes `{{*:files}}`; the customer confirmation does not.
**Compatibility**
- Opt-in. Without `forms.attachments` the generated config is identical to 1.15.5. - Opt-in. Without `forms.attachments` the generated config is identical to 1.15.5.
- Existing forms, submissions, e-mail templates, `submitForm` calls and hand-written actions keep working; every - Existing forms, submissions, e-mail templates, `submitForm` calls and hand-written actions keep working; every
API change is an added optional argument, field or union member. A text-only form submits exactly as before, API change is an added optional argument, field or union member. Text-only forms never touch the endpoint.
with or without `attachments` on. - New dependency: `busboy` (the streaming multipart parser Payload already ships).
- **MongoDB:** no migration. - **MongoDB:** no migration.
- **Postgres / SQLite projects that turn it on:** one `pnpm payload migrate:create`. New: the `form_uploads` - **Postgres / SQLite projects that turn it on:** one `pnpm payload migrate:create`. Additive only: the block
table, the block tables `forms_blocks_file` (+ `_locales`, + the allowed-types table), the tables for `file` (+ locales, + allowed types), the submission's files array table and three columns (delivery,
`form_submissions_submission_uploads` array table with its `_rels`, a `form_uploads_id` column in note, attempt key), the new Form messages columns. No upload collection, so no `_rels` or locked-documents changes.
`payload_locked_documents_rels`, and the new Form messages columns. All additive; nothing is dropped or rewritten. - After upgrading and enabling: `generate:types`. No import-map change, no env variable, no storage setup.
- After upgrading and enabling: `generate:types`, `generate:importmap` (the S3 handler is already there in - Version: a minor release.
projects that inject `s3Storage`).
- Version: a minor release (new feature, no breaking change).
## 10. Decisions for the owner ## 10. Decisions for the owner
Recommendation first in each. Recommendation first in each.
1. **Default storage.** 1. **Sites that send through Microsoft Graph, files of 3 MB and more.**
**A private R2 bucket** (`R2_PRIVATE_BUCKET`), local disk in development, disk-with-volume as a stated **Send those e-mails through the SMTP settings in the panel; without SMTP the limit on Graph is 3 MB**, and
opt-in, production refuses to start with neither. — *or* disk + volume as the default — *or* also build a the form and the panel say so. No change to the agency's Azure app.
GridFS adapter now (zero configuration, but CVs enter every database backup and we maintain the adapter). — *or* build the Graph upload session: 10 MB on Graph, but the agency app needs `Mail.ReadWrite` (scoped to
2. **Retention.** the forms mailbox), the secret that sits in every project's environment gains mailbox read access, and each file
**`retentionDays` exists, off by default**; the docs recommend a value and `ipal-doctor` notes when passes through that mailbox's Drafts and Sent Items before the plugin deletes it.
attachments are on without one. A plugin update should not start deleting a client's data on its own. 2. **When the e-mail cannot be sent.**
— *or* a default such as 180 days. **The visitor sees an error and can retry; staff get a notice without the file; the submission is marked
3. **Staff link in e-mails.** "Not sent".** — *or* the visitor sees the normal confirmation and staff must ask again.
**The `{{*:files}}` placeholder**, placed by the editor (and by the seed) in the company notification. 3. **Legacy `.doc` (and `.xls`).** The client asked for DOC, but the old format can carry macros and can only be
— *or* added automatically to every e-mail whose recipient is not an address the visitor typed. checked roughly.
4. **Malware scanning.** **Allow it, refuse files with a macro storage, and say in the docs that this check is best-effort.**
**None built in; a `scan` hook** for projects that need it. Downloads are forced attachments and macro-enabled — *or* leave `.doc` out of the default types (PDF and DOCX only); a project can still tick it.
DOCX is refused, but a legacy `.doc` can carry macros that only the reader's Office blocks.
— *or* require a scanner before `.doc` is accepted.
## 11. Build plan after the go-ahead ## 11. Build plan after the go-ahead
1. Prove the transfer (a `File` in `values` through a Server Action on the reference site), then the storage 1. Prove the transfer: a streamed multipart request to a Payload endpoint on the reference site, with the read
helper with two `s3Storage` instances in one config. cut off at the limit; confirm the proxy matcher and Traefik behaviour.
2. `forms.attachments`, the `file` block, the `form-uploads` collection, `buildPrivateR2Storage`, `formUploadLimits`. 2. `forms.attachments`, the `file` block, the endpoint, the wall, the type registry and blocklist, the `scan` hook.
3. `submitForm` file checks, storage, cleanup, sweep, retention; the new result codes and messages. 3. E-mail: attachments through `mailAdapter` on SMTP and Graph (inline under 3 MB, then decision 1), the
4. `useBuilderForm`, `BuilderForm`, `RenderForm`; the e-mail row and `{{*:files}}`. file-carrying rule, the failure notice, delivery state on the submission, the attempt key, the large test e-mail.
5. Tests on a real Payload instance, one group per acceptance test of the request: 4. `useBuilderForm`, `BuilderForm`, `RenderForm`, the new messages.
(1) text-only submit unchanged · (2) PDF, DOC, DOCX each → one submission, downloadable, filename in the staff 5. Tests on a real Payload instance. The request's seven acceptance tests, re-read for e-mail only:
e-mail · (3) oversized, mismatched, unsupported, extra files and direct calls → no submission, no file · (1) text-only submit unchanged · (2) PDF, DOC, DOCX each → one submission with metadata, the file attached to
(4) consent, Turnstile, honeypot, rate limit with a file attached → nothing stored · (5) anonymous and the staff e-mail, byte-identical, and absent from the customer e-mail · (3) oversized, mismatched,
no-access accounts refused, staff allowed, no ID substitution · (6) retry, remove, delete a submission → no unsupported, executable, macro, archive, double-extension and extra files, and direct calls to the endpoint →
duplicates, no orphans · (7) texts in four languages, keyboard operation, existing form tests still pass. no submission, no e-mail · (4) consent, Turnstile, honeypot and rate limit with a file → nothing read past the
6. Docs in the same change: `docs/forms.md`, `docs/storage.md`, `docs/security.md`, `docs/deployment.md` gate, nothing sent · (5) *replaces the download test:* no route serves a file, nothing is on disk or in the
(volume, body limits), `docs/env.md`, `AGENT.md`, the `ipal-form` and `ipal-reference` skills, the seed database after the request, and the endpoint refuses cross-origin calls · (6) retry after a failed send, a
template, CHANGELOG "## Unreleased"; a file field on a reference-site demo form. repeated request with the same attempt key, removing a selection → one e-mail, no duplicates, the failed
attempt marked · (7) texts in four languages, keyboard operation, existing form tests still pass.
Plus: SMTP refusal and Graph refusal → "Not sent", the notice e-mail, the visitor error.
6. Docs in the same change: `docs/forms.md`, `docs/email.md`, `docs/security.md`, `docs/storage.md` (one
paragraph: form files are not stored), `docs/deployment.md` (proxy limits), `AGENT.md`, the `ipal-form` and
`ipal-reference` skills, the seed template, CHANGELOG "## Unreleased"; a file field on a reference demo form.
7. Gate: `test:int`, typecheck, lint, build, `build:starter`, `starter:gate`, the reference doctor static run, 7. Gate: `test:int`, typecheck, lint, build, `build:starter`, `starter:gate`, the reference doctor static run,
the reference smoke tests on a free port. No version bump, push, merge or release. the reference smoke tests on a free port. No version bump, push, merge or release.
## 12. To confirm during the build
- A Payload custom endpoint receives the body as an unread stream on Next 16.4.
- Traefik's read timeout in Coolify on a slow 10 MB upload (needs a real deploy).
- The SMTP size limits of the providers our projects use (the large test e-mail measures it).
- On Graph: the exact request size at which inline `sendMail` starts to fail (Microsoft documents "under 3 MB").