Co-Authored-By: Claude Fable 5.2 <[email protected]>
21 KiB
Form attachments — design proposal
Status: proposal, nothing built. Branch
claude/form-attachments-9694cb, cut from755f510(v1.15.5). Request:vanstevpl-web/docs/plugin-requests/2026-11-13-candidate-form-attachments.md— an optional CV (PDF/DOC/DOCX, 10 MB) on the Careers form; the owner chose to build it in the plugin. Next step: the owner answers the four decisions in §10; the build follows §11.
1. Summary
A new opt-in option, forms.attachments, adds:
- a File field type in the form builder (
fileblock), - a private upload collection (
form-uploads) that only staff with submission access can read, - file handling inside the existing submit pipeline — one request, same gates, no upload endpoint,
- the files on the submission in the admin panel, a readable filename in e-mails, and a staff link.
Without forms.attachments nothing changes: no new block, collection, field, table or route.
ipalKit({
forms: {
attachments: true, // or { maxSizeMB, maxTotalMB, maxFiles, fileTypes, storage, retentionDays, scan, collectionOverrides }
},
})
2. What the form-builder already has, and what we reuse
@payloadcms/plugin-form-builder 3.90.2 already ships an upload block, a uploadCollections option, a
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 |
|---|---|---|
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 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". |
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. |
So: our own file block and our own validation, written into upstream's submissionUploads. A project that
wants upstream's block can still pass forms.fields.upload: <Block>.
3. Private storage
One architecture serves every option: form-uploads is an ordinary Payload upload collection, so the storage
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 | |
|---|---|---|---|
| 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:
# .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
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-uploadsand setstorage: 'custom'. ipalEnvRules({ formAttachments: true })requiresR2_PRIVATE_BUCKET;ipal-doctorgets 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
Fileobjects in the form state.useBuilderFormpasses them insidevalues({ attachment: [File] }); React 19 sendsFilearguments of a Server Action as multipart parts, binary, with the filename. The action signaturesendForm(formId, locale, values, turnstileToken?)does not change. To prove first in the build: aFilenested invaluesarrives intact through Next 16.4. Fallback with the same design: aFormDataargument. createSubmitActionsplits files from text values and callssubmitForm({ data, files }).filesis 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. |
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. |
| 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. |
| Cloudflare, when proxied | 100 MB | Nothing. |
| nginx, if a project adds one | 1 MB | client_max_body_size. |
The plugin makes the two Next values one line and keeps them honest:
// next.config.ts
experimental: { ...formUploadLimits({ maxTotalMB: 10 }) } // → both limits at 11 MB
attachments.maxSizeMB(default 10) andattachments.maxTotalMB(default 10, all files of one submission) are 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.ipal-doctorcomparesnext.configwithmaxTotalMBand reports a limit that is too low.- A request over the limit is cut off by Next before the action runs; the visitor sees the form's general error. The browser checks size before sending, so a normal visitor gets the specific message instead.
Known cost, stated plainly: Next reads the request body before the action runs, so the rate limit cannot refuse a large body before it is received. The body limit caps the damage; the rate limit still stops anything from being stored.
5. Validation and safety
Order in submitForm — unchanged gates first, files last, storage only after everything passed:
- Honeypot (in
createSubmitAction) → fake success, nothing read or stored. - Rate limit → 3. Turnstile → 4. field validation and GDPR consent — exactly as today.
- File checks (new), all in memory, before anything is written.
- Store files → create the submission → on any failure delete what was stored.
There is no second entry point, so there is nothing to bypass: REST create on form-uploads is closed, and
REST create on submissions stays "logged-in users only".
File checks, all server-side:
-
Field: a file may only arrive under the key of a
filefield of this form; anything else isunknown_fields. A field hidden by "Show only when" drops its files. Text values under a file key, or files under a text key, are rejected. -
Count: at most
maxFilesper field;requiredneeds 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 PDF starts with %PDF-DOC (and XLS) OLE compound-file signature D0 CF 11 E0 A1 B1 1A E1DOCX ZIP signature and the archive's directory lists [Content_Types].xmlandword/document.xml; an archive withword/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 extend:attachments.fileTypes: { dwg: { label, extensions, mimeType, detect } }. -
Storage key: generated (
<uuid>.<ext of the detected type>); the visitor's filename never reaches the storage layer or a URL. -
Display name: the original name with path parts, control and bidi characters removed, trimmed to 120 characters; stored as text, shown escaped.
-
Download headers, set by the collection itself (no
next.configwiring):Content-Disposition: attachmentwith 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 returnsfile_type. See decision 4.
New result codes, additive: reason: 'validation' with kind: 'file_too_large' | 'file_type' | 'file_count'
and field. required is reused for a missing file.
6. Access
form-uploadsaccess:read= the same rule as reading submissions (defaulteditor+; when the project overridesformSubmissionOverrides.access.read, files follow it automatically).createandupdate= closed for REST and GraphQL (the Local API insubmitFormwrites).delete= the submissions' delete rule (defaultadmin). All of it overridable throughattachments.collectionOverrides.- A row-level submissions rule (one that returns a query, e.g. "only submissions of my forms") is honoured too: the download checks that this user can read the file's own submission.
- A download URL carries only the generated key. Anonymous requests and accounts without submission access get
403/404 whatever URL or ID they try; access is decided by who asks, never by what the link contains. Swapping a
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
- No pre-upload, so no abandoned-form orphans. A file exists on the server only as part of a submission 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 (
afterDeletehook; 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
Panel block file — labels in English and Polish, wording per admin-ux.md:
| Field | Type | Default | Label (en / pl) |
|---|---|---|---|
name |
text, required | — | Field key / Klucz pola |
label |
text, localized | — | Label / Etykieta |
help |
text, localized | — | Help text / Tekst pomocy — "Shown under the field, e.g. accepted types and size." |
width, required |
as other blocks | ||
allowedTypes |
select, many | PDF, DOC, DOCX | Allowed file types / Dozwolone typy plików |
maxSizeMB |
number, 1…ceiling | 10 | Maximum size (MB) / Maksymalny rozmiar (MB) |
maxFiles |
number, 1…ceiling | 1 | Maximum files / Maksymalna liczba plików |
showWhen |
as other blocks |
Block name: File / Plik ("File fields / Pola pliku"). forms.fields.file: false hides the block;
forms.fields.file: <Block> replaces it; fileBlock is exported.
Types: FormsOption.attachments, FormsOption.fields.file; BuilderField gains help, allowedTypes,
maxSizeMB, maxFiles; publicForm passes them to the browser.
useBuilderForm — a file field's value is File[]:
getFileProps(field)→id,name,type: 'file',accept(extensions and MIME types of the allowed types),multiple,required,onChange,aria-invalid,aria-describedby(help + error),ref.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.- The existing
isSubmittingis the pending state. A Server Action gives no upload percentage; the docs say so.
BuilderForm / RenderForm — a native <input type="file"> with a real <label>, the help text, a list of
selected files (aria-live="polite"), and per file a Remove button named "Remove {file}". Keyboard and
touch work because every control is native. New classNames keys: file, help, fileList, fileItem,
fileRemove; data-type="file". Files survive moving between steps. renderField and custom markup on the hook
work as for any field.
Visitor texts — new keys in Form messages (notifications.form), defaults in English and Polish, each
editable per language in the panel (that is where DE and NL come from; labels and help are localized panel fields):
| 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. |
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. |
fileRemove |
Remove {file} | Usuń {file} |
resolveFormMessage maps the new codes; an empty panel field falls back to the default of that language.
9. E-mail and 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 ofemailLayoutshow 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). WithoutserverURLit 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.attachmentsthe generated config is identical to 1.15.5. - Existing forms, submissions, e-mail templates,
submitFormcalls 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, with or withoutattachmentson. - MongoDB: no migration.
- Postgres / SQLite projects that turn it on: one
pnpm payload migrate:create. New: theform_uploadstable, the block tablesforms_blocks_file(+_locales, + the allowed-types table), theform_submissions_submission_uploadsarray table with its_rels, aform_uploads_idcolumn inpayload_locked_documents_rels, and the new Form messages columns. All additive; nothing is dropped or rewritten. - After upgrading and enabling:
generate:types,generate:importmap(the S3 handler is already there in projects that injects3Storage). - Version: a minor release (new feature, no breaking change).
10. Decisions for the owner
Recommendation first in each.
- Default storage.
A private R2 bucket (
R2_PRIVATE_BUCKET), local disk in development, disk-with-volume as a stated opt-in, production refuses to start with neither. — or disk + volume as the default — or also build a GridFS adapter now (zero configuration, but CVs enter every database backup and we maintain the adapter). - Retention.
retentionDaysexists, off by default; the docs recommend a value andipal-doctornotes when attachments are on without one. A plugin update should not start deleting a client's data on its own. — or a default such as 180 days. - Staff link in e-mails.
The
{{*:files}}placeholder, placed by the editor (and by the seed) in the company notification. — or added automatically to every e-mail whose recipient is not an address the visitor typed. - Malware scanning.
None built in; a
scanhook for projects that need it. Downloads are forced attachments and macro-enabled DOCX is refused, but a legacy.doccan carry macros that only the reader's Office blocks. — or require a scanner before.docis accepted.
11. Build plan after the go-ahead
- Prove the transfer (a
Fileinvaluesthrough a Server Action on the reference site), then the storage helper with twos3Storageinstances in one config. forms.attachments, thefileblock, theform-uploadscollection,buildPrivateR2Storage,formUploadLimits.submitFormfile checks, storage, cleanup, sweep, retention; the new result codes and messages.useBuilderForm,BuilderForm,RenderForm; the e-mail row and{{*:files}}.- Tests on a real Payload instance, one group per acceptance test of the request: (1) text-only submit unchanged · (2) PDF, DOC, DOCX each → one submission, downloadable, filename in the staff e-mail · (3) oversized, mismatched, unsupported, extra files and direct calls → no submission, no file · (4) consent, Turnstile, honeypot, rate limit with a file attached → nothing stored · (5) anonymous and no-access accounts refused, staff allowed, no ID substitution · (6) retry, remove, delete a submission → no duplicates, no orphans · (7) texts in four languages, keyboard operation, existing form tests still pass.
- Docs in the same change:
docs/forms.md,docs/storage.md,docs/security.md,docs/deployment.md(volume, body limits),docs/env.md,AGENT.md, theipal-formandipal-referenceskills, the seed template, CHANGELOG "## Unreleased"; a file field on a reference-site demo form. - 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.