Files
ipal-kit/docs/dev/form-attachments-proposal.md
T

22 KiB
Raw Blame History

Form attachments — design proposal (revision 2: e-mail only)

Status: built. This is the design record (revision 2, e-mail only). The owner's decisions on §10: (1) build the Microsoft Graph large-file upload, (2) the visitor sees an error when the e-mail fails, (3) allow legacy .doc / .xls and refuse macros. What shipped and how to use it: forms.md "Files" and email.md "Attachments" — where this record and those pages differ, the pages are right. Request: vanstevpl-web/docs/plugin-requests/2026-11-13-candidate-form-attachments.md. Owner's decision (2026-11-13): "files are not stored at all. just send on e-mail. up to 10MB, filetypes, add security wall."

1. Summary

A new opt-in option, forms.attachments, adds a File field to the form builder. A file a visitor attaches:

  1. passes every existing gate and a set of file checks,
  2. is held in memory for that one request,
  3. is attached to the company notification e-mail through the project's e-mail adapter,
  4. is dropped. Nothing is written to disk, a bucket, the database or a Media record. There is no download 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.

ipalKit({
  forms: {
    attachments: true,     // or { maxSizeMB, maxTotalMB, maxFiles, fileTypes, allowRisky, scan, maxConcurrent }
  },
})

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.

2. Transfer

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
The endpoint (Payload's /api route handler) none from Next; ours: maxTotalMB + 64 KB of fields, enforced while reading —
Next.js Server Actions bodySizeLimit (1 MB) does not apply — files never go through the action —
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

A Content-Length over the limit is refused before a byte is read; a body that lies about its length is cut off at the limit.

3. The security wall

Every step runs before the next one starts. A failure stops the request; nothing after it runs.

# Check Before any file byte is accepted?
1 Method, same-origin (Origin / Sec-Fetch-Site), content type Yes — headers only
2 Rate limit per IP (the existing limiter and bucket) Yes — headers only
3 Declared size over the limit → refused Yes — headers only
4 Concurrency guard: at most maxConcurrent (default 2) file submissions at once per instance; more get "try again in a moment" Yes
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 —

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".

Type checks — by content, never by name or browser MIME alone:

Type Check
PDF starts with %PDF-
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.
DOC, XLS OLE signature D0 CF 11 E0 A1 B1 1A E1; refused when the file carries a VBA macro storage (decision 3)
RTF, JPG, PNG, WebP their signatures

Refused by default, whatever the field allows: executables and scripts (exe, dll, msi, bat, cmd, com, scr, js, vbs, ps1, sh, jar, apk, app, dmg, lnk, hta and the like, by extension and by signature: MZ, ELF, Mach-O, #!), 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 } }.

Further cheap checks included:

  • 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).

No antivirus. The plugin does not scan files for malware. These checks stop the wrong kind of file; they do not prove a PDF or DOC is safe. A project that needs scanning plugs it in: attachments.scan: async ({ name, type, size, data }) => ({ ok, reason? }) (ClamAV, a scanning API). A refusal is reported to the visitor as a file-type error.

New result codes, additive: reason: 'validation' with kind: 'file_too_large' | 'file_type' | 'file_count', and reason: 'delivery' (§6).

4. E-mail size — the real maximum per path

Base64 adds 37%: a 10 MB file is a 13.7 MB message. maxTotalMB (default 10) caps one submission, so one e-mail never exceeds about 14 MB.

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:

Server limit (typical — check the provider) Largest file
10 MB (some shared hosting, Postmark) about 7 MB — a 10 MB field would fail
25 MB (Google Workspace, Mailgun) about 18 MB
35 MB (Microsoft 365 default) about 25 MB

The recipient's mailbox has its own limit as well. The values above are from memory, not measured; the build adds a real test instead of trusting them: Send test e-mail in the panel gets "with a 10 MB attachment".

Microsoft Graph (graphAdapter), checked against Microsoft's documentation on 2026-11-13:

  • sendMail with the file inline works for attachments under 3 MB, with today's Mail.Send permission and saveToSentItems: false.
  • 3 MB to 150 MB needs an upload session: create a draft in the sender mailbox, upload the file in chunks, send the draft. That needs the Mail.ReadWrite application permission, which lets the app read mailboxes unless it is scoped to the one sender mailbox. The draft is sent from the mailbox, so a copy passes through Drafts and lands in Sent Items, and must be deleted afterwards. Microsoft lists a known issue with upload sessions on shared mailboxes, and GRAPH_SENDER is one.
  • The agency's Azure app already has Mail.ReadWrite (application, admin consent granted — confirmed by the owner on 2026-11-13, together with Mail.Read and Mail.Send). So the upload session needs no Azure change.
  • So the real maximum on Graph is under 3 MB with the code as it is, and 10 MB once the upload session is built (decision 1).

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.

When the mail provider rejects the message:

  • 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.

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)
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…cap 10 Maximum size (MB) / Maksymalny rozmiar (MB)
maxFiles number, 1…cap 1 Maximum files / Maksymalna liczba plików
showWhen as other blocks

Block name: File / Plik. forms.fields.file: false hides it; forms.fields.file: <Block> replaces it; 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, maxSizeMB, maxFiles; publicForm passes them to the browser.

useBuilderForm — a file field's value is File[]:

  • getFileProps(field) → id, name, type: 'file', accept, 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); browser checks for count, size and extension with the server's messages.
  • 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, the selected files in a list (aria-live="polite"), and a Remove button per file named "Remove {file}". Every 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 work as for 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, defaults in English and Polish, editable per language in the panel (that is where DE and NL come from; label 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.
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}

8. What the submission keeps, and GDPR

  • 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.

9. Compatibility

  • 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 API change is an added optional argument, field or union member. Text-only forms never touch the endpoint.
  • New dependency: busboy (the streaming multipart parser Payload already ships).
  • MongoDB: no migration.
  • Postgres / SQLite projects that turn it on: one pnpm payload migrate:create. Additive only: the block tables for file (+ locales, + allowed types), the submission's files array table and three columns (delivery, note, attempt key), the new Form messages columns. No upload collection, so no _rels or locked-documents changes.
  • After upgrading and enabling: generate:types. No import-map change, no env variable, no storage setup.
  • Version: a minor release.

10. Decisions for the owner

Recommendation first in each.

  1. Sites that send through Microsoft Graph, files of 3 MB and more. Build the Graph upload session, since the agency app already has Mail.ReadWrite: 10 MB works on Graph with no Azure change. Files under 3 MB keep the inline path. Cost to accept: each larger file passes through the sender mailbox's Drafts and Sent Items; the plugin deletes the draft on failure and the sent copy after sending, and a failed clean-up is logged. The build first tests Microsoft's known issue with shared mailboxes on GRAPH_SENDER; if it blocks the upload, the fallback is the alternative below. — or send those e-mails through the SMTP settings in the panel; without SMTP the limit on Graph is 3 MB. Nothing touches the mailbox, but every Graph site that wants 10 MB needs SMTP set up too.

    Separate from this feature, for the agency to consider: the app's permissions cover all mailboxes of the tenant, and its secret sits in every project's environment. Limiting the app to the forms mailbox (an application access policy in Exchange) would shrink that. Not part of this build.

  2. When the e-mail cannot be sent. The visitor sees an error and can retry; staff get a notice without the file; the submission is marked "Not sent". — or the visitor sees the normal confirmation and staff must ask again.

  3. Legacy .doc (and .xls). The client asked for DOC, but the old format can carry macros and can only be checked roughly. Allow it, refuse files with a macro storage, and say in the docs that this check is best-effort. — or leave .doc out of the default types (PDF and DOCX only); a project can still tick it.

11. Build plan after the go-ahead

  1. Prove the transfer: a streamed multipart request to a Payload endpoint on the reference site, with the read cut off at the limit; confirm the proxy matcher and Traefik behaviour.
  2. forms.attachments, the file block, the endpoint, the wall, the type registry and blocklist, the scan hook.
  3. E-mail: attachments through mailAdapter on SMTP and Graph (inline under 3 MB, then decision 1), the file-carrying rule, the failure notice, delivery state on the submission, the attempt key, the large test e-mail.
  4. useBuilderForm, BuilderForm, RenderForm, the new messages.
  5. Tests on a real Payload instance. The request's seven acceptance tests, re-read for e-mail only: (1) text-only submit unchanged · (2) PDF, DOC, DOCX each → one submission with metadata, the file attached to the staff e-mail, byte-identical, and absent from the customer e-mail · (3) oversized, mismatched, unsupported, executable, macro, archive, double-extension and extra files, and direct calls to the endpoint → no submission, no e-mail · (4) consent, Turnstile, honeypot and rate limit with a file → nothing read past the gate, nothing sent · (5) replaces the download test: no route serves a file, nothing is on disk or in the database after the request, and the endpoint refuses cross-origin calls · (6) retry after a failed send, a 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, 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"), and whether the upload session works on the shared GRAPH_SENDER mailbox.