Compare commits

...
55 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 e603561de4 1.16.3: renumber the prepared release (was 1.17.0)
CI / check (push) Failing after 6m22s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:53:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 e29f882aa6 1.17.0 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 195ca3ab11 1.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 b9df570e84 Merge claude/deps-payload-3-94: Payload 3.94.1, dependency updates, overrides re-checked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 a0c576e54c Dev audit: @swc/cli 0.8.2, vite 7.3.8; Node 22.23.5 check in Coolify
@swc/cli 0.8.0 still resolved piscina 4.9.3 and @xhmikosr/decompress 10.2.1
(the two criticals). 0.8.2 with refreshed transitive deps and vite 7.3.8 as a
direct dev dependency take the dev-tree audit from 31 to 4 (0 high, 0 critical).
Docs: Payload 3.94 needs Node 22.23.5+ also in Coolify; how to check it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 ab51027617 Payload 3.94.1, dependency updates, overrides re-checked
- payload and every @payloadcms/* 3.94.1 in the plugin's dev dependencies, the
  reference site and the starter (peer range unchanged: ^3.90.2); react/react-dom
  19.3.1; reference engines node >=22.23.5 <23 (Payload 3.94's minimum).
- Overrides re-checked: dompurify and happy-dom still needed; mongoose (3.90–3.93)
  and undici (3.90–3.91) only on an older Payload; graphql-scalars no longer needed
  (GHSA-x8rm-f576-gq67 covers 1.24.1–2.0.0; Payload pins 1.22.2). Reference keeps
  dompurify + happy-dom; plugin root drops graphql-scalars.
- ipal-doctor transitive-min: the mongoose fix names the Payload upgrade first.
- nodemailer 10.6.1; dev: playwright 1.65.1, vitest 5.1.1, prettier 3.10.1,
  @swc/cli 0.8, rimraf 6 (clean uses --glob), cross-env 10, open 11,
  sort-package-json 4, @swc-node/register 1.12.1, vite-tsconfig-paths 6.1.1;
  reference tailwind 4.3.5, postcss 8.5.33.
- Kept back: typescript 7, eslint 10, graphql 17, @types/node 26, lucide-react 1.x.
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, PROGRAMISTA §1, forms.md,
  doctor.md; reference skills copy; CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 15:18:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 13b66413f8 1.16.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.2" section. PROGRAMISTA §6: item 63. Reference site: skills
and the AGENTS.md pointer on 1.16.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 5d9bc10cfd 1.16.2
Version bump; the Unreleased section becomes 1.16.2: pnpm.overrides for Payload's
mongoose (8.24.1 → ~8.24.10; GHSA-pcrw-h46h-c93h critical and four more) and
happy-dom (20.x → ^21.0.4; two highs) in the reference site and the starter; new
ipal-doctor rule transitive-min and DoctorContext.installedAll(name). What projects
must update: every MongoDB site adds the two override lines (Postgres/SQLite: the
happy-dom one), reinstalls, rebuilds and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 1917686b52 Merge claude/inspiring-goldstine-66f9c2: mongoose and happy-dom overrides, doctor rule transitive-min
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:18:49 +01:00
Radosław SmolińskiandClaude Fable 5.2 de8362820f Overrides for Payload's mongoose and happy-dom advisories; doctor rule transitive-min
@payloadcms/db-mongodb pins mongoose 8.24.1 (one critical, two high, two moderate
advisories, fixed by 8.24.7) and @lexical/headless 0.50 brings happy-dom 20.x (two
high, fixed by 21.0.4). Payload 3.93.0 fixes neither.

- reference/package.json (and so the starter): pnpm.overrides for mongoose
  (~8.24.10) and happy-dom (^21.0.4); pnpm audit --prod on the reference is clean
- root package.json: the happy-dom override for the plugin's own dev tree
- ipal-doctor: transitive-min reports mongoose 8.x < 8.24.7 (error) and
  happy-dom < 21.0.4 (warning) from the lockfile and prints the override line;
  DoctorContext.installedAll(name)
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, doctor.md, README, CHANGELOG

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-17 00:01:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 7c034a07ef 1.16.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.1" section. PROGRAMISTA §6: item 62. Reference site: skills
and the AGENTS.md pointer on 1.16.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 5c9eeaf330 1.16.1
Version bump; the Unreleased section becomes 1.16.1: Next.js 16.4.6 in the plugin,
the reference site and the starter; minimum safe version 16.4.5 because of
GHSA-mfr8-8qww-v76h (16.3.0–16.4.4); ipal-doctor next-min raised. What projects
must update: every site below 16.4.5 runs
`pnpm add [email protected] [email protected]` and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:10 +01:00
Radosław SmolińskiandClaude Opus 5.5 ad6011b66a Merge claude/next-16-4-6: Next.js 16.4.6, minimum safe 16.4.5 (GHSA-mfr8-8qww-v76h)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:02 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b03c94979 Next.js 16.4.6; minimum safe version 16.4.5 (GHSA-mfr8-8qww-v76h)
Next.js 16.3.0–16.4.4 is affected by GHSA-mfr8-8qww-v76h (CVE-2026-119790, moderate:
information disclosure across root params when a 'use cache' function is called
through unstable_cache()), first patched in 16.4.5.

- next and eslint-config-next 16.4.6 in the plugin's dev dependencies and the
  reference site (the starter is generated from it); lockfiles refreshed.
- ipal-doctor next-min: error below 16.4.5, naming the advisory; fix
  `pnpm add [email protected] [email protected]`; still silenceable. Tests.
- AGENT.md §4 item 11, ipal-setup, ipal-upgrade, doctor.md: minimum 16.4.5;
  reference skills copy refreshed. CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:45:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 ba3d57a77a 1.16.0 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.0" section. PROGRAMISTA §6: item 61. Reference site: skills
and the AGENTS.md pointer on 1.16.0; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:19:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 7f0c2f9d72 1.16.0
Version bump; the Unreleased section becomes 1.16.0: files on panel forms, checked,
e-mailed to the company and never stored (forms.attachments, File field, streamed
endpoint with the security wall and abort/timeout handling); attachments over SMTP
and Microsoft Graph (upload session, mailbox copy deleted); test e-mail with a
10 MB file; Turnstile reset and BuilderForm honeypot fixes; Graph token cache.
What projects must update: nothing required; to use files — option, File field,
migration on Postgres/SQLite, formClasses keys, proxy body limit, Graph
Mail.ReadWrite or SMTP. Verify on real systems: Graph 10 MB send and cleanup,
Traefik timeout on a slow upload, SMTP size limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:18:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 3cde9974d0 Merge claude/form-attachments-9694cb: files on forms, e-mailed and never stored
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:13:55 +01:00
Radosław SmolińskiandClaude Fable 5.2 6f006825a4 Form files: an upload aborted while the gates are pending no longer leaves its attempt key registered
Re-review of 1.16.0: beforeFiles could resume after the request was answered and
register the attempt key with nobody left to release it. It now stops after every
await once the request is over; the registration has no await before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:09:14 +01:00
Radosław SmolińskiandClaude Fable 5.2 7ecfb26eb1 Reference: refreshed skills copy (upload timeouts)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:04:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd74d7decb Reference: refreshed skills copy and generated types for the file messages
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:52:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 97202ee03e Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:51:05 +01:00
Radosław SmolińskiandClaude Fable 5.2 b6f9f34705 Form attachments: tests for project options and the concurrency guard
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:44:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 ea43d94dd2 Reference index: describe the mail sink
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:43:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 fdb6140c09 Form attachments: reference smoke test with a mail sink, Turnstile reset fix, docs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:42:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 387debc88c WIP: reference site — File field on the quote form, mail sink smoke test
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:34:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 b7fb1b0e31 WIP: form attachments — agent guide, skills, seed template, changelog
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:32:45 +01:00
Radosław SmolińskiandClaude Fable 5.2 344574d6bd WIP: form attachments docs (forms, email, security, storage, deployment, notifications), honeypot value sent
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:30:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 701bb420c1 WIP: form attachments — unit tests, test e-mail with attachment, lint
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:28:22 +01:00
Radosław SmolińskiandClaude Fable 5.2 02b1e96d3d WIP: form attachments tests
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:24:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 6003b3d7d7 WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:20:02 +01:00
Radosław SmolińskiandClaude Fable 5.2 0ba0014ed5 Form attachments proposal: Graph upload session recommended (Mail.ReadWrite already granted)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:04:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 62bed415ed Form attachments proposal: e-mail only, no storage (revision 2)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:01:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 d2caf8c2ae Form attachments: design proposal
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:55:45 +01:00
Radosław SmolińskiandClaude Opus 5.5 755f510c9f 1.15.5 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.5" section. PROGRAMISTA §6: item 60. Reference site: skills
and the AGENTS.md pointer on 1.15.5; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 970307f3ab 1.15.5
Version bump; the Unreleased section becomes 1.15.5: required fields with
references are seeded complete; a stricter dry run (missing $form / $page is an
error there too). What projects must update: nothing required; a required reference
cycle now fails clearly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław Smoliński c7e198fd92 Merge claude/seeder-required-refs: required fields with references are created complete
createSeeder's first pass resolves { $page } / { $form } references to existing
records, so a required layout is created complete; a forward $page is filled in
pass 2 and a record whose required field needs it waits for that page. Required
cycles and never-appearing targets are an error with nothing written; the dry run
reports the same, including a missing $form. Guards, create-only, the edit check
and SEED_ONLY are unchanged. Reported from vanstevpl-web.
2026-11-13 14:31:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 748ef9286f Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).

- pass 1 resolves references to records that exist (or were created earlier in
  the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
  pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
  are an error with nothing written; unknown page targets are found while
  planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
  in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
  target, optional and required forward links, a cycle, missing page and form,
  create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:29:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 Merge claude/seeder-localized-arrays: whole localized arrays keep every language
createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 4d1de4c66a 1.15.3 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.3" section. PROGRAMISTA §6: item 58. Reference site: skills
and the AGENTS.md pointer on 1.15.3; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 3edf8865ed 1.15.3
Version bump; the Unreleased section becomes 1.15.3: ipal-audit and ipal-doctor no
longer report the panel's bilingual labels (adminText(), { en, pl }) as hardcoded
text; public text is still reported. What projects must update: nothing required;
pnpm ipal:skills for the updated audit scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław Smoliński 594b958bb2 Merge claude/audit-admin-labels: the panel's bilingual labels are not hardcoded text
ipal-audit and the doctor's i18n-literals read the syntax tree (polish-literals.mjs,
a plain grep without TypeScript): adminText(), { en, pl } as label, singular, plural,
description, placeholder or group, a rowLabel() fallback and const x: AdminText in a
schema file are accepted. Still reported: every .tsx file, Polish-only labels, other
keys, anything under defaultValue. Reported from the Niezly Dandys project.
2026-11-05 12:59:28 +01:00
Radosław SmolińskiandClaude Opus 5.5 f73465c3bb ipal-audit, ipal-doctor: the panel's bilingual labels are not hardcoded text
"Hardcoded Polish text in code" (i18n-literals) grepped every string, so adminText() and { en, pl }
labels in schema files were reported, though AGENT.md 6.5a asks for them. polish-literals.mjs reads
the syntax tree with the project's TypeScript (a plain grep without it) and spares those forms in
schema files only; every .tsx file, Polish-only labels, other keys and defaultValue still fail.
Reported by Niezly Dandys (1.15.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:55:44 +01:00
Radosław SmolińskiandClaude Opus 5.5 36b27ed323 1.15.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.2" section. PROGRAMISTA §6: item 57. Reference site: skills
and the AGENTS.md pointer on 1.15.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:08:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 627cad792a 1.15.2
Version bump; the Unreleased section becomes 1.15.2: ipal-doctor finds the frontend
route group by structure (any app/(<group>) with the catch-all page, layout.frontend
override, findFrontend), accepts notFoundView.ts/.tsx. What projects must update:
nothing required; remove a temporary layout-required silence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:08:08 +01:00
Radosław Smoliński c33b264306 Merge claude/doctor-route-groups: ipal-doctor finds the frontend by structure
layout-required takes any app/(<group>) (or app) that holds the catch-all page, a
localized one first, instead of the literal (frontend); two candidates warn.
notFoundView may be .ts or .tsx; required files accept their usual extensions.
ipal-doctor.json layout.frontend wins; new export findFrontend. Reported from the
Say Diamonds project.
2026-11-03 15:04:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 b80770bc2e ipal-doctor: find the frontend route group by structure, accept notFoundView.tsx
layout-required no longer assumes src/app/(frontend): any app/(<group>) (or app itself) holding the
catch-all page is the frontend, a localized one first; two candidates give a warning naming both.
notFoundView.ts or .tsx, and the usual extensions for the other required files. New
ipal-doctor.json layout.frontend override and export findFrontend. Reported by Say Diamonds
(1.15.1, route group (site)).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:00:05 +01:00
Radosław SmolińskiandClaude Opus 5.5 a515bd6851 1.15.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.1" section. PROGRAMISTA §6: item 56. Reference site: skills
and the AGENTS.md pointer on 1.15.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 09bff6a683 1.15.1
Version bump; the Unreleased section becomes 1.15.1: guardSeedExit() (a seed that
ends early exits 1 with the reason), wired into the seed templates and the
reference site; reference smoke tests start their own server. What projects must
update: nothing required; add guardSeedExit(), check echo $? after a seed in Coolify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 e715b5720d Reference smoke tests never test another project's server; skills refreshed
- reference/playwright.config.ts: reuseExistingServer only with E2E_REUSE_SERVER=1.
  Playwright starts the built site itself on E2E_BASE_URL's port (default 3100) and
  fails when the port is taken — before, a dev server of another project on 3100
  (intecion.com's) was tested instead. CI is unchanged: it starts nothing before
  test:e2e. README's production check follows.
- reference/.agents/skills refreshed after the seed-exit-guard merge (ipal-form and
  ipal-site seed templates, ipal-reference); INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:24:05 +01:00
Radosław Smoliński 03515c66c4 Merge claude/seed-exit-guard: guardSeedExit() — a seed that ends early exits 1, never a silent 0
guardSeedExit() (@intecion/ipal-kit/seed, opt-in): a beforeExit guard exits 1 with
the reason when a seed run ends before Payload initializes or before summary();
createSeeder and summary() mark the stages. Wired into the reference seed and the
ipal-site / ipal-form seed templates. Normal exit codes are unchanged.
2026-10-29 19:23:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 f789e36636 Seeds: guardSeedExit() — a run that ends early exits 1 with the reason, never a silent 0
payload run starts the CLI with `void start()` and imports the script; when the script's top-level await
is left without live handles, Node exits with code 0 and no output — a success in Coolify's Terminal.
guardSeedExit() (@intecion/ipal-kit/seed, dependency-free) listens for beforeExit: until summary() runs it
prints "[seed] ended before Payload initialized" / "… before the seed finished" and exits 1. createSeeder
marks the run initialized, summary() finished; process.exit paths (normal, errors, the production
refusals) are untouched. Wired into the ipal-site and ipal-form seed templates and the reference seed, so
ipal-kit create sites get it. Tests include a real child process started like payload run.
Docs: seeding.md, deployment.md §4.7, AGENT.md, ipal-reference (+ api.md), CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:19:14 +01:00
114 changed files with 9847 additions and 1882 deletions
+11 -8
View File
@@ -77,10 +77,12 @@ site with every team convention, installs it from a shipped lockfile and makes t
`nodemailer`, `lucide-react`, `slugify` and `server-only` are regular
`dependencies` of the plugin — they install with it; don't add them yourself.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**; Payload 3.94 itself needs **Node.js 22.23.5 or later**
on the 22 line.
What you provide are the **peer dependencies** — packages the plugin shares with
your project — in a version matching your Payload:
your project — in a version matching your Payload. The plugin accepts Payload `^3.90.2`; the reference site and the starter use
**3.94.1** (with `react` / `react-dom` 19.3.1, which Payload 3.94 requires):
| Peer | Range | Notes |
|---|---|---|
@@ -91,16 +93,17 @@ your project — in a version matching your Payload:
| `@payloadcms/storage-s3` | `^3.90.2` | optional — only when media go to Cloudflare R2 ([docs/storage.md](./docs/storage.md)) |
```bash
pnpm add @payloadcms/[email protected]0.2 @payloadcms/[email protected]0.2 \
pnpm add @payloadcms/[email protected]4.1 @payloadcms/[email protected]4.1 \
@clocklimited/payload-2fa
pnpm add @payloadcms/[email protected]0.2 # only with R2 media
pnpm add @payloadcms/[email protected]4.1 # only with R2 media
```
Keep every `@payloadcms/*` at exactly the same version as `payload`
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: with
`payload` 3.90.x, Payload's own tree pins a vulnerable `undici`, `dompurify` and
`graphql-scalars` (the last one even in the latest Payload) — add the three overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md) (recommended, not
required by the plugin). Upload optimization and image
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: even
Payload 3.94.1 brings a vulnerable `happy-dom` (via Lexical) and `dompurify` — add
the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md); an older Payload
also needs the `mongoose` (MongoDB adapter, up to 3.93) and `undici` (up to 3.91)
ones listed there (recommended, not required by the plugin). Upload optimization and image
placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
(standard in a `create-payload-app` project).
+312
View File
@@ -8,6 +8,318 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## 1.16.3
### Changed
- **Payload 3.94.1** in the reference site and the project starter (was 3.90.2), with `react` / `react-dom` 19.3.1 and
Node.js `>=22.23.5 <23` in the reference `engines`. The plugin is built and tested against 3.94.1; its peer range is
unchanged (`^3.90.2`), so a project on 3.90.x is not forced to move. What Payload 3.91–3.94 change that a project
notices: Node.js 22.23.5 or later (24.22.3 / 26.13.1 on newer lines), `react` ^19.3.1, Next.js 16.4.5 or later,
`@payloadcms/db-mongodb` ships `mongoose` 8.24.7 (3.94.0), the `deepmerge` dependency is gone (3.94.1), field access
now receives the document id, draft read access and block child read access are checked more strictly, and the slug
field no longer fails required validation on create (a 3.90.2 bug). Nothing in the plugin needed a code change; the
generated types and the import map of the reference site are unchanged.
- **Overrides re-checked against Payload 3.94.1** (AGENT.md §4 item 12): `dompurify` and `happy-dom` are still needed
(Lexical still brings `happy-dom` ^20.9.0: two highs). `mongoose` (MongoDB, Payload 3.90–3.93) and `undici` (Payload
3.90–3.91) are needed only on an older Payload. **`graphql-scalars` needs no override any more**: GHSA-x8rm-f576-gq67
now covers 1.24.1–2.0.0 only, and `@payloadcms/graphql` pins 1.22.2. The reference site and the starter keep only the
`dompurify` and `happy-dom` lines.
- **ipal-doctor `transitive-min`:** the `mongoose` finding names the Payload upgrade (3.94.1) as the first fix; the
thresholds are unchanged.
- Dependencies: `nodemailer` 10.6.1 (runtime). Dev tooling: Playwright 1.65.1 (run `pnpm exec playwright install
chromium` once), Vitest 5.1.1, Prettier 3.10.1, `@swc/cli` 0.8.2 (with `piscina` 4.9.4 and `@xhmikosr/decompress` 11: clears the two critical dev
advisories), `vite` 7.3.8 as a direct dev dependency (Vitest's peer; clears the vite high), `rimraf` 6,
`cross-env` 10 (also in the reference site), `open` 11, `sort-package-json` 4, `@swc-node/register` 1.12.1,
`vite-tsconfig-paths` 6.1.1, Tailwind 4.3.5 and PostCSS 8.5.33 in the reference site. `pnpm audit` of the plugin's
dev tree: 31 → 4 (0 critical, 0 high; what is left sits under `drizzle-kit` and the ESLint toolchain). `--prod` stays
at 0, and the reference site at 0.
- Kept back, with the reason: TypeScript 7 (typescript-eslint supports TypeScript below 6.1 only), ESLint 10
(`eslint-config-next` 16.4.6 plugins do not support it — the lint run crashes), `graphql` 17 (Payload requires
^16.8.1), `@types/node` 26 (projects stay on Node 22), `lucide-react` 1.x (a runtime dependency: projects are told to
keep their own lucide on 0.400.x; moving needs its own change and icon-map checks).
### What projects must update
- **Nothing is required.** The plugin still works with Payload 3.90.2 and later.
- **Recommended — move to Payload 3.94.1** (the `ipal-upgrade` skill, "Every upgrade — Payload"): every `payload` /
`@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1, Node.js 22.23.5
or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` stays `22`), `pnpm install`, `pnpm payload generate:types`,
`pnpm payload generate:importmap`, `rm -rf .next`, build, redeploy on Coolify. Postgres/SQLite: run
`pnpm payload migrate:create` and commit it if it is not empty (Payload 3.94.1 changes how long index and foreign
key names are built). MongoDB: no migration.
- **Node.js 22.23.5 or later everywhere the site runs — before you move to Payload 3.94.** Payload 3.94 refuses older
Node (`engines`: `^22.23.5 || ^24.22.3 || >=26.13.1`). Locally: `node -v`. **Coolify:** Nixpacks picks the Node major
from `engines` / `.nvmrc`, and the patch version comes from the Nixpacks release on the server — so after the first
deploy open the app → Terminal and run `node -v` (the build log shows it too). If it is below 22.23.5, update Coolify
(newer Nixpacks) before you deploy Payload 3.94; until then, stay on 3.90.x. CI images (`node:22` / `setup-node`
with `22`) must resolve to 22.23.5 or later as well.
- **Overrides** (`pnpm.overrides`): on 3.94.x keep `"dompurify@<3.4.17": "^3.4.17"` and
`"happy-dom@<21.0.4": "^21.0.4"`; the `mongoose` and `undici` lines do nothing there — remove them. Remove
`"graphql-scalars@<2.0.1": "^2.0.1"` if you have it (optional). Sites that stay on 3.90–3.93 keep the 1.16.2 lines.
- **Verify:** `pnpm ls payload` → 3.94.1; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no
`versions` finding; the panel opens and a document saves; a form submission arrives.
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.2
### Security
- **`mongoose` and `happy-dom` overrides for Payload's own dependencies.** `@payloadcms/db-mongodb` pins `mongoose`
8.24.1 exactly (still so in Payload 3.93.0). 8.x below 8.24.7 has five advisories published 2026-11-10:
[GHSA-pcrw-h46h-c93h](https://github.com/advisories/GHSA-pcrw-h46h-c93h) (critical, `sanitizeFilter` not applied on
`countDocuments`; fixed in 8.24.3), [GHSA-gg4r-jv3p-qx3c](https://github.com/advisories/GHSA-gg4r-jv3p-qx3c) and
[GHSA-8332-j7wj-wjw4](https://github.com/advisories/GHSA-8332-j7wj-wjw4) (high),
[GHSA-wr5m-5jph-8m96](https://github.com/advisories/GHSA-wr5m-5jph-8m96) and
[GHSA-6972-9mcm-vhwj](https://github.com/advisories/GHSA-6972-9mcm-vhwj) (moderate) — all fixed in 8.24.7.
`@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 brings `happy-dom` 20.x, which has
[GHSA-c8p4-j97h-3vg8](https://github.com/advisories/GHSA-c8p4-j97h-3vg8) (high, fixed in 21.0.0) and
[GHSA-834v-8h66-3h79](https://github.com/advisories/GHSA-834v-8h66-3h79) (high, fixed in 21.0.4). The plugin has no
part in either; only the project's lockfile can lift them. The reference site and the project starter now carry
`"mongoose@>=8 <8.24.7": "~8.24.10"` and `"happy-dom@<21.0.4": "^21.0.4"` in `pnpm.overrides`; with them
`pnpm audit --prod` on the reference site reports no known vulnerabilities, and its seed, production build, smoke
tests and doctor pass. The plugin forces neither override on a project.
### Added
- **ipal-doctor `transitive-min`** (group `versions`): reports a `mongoose` 8.x below 8.24.7 (error) and a `happy-dom`
below 21.0.4 (warning) anywhere in the dependency tree, read from `pnpm-lock.yaml`, and prints the exact
`pnpm.overrides` line. Silence it in `ipal-doctor.json` like any rule
(`"transitive-min": { "off": true, "reason": "…" }`). `DoctorContext.installedAll(name)` is the building block for
your own rules on transitive packages.
### Changed
- AGENT.md §4 item 12, the `ipal-setup` and `ipal-upgrade` skills, doctor.md and the README list five overrides.
### What projects must update
- **Every MongoDB site** (`@payloadcms/db-mongodb`): add the two lines to `pnpm.overrides` in `package.json`, next to
the existing `dompurify` / `graphql-scalars` / `undici` entries:
```json
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10"
```
then `pnpm install`, `pnpm build`, commit `package.json` and `pnpm-lock.yaml`, redeploy on Coolify. No data change,
no migration, no import map change. The selectors only touch the vulnerable versions: a mongoose 9 or a mongoose
8.24.7 and later is left as it is.
- **Postgres / SQLite sites:** only the `happy-dom` line (they have no mongoose).
- **Verify:** `pnpm why mongoose happy-dom` → mongoose 8.24.10 (MongoDB sites), happy-dom 21.0.4; `pnpm audit --prod` →
no high or critical; `pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.1
### Security
- **Next.js 16.4.6; the minimum safe version is now 16.4.5.** Next.js 16.3.0–16.4.4 is affected by
[GHSA-mfr8-8qww-v76h](https://github.com/advisories/GHSA-mfr8-8qww-v76h) (CVE-2026-119790, moderate): information
disclosure across root params when a `'use cache'` function is called through `unstable_cache()`. Fixed in 16.4.5.
This is the advisory behind the `pnpm dev` warning "Next.js 16.4.3 is affected by a known security vulnerability".
The plugin's dev dependencies (`next`, `eslint-config-next`), the reference site and the project starter move to
16.4.6. The Next.js 15 lines Payload 3.90 accepts are not affected by this advisory but still carry older critical
ones, so 16.4.x stays the only safe line. The plugin's peer range is unchanged (`next >=15`).
### Changed
- **ipal-doctor `next-min`** now reports `next` below 16.4.5 as an error, naming GHSA-mfr8-8qww-v76h (below 16.4.1 it
still names the RCE and DoS advisories). The fix it prints: `pnpm add next@16.4.6 eslint-config-next@16.4.6`. It can
be silenced in `ipal-doctor.json` as before (`"next-min": { "off": true, "reason": "…" }`).
- AGENT.md §4 item 11, the `ipal-setup` and `ipal-upgrade` skills and doctor.md state 16.4.5 as the minimum.
### What projects must update
- **Every client site below Next.js 16.4.5:** `pnpm add next@16.4.6 eslint-config-next@16.4.6`, `rm -rf .next`,
`pnpm build`, commit the lockfile and redeploy on Coolify. `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no
`next-min` finding; `pnpm dev` prints no security warning. No plugin option, migration or import map change.
- `pnpm ipal:skills` brings the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.0
### Added
- **Files on forms, sent by e-mail and never stored** (`forms: { attachments: true }`, [forms.md](./forms.md) "Files").
A new **File** field in the form builder: label and help text per language, required, allowed file types,
maximum size and number of files, "Show only when". A file a visitor attaches is checked, attached to the
company notification e-mail and dropped. There is no upload collection, bucket, disk write or download route;
the submission keeps the file's name, type and size and whether the mail server took the message.
- **Checks, in order, before a file is accepted:** same origin, rate limit, declared size, a concurrency guard,
honeypot, Turnstile, field validation and GDPR consent, then per file: count, name (double and refused
extensions), size while reading, content signature, container and macro checks. An upload that breaks off,
stalls (`submit.idleTimeoutMs`, 30 s) or runs too long (`submit.timeoutMs`, 5 minutes) is given up and frees
everything it held. Programs, scripts,
macro-enabled Office files, archives, HTML and SVG are refused unless the project allows the extension
(`allowRisky`). **No antivirus is built in** — `attachments.scan` is the hook for one.
- **E-mail:** the file goes to every e-mail of the form whose recipients are fixed addresses from the panel; an
e-mail addressed with a placeholder (the confirmation to the visitor) never carries it. `{{field}}`, `{{*}}` and
`{{*:table}}` show the file name.
- **The visitor is told when the problem is the file:** too large (with the limit), a format the field does not
take (with the formats), a refused file (a program, an archive, macros, content that does not match), too many
files, or a file that could not be e-mailed. Each message names the file, says what to do, shows at the File
field, and on an optional field adds "You can also send the form without the file." What the visitor typed
stays in the form. A failure that is not about the file keeps its own message.
- **A failed send is visible:** the visitor sees "We could not send the file …" and can retry, staff get the
notification without the file, the submission is marked **File delivery: Not sent**. A repeated request
(double click, a resend) sends nothing twice.
- Browser: `RenderForm` / `BuilderForm` render a native file input with help text, the list of picked files and
a "Remove" button; `useBuilderForm` gains `getFileProps`, `getFiles`, `removeFile`, `helpId`,
`getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`.
- New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`), English and Polish defaults.
- New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`,
`mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`);
`splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' |
'file_type' | 'file_refused' | 'file_count'` and `reason: 'delivery'`.
- **Attachments over both e-mail transports** ([email.md](./email.md) "Attachments"). SMTP passes them through.
Microsoft Graph sends attachments under 3 MB in the one `sendMail` call; larger ones go through a draft and an
upload session, and the copy the mailbox keeps is deleted afterwards. That path needs the `Mail.ReadWrite`
application permission (limit it to the forms mailbox — steps in email.md). Without the permission the message
goes over SMTP when the panel has SMTP settings; otherwise the form's file limit drops to about 2.8 MB.
`mailAdapter({ graph: { largeAttachments: false } })` turns the large path off.
- **Test e-mail with a 10 MB file:** a checkbox next to "Send test e-mail" (endpoint body `attachmentMB`) — shows
whether the mail server takes a file of that size.
### Fixed
- **A form can be sent again after the server refused it.** After a refused submission (a field error from the
server, a failed e-mail) `useTurnstile().reset()` cleared the token but never asked the widget for a new one, so
with Turnstile on, the next click on Send answered "The form could not be sent" without sending anything.
`reset()` now makes the widget issue a new token (`Turnstile` takes a `resetSignal` prop for your own wiring).
No project change.
- **The honeypot of `BuilderForm` / `RenderForm` now reaches the server.** The hidden field was rendered, but its
value was not part of what the form sent, so a bot that filled it was not dropped. It is now sent with the
submission (`createSubmitAction` checks and strips it, as before). A hand-written action that calls `submitForm`
directly must strip `HONEYPOT_FIELD` first, as the example in forms.md always did — otherwise a filled honeypot
is answered with "unknown field" instead of the fake success.
### Changed
- The Microsoft Graph access token is cached in the process until a minute before it expires (it was fetched on
every send).
### What projects must update
- **Nothing is required; existing forms need nothing.** Without `forms.attachments` the forms config, collections,
routes and e-mails are unchanged, and a form without a File field behaves as before even with the option on.
`pnpm ipal:skills` brings the updated `ipal-form` / `ipal-reference` skills.
- **Import map:** no new admin component — `pnpm payload generate:importmap` changes nothing (running it is harmless).
- To use files on forms: set `forms: { attachments: true }`, add a **File** field to the form (panel or seed), keep
one e-mail with a fixed recipient on that form, run `pnpm generate:types`. **Postgres / SQLite:**
`pnpm payload migrate:create` (the File block tables, three columns and one array table on submissions, the new
Form messages columns — all additive). MongoDB: no migration.
- Add the classes `file`, `help`, `fileList`, `fileItem`, `fileRemove` to `src/components/forms/formClasses.ts`
(template in the `ipal-form` skill) and fill Form messages → Files for languages other than English and Polish.
- **Proxy body limit** ([deployment.md](./deployment.md) "Form files"): the browser posts up to `maxTotalMB`
(10 MB) plus the answers to `/api/ipal/forms/submit`. 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. Keep `/api` out of the i18n
proxy matcher (the default one does).
- **Mail transport for files:** with Microsoft Graph, grant `Mail.ReadWrite` (application permission) limited to the
forms mailbox with an application access policy ([email.md](./email.md)), **or** fill SMTP settings in Site
integrations (files of 3 MB and more then go over SMTP), **or** accept a limit of about 2.8 MB per form. With SMTP
only, nothing to grant — the mail server's own size limit applies. Send the test e-mail with the 10 MB file once
per site.
### Verify on your real systems
The plugin's tests use a mock of Microsoft Graph and a local mail sink; check these once on the real setup:
- [ ] **Graph, 10 MB file:** a form submission with a 10 MB file arrives with the attachment; the sender mailbox keeps
**no draft and no copy in Sent Items** a minute later, and no draft after a failed send either. Checklist:
[email.md](./email.md) "Verify on the real tenant".
- [ ] **Traefik timeout on a slow upload:** a 10 MB upload over a throttled connection (browser dev tools, "Slow 4G")
finishes; if it is cut, raise the entry point's `respondingTimeouts.readTimeout`.
- [ ] **SMTP size limit:** the test e-mail with the 10 MB file is accepted by the SMTP server (many limit a message to
10–25 MB, and base64 adds a third); if not, lower `maxSizeMB` / `maxTotalMB` or use Graph.
## 1.15.5
### Fixed
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
page created later in the same call is filled in the second pass, and a record whose required field needs that page
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
### Changed
- **A stricter dry run:** `SEED_DRY_RUN=1` with a `{ $form }` to a form that neither exists nor is seeded earlier in the
same run is now an error, as the real run would be (before, the dry run printed a placeholder and reported a create).
The same holds for a `{ $page }` that never appears.
### What projects must update
- Nothing is required: seed scripts need no change.
- A seed with a required reference cycle (two new pages whose required fields link to each other) now stops with a
clear error naming the pages, and nothing is written for them; make one of the links optional or seed one page
first. Before, such a run could look successful in the dry run and fail on validation in the real one.
- A dry run that now reports a missing form or page: seed that record first (or create it in the panel), then run again.
## 1.15.4
### Fixed
- **Seeding whole localized arrays** (`createSeeder`, `writeLocales`): a value written per language as a whole —
`fields: { pl: [...], en: [...], de: [...] }`, a page `layout`, a global array — now keeps the stored row ids in every
language. Before, each locale write made new shared rows and only the last language survived (form fields, nested
select options, layouts, global arrays); an editor's later save could then fail validation. Fields that are
themselves `localized: true` (a localized layout) keep rows per language, as before. Seed scripts need no change;
repairing records an earlier seed already wrote: "What projects must update".
### What projects must update
- Nothing is required: seed scripts need no change.
- A project that seeded whole localized arrays (form fields with options, a page `layout`, a global array written as
`{ pl: [...], en: [...] }`) and lost languages: a plain re-run skips existing records (create-only), so rewrite them
with `SEED_UPDATE=1` — **locally first**, then check every language in the panel. On a live site only for the named
records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1 IPAL_SEED_ALLOW_PROD_UPDATE=1`, `SEED_DRY_RUN=1` first,
after a backup (Coolify). Records an editor changed since seeding are skipped — fix those in the panel. A global
array: `fillGlobal` fills empty fields only, so clear the field in the panel before the run, or fix it by hand.
## 1.15.3
### Fixed
- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish
text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`,
the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's
TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or
`blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`,
`plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several
lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
### What projects must update
- Nothing is required.
- Run `pnpm ipal:skills` after upgrading, so the updated audit scripts reach the project: the **ipal-audit** skill runs
the project's own copy in `.agents/skills/ipal-audit/scripts` (`audit.sh`, `polish-literals.mjs`); `ipal-doctor` already
uses the plugin's.
## 1.15.2
### Fixed
- **ipal-doctor finds the frontend by structure, not by the name `(frontend)`.** A site with its pages in another route
group (`src/app/(site)/[locale]`) was treated as single-language: false "missing" routes and a demand for the
single-language Markdown route. `layout-required` now takes any `app/(<group>)` (or `app` itself) that holds the
catch-all page, a localized one first; two candidates give a warning naming both. The lazy 404's server action may be
`notFoundView.ts` or `notFoundView.tsx` (pages.md), and the other required files accept their usual extensions
(`.ts`/`.tsx`, route `.js`). New: `ipal-doctor.json` `"layout": { "frontend": "src/app/(site)" }` for a layout the
doctor cannot tell; new export `findFrontend`.
### What projects must update
- Nothing is required.
- After upgrading, remove any temporary `layout-required` silence in `ipal-doctor.json` that was added for a route group
with another name (e.g. `(site)`) or a `notFoundView.tsx`, then run `pnpm exec ipal-doctor` again. Only if the doctor
reports two frontend candidates: set `"layout": { "frontend": "src/app/(<group>)" }`.
- `pnpm ipal:skills` for the updated `ipal-doctor` and `ipal-reference` skills.
## 1.15.1
A seed run that stops early now fails loudly instead of looking like a success.
### New
- `guardSeedExit()` in `@intecion/ipal-kit/seed` ([seeding.md](./seeding.md)): call it first in a seed script. A run that
ends before Payload initializes or before `summary()` — `payload run` exits with code 0 and no output when the
script's top-level await is left without anything that keeps Node running — now prints `[seed] ended before Payload
initialized` / `… before the seed finished` and exits 1. `createSeeder` and `summary()` report to it; normal runs, dry
runs, write errors and the production refusals keep their exit codes and messages. Also `activeSeedExitGuard()` and
the types `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`.
- The seed templates (`ipal-site`, `ipal-form`) and the reference site call it, so sites made with `ipal-kit create` have it.
### Changed
- Reference site (not shipped): the Playwright smoke tests start their own server and fail when the port is taken
(`reuseExistingServer` only with `E2E_REUSE_SERVER=1`), so another project's dev server is never tested by mistake.
### What projects must update
- Nothing is required.
- Recommended: add `guardSeedExit()` (imported from `@intecion/ipal-kit/seed`) as the first statement of every seed
script, before `getPayload()`; without it nothing changes. A guarded script must end with `seed.summary()` (the seed
templates do), otherwise it exits 1 as "ended before the seed finished".
- **Check in Coolify:** after a seed in the app's Terminal, `echo $?` must print `0`; `1` with a `[seed] ended …` line
means the run stopped early and nothing after that point was written — run it again.
- `pnpm ipal:skills` for the updated `ipal-site` / `ipal-form` seed templates and `ipal-reference`.
## 1.15.0
A new site in one command (`ipal-kit create`), built from a complete reference site; `ipal-doctor`, which checks any site
+50 -24
View File
@@ -51,6 +51,8 @@ stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (d
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with
`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below:
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
instead of a silent 0 that looks like success in Coolify's Terminal.
- Seeds are create-only and idempotent: match by the default-locale slug / form title / the global, skip what exists.
- Never delete; never seed users, passwords or secrets; globals: fill only empty fields; no media uploads.
- Every locale written separately with `fallbackLocale: false`; `context: { disableRevalidate: true, ipalSkipIndexNow: true }`.
@@ -218,6 +220,7 @@ Do not make the provider or the widget conditional in code — always wire them.
| Instead of the plugin | Why not | Use |
|---|---|---|
| your own form with fields in JSX, `react-hook-form`, `formik`, your own form renderer | the client cannot change the fields; no Turnstile, rate limit, GDPR consent; a copy of the engine passes addresses from the Emails tab into HTML | the builder in the panel + `<RenderForm>` (look: `formClasses`, unusual cases: `useBuilderForm`) |
| a file input wired by hand, your own upload route, form files saved to Media / R2 / disk | candidate and customer documents end up public or kept forever; no type, size or macro checks; the gates are skipped | `forms: { attachments: true }` + the **File** field — the file is e-mailed to the company and never stored (forms.md "Files") |
| your own `api/contact` / `api/send` / `api/form` route, `nodemailer` / `resend` / `@sendgrid` in the project | bypasses the `submitForm` validation and gates, a second mail transport | the `sendForm` server action → `submitForm`, mails from Forms → Emails via `mailAdapter()` |
| reCAPTCHA, hCaptcha, your own captcha | a second mechanism, no status in the panel | Turnstile from the plugin |
| a hand-written `<script type="application/ld+json">` | no escaping, drifts from the panel | `JsonLdGraph` |
@@ -420,7 +423,7 @@ CDN preconnect: `<MediaPreconnect />` (from env). Media: `normalizeFilenameHook`
```
src/
app/
(frontend)/
(frontend)/ # any route group name works ((site) …); ipal-doctor finds it by structure
styles.css # Tailwind + @source on node_modules/@intecion/ipal-kit/dist
[locale]/ # single-language: no [locale] (see i18n.md)
layout.tsx # no <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
@@ -502,32 +505,52 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`,
9. **RSC by default.** `'use client'` only for state/interaction, in a separate file;
the section stays a server component and passes data to it. Secrets: `import 'server-only'`.
10. **Blocks do not import `lib/*`** (cycle). Server-side data → `enhanceProps`.
11. **Next.js 16.4.1 or later** (minimum safe version). 16.0.0–16.4.0 have unauthenticated RCE and DoS
advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-p3m5-59mp-jv5r); Payload supports no patched
15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.1) and make sure `sharp` resolves to
0.35.5 or later (`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep.
**Check:** `pnpm ls next sharp` → next ≥ 16.4.1, sharp ≥ 0.35.5; `pnpm dev` prints no security-upgrade warning.
12. **No open production advisories.** Node.js 20 or later (the plugin's `nodemailer` 10 requires it). Run
11. **Next.js 16.4.5 or later** (minimum safe version; the plugin, the reference site and the starter use 16.4.6).
16.0.0–16.4.0 have unauthenticated RCE and DoS advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr,
GHSA-p3m5-59mp-jv5r); 16.3.0–16.4.4 have GHSA-mfr8-8qww-v76h (information disclosure across root params when a
`'use cache'` function is called through `unstable_cache()`, moderate; fixed in 16.4.5). Payload supports no
patched 15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.5):
`pnpm add next@16.4.6 eslint-config-next@16.4.6`, and make sure `sharp` resolves to 0.35.5 or later
(`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep.
**Check:** `pnpm ls next sharp` → next ≥ 16.4.5, sharp ≥ 0.35.5; `pnpm exec ipal-doctor` → no `next-min`
finding; `pnpm dev` prints no security-upgrade warning.
12. **No open production advisories.** Node.js 20 or later for the plugin itself (its `nodemailer` 10 requires it);
**Payload 3.94 needs Node.js 22.23.5 or later** on the 22 line (`engines`: `">=22.23.5 <23"`, `.nvmrc` `22`), locally,
in CI and in Coolify (Nixpacks takes the major from `engines` / `.nvmrc` and the patch from its own release: check
`node -v` in the app's Terminal; below 22.23.5, update Coolify before moving to Payload 3.94). Run
`pnpm audit --prod`. The plugin's own dependencies are clean; what remains comes from Payload's tree, which only
the project's lockfile can fix. With `payload` 3.90.x three packages are pinned exactly and need `pnpm.overrides`
next to the `@payloadcms/*` ones:
the project's lockfile can fix. With `payload` **3.94.x** two packages are still pinned below a fix and need
`pnpm.overrides` next to the `@payloadcms/*` ones:
```json
"dompurify@<3.4.17": "^3.4.17",
"graphql-scalars@<2.0.1": "^2.0.1",
"happy-dom@<21.0.4": "^21.0.4"
```
`happy-dom` comes from `@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 (`^20.9.0`, still so in 3.94.1);
every 20.x has GHSA-c8p4-j97h-3vg8 (high, SSRF when parsing untrusted HTML, fixed in 21.0.0) and
GHSA-834v-8h66-3h79 (high, host code execution, fixed in 21.0.4). 21 is a major, but only
`@lexical/headless/dom` (`withDOM`) loads it — Payload never imports that entry, and Lexical 0.53 itself moved to
`^21.0.4`. `dompurify` comes from the admin code editor (`@payloadcms/ui` → `monaco-editor`; low advisories).
**On an older Payload** add these too, until you upgrade (upgrading to 3.94.1 is the better fix):
```json
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
`undici` comes from `payload` (3.92.1 and later already ship 7.30.1), `dompurify` from the admin code editor
(`@payloadcms/ui` → `monaco-editor`, which pins 3.2.7). `graphql-scalars` comes from `@payloadcms/graphql`, which
pins 1.22.2 up to the latest Payload (3.92.1); every version up to 2.0.0 has a high ReDoS advisory in the
`PhoneNumber` scalar (GHSA-x8rm-f576-gq67). 2.x is a major (graphql-js 16+, Node.js 22 recommended), but Payload
only uses `DateTimeResolver` and `EmailAddressResolver`, which work unchanged — keep the override until Payload
ships 2.0.1 or later. `deepmerge` (low, from `payload`) has no fixed version yet; it stays in the report. Everything else in the report (`fast-uri`, `js-yaml`,
`browserslist`, `source-map-js`, `fast-copy`, `baseline-browser-mapping`) is a range: `pnpm update` or a fresh
lockfile picks up the fix; add an override like the ones above only if it does not. These are recommendations —
the plugin forces none of them. Never add a project dependency on `nodemailer` or `@types/nodemailer`.
**Check:** `pnpm audit --prod` → no high or critical (only the `deepmerge` low may remain);
`pnpm why undici dompurify graphql-scalars` → only the fixed versions; with GraphQL in use, a query that reads a
`createdAt` (DateTime) and filters on `email` (EmailAddress) returns data.
`mongoose` (MongoDB sites on Payload 3.90–3.93): `@payloadcms/db-mongodb` pins 8.24.1, which has five advisories —
GHSA-pcrw-h46h-c93h (critical, `sanitizeFilter` not applied on `countDocuments`, fixed in 8.24.3),
GHSA-gg4r-jv3p-qx3c and GHSA-8332-j7wj-wjw4 (high), GHSA-wr5m-5jph-8m96 and GHSA-6972-9mcm-vhwj (moderate), all
fixed in 8.24.7; Payload 3.94.0 and later ship 8.24.7. `undici` (Payload 3.90–3.91): 3.92.0 and later ship 7.30.1.
Both selectors match only the vulnerable versions, so they do nothing once Payload ships the fix — remove them then.
**`graphql-scalars` needs no override any more:** GHSA-x8rm-f576-gq67 now covers 1.24.1–2.0.0 only, and
`@payloadcms/graphql` pins 1.22.2. A `"graphql-scalars@<2.0.1": "^2.0.1"` line added earlier may be removed (it
also works if kept: Payload's GraphQL runs unchanged on 2.x). The `deepmerge` low is gone from Payload 3.94.1.
Everything else in the report (`fast-uri`, `js-yaml`, `browserslist`, `source-map-js`, `fast-copy`,
`baseline-browser-mapping`) is a range: `pnpm update` or a fresh lockfile picks up the fix; add an override like
the ones above only if it does not. These are recommendations — the plugin forces none of them. Never add a
project dependency on `nodemailer` or `@types/nodemailer`.
**Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom mongoose undici` → only the
fixed versions (dompurify 3.4.17 or later, happy-dom 21.0.4 or later, mongoose 8.24.7 or later, undici 7.30.1 or
later); `pnpm exec ipal-doctor` → no `transitive-min` finding; after a Payload or mongoose change run
`pnpm build`, open the panel and save a document.
---
@@ -746,7 +769,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo
(`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters.
- Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project):
`label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`,
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`.
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from
`@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error.
- `admin.description` only when the label is not enough — one sentence ≤ 120 characters:
what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`),
never how the code works (no component, function, env-var or package names).
@@ -1033,9 +1057,10 @@ project → **plugin gap**, not a copy.
| Unusual form markup | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| A field filled in by the page (product variant, category) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md |
| Sending | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| A file on a form (CV, specification) | `forms: { attachments: true }` + a **File** field in the panel; the file is e-mailed to the company and **never stored** (no Media, no bucket, no download). Options `FormAttachmentsOption` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes`: `FormFileType` / `FormFileDetect`, `allowRisky`, `scan`: `FormFileScanInput` → `FormFileScanResult`, `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`: `FormSubmitEndpointOptions`); block `buildFileBlock` / `fileBlock`; types `FORM_FILE_TYPES`, refused `RISKY_FILE_EXTENSIONS`; own markup `getFileProps` / `getFiles` / `removeFile`, `fileFieldRules`, `fileFieldError`, `formatFileSize`, `BuilderFileLimits`, `BuilderFile`; own transfer `submitForm({ files })` + `splitFormFiles`; transport ceiling `mailAttachmentLimit` | forms.md "Files", email.md "Attachments" |
| Message texts and step button texts | Form messages → `getFormTexts(locale)` | notifications.md |
| A form in the database | seed `ipal-form/resources/seed-form.template.ts` | forms.md, seeding.md |
| Antispam / limit / IP | honeypot in `BuilderForm`, Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
| Antispam / limit / IP | honeypot in `BuilderForm` (`getHoneypotProps` on `useBuilderForm`), Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
| GTM event after sending | `buildFormAnalyticsFields` (panel) — `RenderForm` sends it itself | forms.md |
| A form outside the builder (e.g. filters) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
@@ -1104,6 +1129,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|---|---|---|
| Plugin globals: write editor+ (Site integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
| Form files (`forms.attachments`): off; when on — 10 MB, PDF/DOC/DOCX ticked, programs/macros/archives refused, no antivirus, Graph sends files of 3 MB and more through a draft it deletes | omit `attachments`; `forms.fields.file: false`; `mailAdapter({ graph: { largeAttachments: false } })` | `maxSizeMB` / `maxTotalMB` / `maxFiles` / `fileTypes` / `allowRisky` / `scan` / `strictPdf` / `notice` / `submit`; `buildFileBlock`; `formSubmissionOverrides.fields` for the file fields of a submission |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
+27 -6
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.15.0 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.16.3 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
@@ -92,7 +92,11 @@ try {
// no .env (CI)
}
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */
/**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'
export default defineConfig({
@@ -105,7 +109,7 @@ export default defineConfig({
webServer: {
command: 'pnpm start',
env: { PORT: new URL(baseURL).port || '3000' },
reuseExistingServer: true,
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
url: `${baseURL}/api/health`,
},
workers: 1,
@@ -907,6 +911,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
@@ -1148,8 +1157,9 @@ Rules: AGENT.md §8a.
| File | What it shows |
|---|---|
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret (local / CI database only) (below) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret, and e-mail sending pointed at the tests' mail sink (local / CI database only) (below) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) |
### `e2e/create-test-admin.ts`
@@ -1160,7 +1170,8 @@ Rules: AGENT.md §8a.
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -1180,6 +1191,16 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
```
+6
View File
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
+2 -1
View File
@@ -27,7 +27,8 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
```
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
`layout.allow`, `seen` (written by the doctor), `extraRules`.
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
group name works), `seen` (written by the doctor), `extraRules`.
5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`).
## Options and exit codes
+45
View File
@@ -62,6 +62,7 @@ Underneath is `BuilderForm` (client) — clean, accessible HTML **without styles
checkbox, **Checkbox group** (multiple choice, min/max), message, **Step** (splits into steps),
country, state (on by default in form-builder, rendered as a text field).
Turning a type off: `forms.fields: { country: false, state: false }`.
With `forms: { attachments: true }` there is also **File** (section 3a).
- **Multi-step form:** the editor inserts a **Step** block (title, description) — the fields below it form one
screen. The Next/Back buttons and "Step 1 of 3" come from **Form messages → Form messages** (next, back,
stepOf). Next validates only the current step; a server error returns to the step with the field; focus
@@ -82,6 +83,41 @@ Custom field type in the panel: the `FormsOption['fields']` type only accepts `b
(at runtime the block object passes through to form-builder, but TS rejects it), and the server treats
an unknown type as text anyway — if you need a custom type or validation → **plugin gap** (`ipal-plugin-gap`).
## 3a. A file on a form (CV, specification, photo) — `forms.attachments`
The file is **e-mailed to the company and never stored**: no Media record, no bucket, no disk, no download link.
Never build this by hand (your own `<input type="file">`, upload route or upload collection = an error).
1. Config: `forms: { attachments: true }` (defaults: 10 MB per file and per submission, at most 3 files per field).
Options (`FormAttachmentsOption`): `maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes` (add / replace / `false`),
`allowRisky`, `scan` (antivirus hook), `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`
(`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`,
`idleTimeoutMs` 30 s, `timeoutMs` 5 min — a stalled or dropped upload is given up and frees its slot).
Postgres: `pnpm payload migrate:create`; then `pnpm generate:types`.
2. Form: a **File** field — in the seed
`{ blockType: 'file', name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], maxSizeMB: 10, maxFiles: 1, label: {…}, help: {…} }`
(the template has the line, commented). Types: `pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp`.
The label and the help text ("PDF or DOCX, up to 10 MB") are written per language in the panel / seed.
3. E-mails: the file goes to **every e-mail whose To / CC / BCC are fixed addresses** — the company notification.
An e-mail addressed with `{{email}}` (the confirmation to the customer) never gets it. A form with a File field
and no fixed-recipient e-mail cannot be saved. `{{attachment}}` / `{{*:table}}` show the file name.
4. Code: nothing. `RenderForm` renders the field (native input, help text, file list, "Remove" button), and the
browser posts files to the plugin's endpoint `POST /api/ipal/forms/submit` — no route file, no `next.config`
change. Classes: `file`, `help`, `fileList`, `fileItem`, `fileRemove` in `formClasses.ts`. Your own markup:
`f.getFileProps(field)`, `f.getFiles(field)`, `f.removeFile(field, i)`, `f.helpId(field)`.
5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`) — English and Polish defaults; fill every other language of the site. Each tells
the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
(email.md "Attachments"); without it they go over SMTP when the panel has SMTP settings, else the form's limit
drops to about 2.8 MB by itself. Keep Graph small on purpose: `mailAdapter({ graph: { largeAttachments: false } })`.
Tell the client plainly: **there is no antivirus scan** (the e-mail says so), the macro check of old `.doc` / `.xls`
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
@@ -144,6 +180,11 @@ Details the seed already covers, which you check after every manual change in th
- [ ] second language → labels and messages in that language;
- [ ] GTM Preview → an event with the name from the panel after success;
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values;
- [ ] form with a **File** field: a PDF arrives attached to the company e-mail, the customer e-mail has no file,
the submission shows *Files* and *File delivery: Handed to the mail server*, Media has no new record;
a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
still there; a file over the limit → "…is too large. Choose a file of up to N MB." before sending; each
message in every language of the site; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -155,6 +196,10 @@ Details the seed already covers, which you check after every manual change in th
| `reason: 'validation'`, `kind: 'unknown_fields'` | the frontend sends a field the form does not have (custom renderer with an extra field, typo in `name`) |
| "Next/Back" buttons in English | empty Form messages → next / back / stepOf in that language |
| `reason: 'not_found'` | `formId` from another database (seeded on dev, another ID on prod) — use a relationship from the panel, not a fixed ID in code |
| "We could not send the file …", submission says *Not sent* | the mail server refused the message (size limit: see the note on the submission), or Graph without `Mail.ReadWrite` and no SMTP settings → Test e-mail with the 10 MB file; lower the field's maximum or fix the transport (email.md "Attachments") |
| the form with a File field cannot be saved ("Add an e-mail with a fixed recipient…") | every e-mail of the form is addressed with a placeholder → add the company notification with a fixed address |
| the File field does not appear in the builder | `forms.attachments` is off, or `forms.fields.file: false` |
| a file is refused although its type is ticked | the content does not match the extension, the name has a second extension (`cv.pdf.docx`), the document has macros, or it is password-protected |
| submission exists, no email | missing `email: mailAdapter()`, empty Emails tab, transport in the panel; server logs |
| always `turnstile` | wrong key pair / domain in Cloudflare (BuilderForm resets the token after an error) |
| the page became dynamic (`ƒ`) | `headers()` in a component instead of in the action |
@@ -27,6 +27,12 @@ export const formClasses: BuilderFormClassNames = {
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium text-fg-strong',
choice: 'flex items-center gap-2',
// File field (forms.attachments): the native input, its help text, the list of picked files.
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
help: 'mt-1 text-sm text-fg-muted',
fileList: 'mt-2 grid gap-1 text-sm',
fileItem: 'flex flex-wrap items-center gap-2',
fileRemove: 'underline underline-offset-2',
error: 'mt-1 text-sm text-danger',
formError: 'rounded-control bg-danger-surface p-4 text-danger',
actions: 'flex flex-wrap gap-3',
@@ -25,7 +25,7 @@
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
@@ -44,6 +44,11 @@ const FORM = {
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// A file sent to the company by e-mail — never stored on the site (needs `forms: { attachments: true }`).
// It rides on the notification below (fixed recipient); the confirmation to {{email}} never carries it.
// { blockType: 'file', name: 'attachment', required: false, width: 100, allowedTypes: ['pdf', 'doc', 'docx'],
// maxSizeMB: 10, maxFiles: 1, label: { pl: 'Załącznik (opcjonalnie)', en: 'Attachment (optional)' },
// help: { pl: 'PDF, DOC lub DOCX, do 10 MB', en: 'PDF, DOC or DOCX, up to 10 MB' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
@@ -104,6 +109,8 @@ function richText(text: string) {
}
}
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit({ label: '[seed-form]' })
const payload = await getPayload({ config })
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
// A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
+6 -3
View File
@@ -68,6 +68,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
@@ -110,7 +111,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| global `cookie-settings` | banner texts, categories, cookie list; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global `notifications` | form messages per language; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global revalidation hook | `afterChange` on the four globals → `revalidatePath('/', 'layout')` | `revalidatePath` | omit `revalidatePath` |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only); body `{ to, attachmentMB? }` — `attachmentMB` attaches a dummy file to measure the mail server's size limit | — | **currently always** |
| `POST /api/ipal/forms/submit` | a panel form **with files** posts here (multipart, read as a stream; same gates as `sendForm`); same-origin only | `forms.attachments` (`path`, `submit`) | off by default |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
@@ -144,7 +146,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
## 3. What the project wires itself
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md).
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason; the pages may sit in any route group — `layout.frontend` names it when two qualify; docs/doctor.md).
`$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`).
| element | file | minimal example | how to check | details |
@@ -178,6 +180,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → SMTP → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **ipal-form** |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
@@ -248,7 +251,7 @@ Details: env.md, deployment.md, PROGRAMISTA §3.
**DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11.
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding), with `guardSeedExit()` called first (an early exit → exit 1 with the reason, never a silent 0). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
| Seed env var (run time) | Effect |
|---|---|
@@ -277,7 +277,8 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
|---|---|---|
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | recommended adapter for `buildConfig({ email })`: on every send picks SMTP or Graph per the panel setting and saves the integration status; the plugin does not set `config.email` itself |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter that always sends through the SMTP configured in Site integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env) |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName?, largeAttachments?, cleanupDelaysMs? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env). Attachments under 3 MB ride in `sendMail`; larger ones go through a draft + upload session (needs `Mail.ReadWrite`) and the mailbox copy is deleted; `largeAttachments: false` turns that path off (email.md "Attachments") |
| `mailAttachmentLimit(payload)` | `@intecion/ipal-kit` | Total attachment bytes the site's e-mail adapter can carry, or `null` (no ceiling of its own). About 3 MB on Graph without the large-file path and without SMTP settings — form File fields use it for the limit they show |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | sends your own e-mail (your HTML) always through SMTP from the panel → `{ sent: true, messageId }` / `{ sent: false, error }`; does not throw; server code only |
**Types:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — adapter options; `SendEmailArgs`, `SendEmailResult` (`/server`) — `sendEmail` arguments and result.
@@ -378,6 +379,11 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wires `@payloadcms/plugin-form-builder` (Forms + Form Submissions, field types, closed REST for submissions); the plugin wires it itself with the `forms` option — do not call |
| `stepBlock` | `@intecion/ipal-kit` | Form-builder "Step" block (splits the form into steps, with "Show only when"); the plugin adds it itself (`forms.fields.step`) — only for your own form-builder configuration |
| `buildFileBlock(options?)`, `fileBlock` | `@intecion/ipal-kit` | "File" block of the form builder (label, help text, allowed types, maximum size and files); the plugin adds it with `forms.attachments`. `buildFileBlock({ maxSizeMB, fileTypes, … })` for your own variant in `forms.fields.file`; `fileBlock` = the default one |
| `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS` | `@intecion/ipal-kit` | Built-in file types of the File field (`pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp` → label, extensions, MIME type) and the extensions refused unless `attachments.allowRisky` lists them |
| `formatFileSize(bytes)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | "2.1 MB" / "640 KB" for a file list |
| `fileFieldRules(field)`, `fileFieldError(field, files, texts)` | `@intecion/ipal-kit/client` | The limits of a File field in the browser (from `field.resolved`, set by the server) and the first problem with the picked files as the visitor's message — `useBuilderForm` uses both |
| `splitFormFiles(values)` | `@intecion/ipal-kit/server` | Splits `File` values from the answers → `{ fields, files }` for `submitForm({ data: fields, files })` in your own action or route; `createSubmitAction` already does it |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | "Checkbox group" block (multiple choice, `minSelected`/`maxSelected`, value `string[]`); the plugin adds it itself (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | "Time" block (`<input type="time">`, value `HH:MM`); the plugin adds it itself (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Payload `placeholder` field (localized hint in an empty field) for your own form blocks |
@@ -411,7 +417,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -444,7 +450,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Turns `form.analytics` (panel) into an `onSuccess` handler that calls `pushDataLayer(event, params)` (a value like `$topic` — `$` + field name — is taken from the submitted data; empty event = no-op); `useBuilderForm` calls it itself — by hand only with `useForm`/`useContactForm` |
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFileLimits` (root, `/client`) — what the server resolved for a File field (`field.resolved`: `maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`, `typeLabels`); `BuilderFile` (`/client`) — `{ name, size }`, a browser `File` fits. `FormAttachmentsOption`, `FormSubmitEndpointOptions`, `FormFileType`, `FormFileDetect`, `FormFileScanInput`, `FormFileScanResult` (root) — the `forms.attachments` option, its `submit` gates, a file type and its `detect`, and the `scan` hook's input and result. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
## Links (`links`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -558,17 +564,18 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
**Types:** `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
**Types:** `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess` — the early-exit guard; `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
@@ -809,13 +816,14 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. |
| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. |
| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). |
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `ipal-doctor.json` wins. |
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. |
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`.
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
+11 -5
View File
@@ -93,10 +93,16 @@ legacy-peer-deps=true
pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
@payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss
```
**Next.js 16.4.1 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, AGENT.md §4 item 11):
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5` when create-payload-app gave you an older one.
**Node.js 20 or later** (the plugin's `nodemailer` 10 requires it). After the install, `pnpm audit --prod` → no high or
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars` and `undici` overrides from AGENT.md §4 item 12.
**Next.js 16.4.5 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, 16.3.0–16.4.4 have
GHSA-mfr8-8qww-v76h — AGENT.md §4 item 11): `pnpm add [email protected].6 [email protected].6 sharp@^0.35.5` when
create-payload-app gave you an older one.
**Payload 3.94.1** (what the reference site and the starter use; the plugin accepts `^3.90.2`): every `payload` /
`@payloadcms/*` on the same exact version, `react` and `react-dom` 19.3.1 (Payload 3.94 requires `^19.3.1`), and
**Node.js 22.23.5 or later** on the 22 line (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) — Payload 3.94's
minimum, also in Coolify (Nixpacks picks the patch: check `node -v` in the app's Terminal after the first deploy). After the install, `pnpm audit --prod` → no high or critical; add the `dompurify` and `happy-dom` overrides
from AGENT.md §4 item 12 (`"happy-dom@<21.0.4": "^21.0.4"` fixes two high advisories Lexical still brings in). On an
older Payload also the `mongoose` (MongoDB) and `undici` ones listed there. `pnpm exec ipal-doctor` → no
`transitive-min` finding.
`nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own
`lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then
@@ -104,7 +110,7 @@ plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact
`"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`.
**Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.1,
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.5,
sharp ≥ 0.35.5; `ls src/middleware.ts` → not found.
404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1).
@@ -32,7 +32,7 @@
*/
import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload'
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
const ONLY: string[] | undefined = undefined
// ----------------------------------------------------------------- /CONTENT --
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit()
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
+118 -7
View File
@@ -82,13 +82,38 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`buildGlobalRevalidateHook({ revalidatePath })`; `consentFieldName` passed only because the option was ignored →
`forms.consentFieldName` works now; your own seed guard / upsert code → `@intecion/ipal-kit/seed` (`createSeeder`).
**Every upgrade — Next.js 16.4.1 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.1 →
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm dev` prints no security-upgrade warning.
**Every upgrade — Next.js 16.4.5 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.5 →
`pnpm add [email protected].6 [email protected].6 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev`
prints no security-upgrade warning.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; with `payload` 3.90.x add the
`dompurify`, `graphql-scalars` and `undici` overrides, `pnpm install`, audit again. **Check:** no high or critical (the
`deepmerge` low has no fix yet).
**Every upgrade — Payload** (AGENT.md §4 items 11–12): the reference site and the starter run Payload **3.94.1**; the
plugin still accepts `^3.90.2`, so moving is recommended, not forced. To move: every `payload` / `@payloadcms/*` (in
`dependencies` and in `pnpm.overrides`) to the same exact version, `react` and `react-dom` to 19.3.1 (Payload 3.94
requires `^19.3.1`), Node.js 22.23.5 or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) on every machine and
in Coolify — Payload 3.94 refuses older Node. Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes
from the Nixpacks release on the Coolify server, so check `node -v` in the app's Terminal (or the build log) and update
Coolify first if it is below 22.23.5 (until then, stay on 3.90.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
build, redeploy. Payload 3.91–3.94 change no schema the plugin defines: no migration from the plugin; on
Postgres/SQLite run `pnpm payload migrate:create` anyway and commit it if it is not empty.
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → one version, 3.94.1; the panel opens and a document
saves; `pnpm exec ipal-doctor` → no `versions` finding; Coolify app → Terminal → `node -v` → 22.23.5 or later.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; on Payload 3.94.x add the
`dompurify` and `happy-dom` overrides to `pnpm.overrides`; on an older Payload also `mongoose` (MongoDB sites; 3.90–3.93
pin 8.24.1, which has a critical advisory, GHSA-pcrw-h46h-c93h, and four more) and `undici` (3.90–3.91):
```json
"dompurify@<3.4.17": "^3.4.17",
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
The selectors match only vulnerable versions, so on 3.94.x the last two do nothing — remove them. A
`"graphql-scalars@<2.0.1": "^2.0.1"` line is no longer needed (the advisory no longer covers Payload's 1.22.2); remove
it or keep it. Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (no data or
schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom
mongoose undici` → 3.4.17, 21.0.4, 8.24.7, 7.30.1 or later; `pnpm exec ipal-doctor` → no `transitive-min` finding; the
panel opens and a document saves.
**→ 1.14.0 (PROGRAMISTA §6, items 48–49; CHANGELOG "What projects must update" — do all 8, in order):**
1. `pnpm payload generate:importmap` — `@intecion/ipal-kit/admin#FaviconCheck` (hint under Site settings → Site icon)
@@ -98,7 +123,7 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`engines`. Remove `nodemailer` and `@types/nodemailer` from the project's own `package.json` if someone added them
(the plugin's copy is the one `mailAdapter` uses). **Check:** Site integrations → E-mail sending → send a test
e-mail over SMTP (and over Microsoft Graph when the project uses it).
3. **Next.js 16.4.1 or later** — the "Every upgrade — Next.js" step above (`next@^16.4.3`, `sharp@^0.35.5`).
3. **Next.js** — the "Every upgrade — Next.js" step above (today 16.4.5 or later, `sharp@^0.35.5`).
4. **Dependency advisories** — the "Every upgrade — dependency advisories" step above (`dompurify` / `graphql-scalars` /
`undici` overrides on payload 3.90.x). **Check:** `pnpm audit --prod` → no high or critical.
5. **Cookie list kept by hand** → offer `cookieScanner: true` (+ `crawl: true` with `IPAL_COOKIE_SCAN_URL`,
@@ -217,6 +242,92 @@ and the browser tab shows the same separator.
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
`SEED_ONLY` stops with "full seed refused".
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
templates show it). `pnpm ipal:skills` for the updated templates.
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
(a `1` with `[seed] ended …` means the run stopped early — run it again).
**→ 1.15.2 (PROGRAMISTA §6, item 57; ipal-doctor route groups; doctor.md) — nothing required:**
1. `pnpm ipal:skills`; remove a temporary `layout-required` silence in `ipal-doctor.json` added for a route group with
another name or a `notFoundView.tsx`.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
**→ 1.16.0 (PROGRAMISTA §6, item 61; files on forms, e-mailed and never stored; forms.md "Files") — nothing required:**
1. `pnpm ipal:skills`. Existing forms need nothing; without `forms.attachments` nothing changes. No import map change.
2. Only if the site wants files on a form (ask the owner): `ipalKit({ forms: { attachments: true } })`, a **File** field on
the form (panel or seed — `ipal-form` skill), one e-mail of that form with a fixed recipient (no `{{field}}`),
`pnpm generate:types`; Postgres/SQLite: `pnpm payload migrate:create` (additive). Add the `formClasses` keys `file`,
`help`, `fileList`, `fileItem`, `fileRemove`; fill Form messages → Files for languages other than en/pl.
3. A hand-built upload path for a form (own collection, bucket, route): replace it with the File field and remove it
(after the owner confirms nothing else uses the stored files).
4. Deploy: a proxy body limit of at least 12 MB on `/api/ipal/forms/submit` (Coolify's Traefik: none by default;
nginx: `client_max_body_size 12m;`). Mail: Graph needs `Mail.ReadWrite` limited to the forms mailbox for files of
3 MB and more, or SMTP settings in Site integrations; otherwise the limit is about 2.8 MB.
**Check:** Site integrations → "Send test e-mail" with the 10 MB file arrives; a form submission with a file arrives with
the attachment, and the submission shows **File delivery: Sent**; with Graph, no draft or Sent Items copy is left in the
sender mailbox a minute later.
**→ 1.16.1 (PROGRAMISTA §6, item 62; Next.js minimum 16.4.5, GHSA-mfr8-8qww-v76h; AGENT.md §4 item 11) — required for
every site below Next.js 16.4.5:**
1. `pnpm add [email protected] [email protected]`, `rm -rf .next`, `pnpm build`; commit `package.json` and the lockfile,
redeploy on Coolify (the new image ships the fixed Next.js).
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev` prints no security warning.
**→ 1.16.2 (PROGRAMISTA §6, item 63; Payload's mongoose and happy-dom advisories; AGENT.md §4 item 12) — required for
every site:**
1. Add to `pnpm.overrides` in `package.json`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites only) and
`"happy-dom@<21.0.4": "^21.0.4"` (every site). Then `pnpm install`, `pnpm build`; commit `package.json` and the
lockfile, redeploy on Coolify. No data change, no migration.
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm why mongoose happy-dom` → mongoose 8.24.10, happy-dom 21.0.4; `pnpm audit --prod` → no high or critical;
`pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
**→ 1.16.3 (PROGRAMISTA §6, item 64; Payload 3.94.1 in the reference site and the starter; AGENT.md §4 items 11–12) —
recommended, not required (the plugin's peer range stays `^3.90.2`):**
1. **Node.js 22.23.5 or later first — everywhere the site runs.** Payload 3.94 refuses older Node. Locally: `node -v`.
Coolify: Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes from the Nixpacks release on the
server, so open the app → Terminal → `node -v` (or read the build log). Below 22.23.5: update Coolify first, and
stay on Payload 3.90.x until then. CI images must resolve to 22.23.5 or later as well.
2. Every `payload` / `@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1,
`"engines": { "node": ">=22.23.5 <23" }` (`.nvmrc` stays `22`). Overrides: keep `"dompurify@<3.4.17": "^3.4.17"`
and `"happy-dom@<21.0.4": "^21.0.4"`; remove the `mongoose`, `undici` and `graphql-scalars` lines (they do nothing
on 3.94.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
`pnpm build`; commit `package.json` and the lockfile, redeploy on Coolify.
3. Postgres/SQLite: `pnpm payload migrate:create`, commit it if it is not empty (3.94.1 changes long index and foreign
key names). MongoDB: no migration.
4. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → 3.94.1; `pnpm why dompurify happy-dom` → 3.4.17,
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+24 -1
View File
@@ -387,7 +387,10 @@ For a seed (script, flags and data format: [seeding.md](./seeding.md)):
1. **dry run** — `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts`, read the planned changes;
2. **Backup now** on the database (§4.6);
3. the real run; check the panel and the site.
3. the real run; check the panel and the site;
4. `echo $?` — `0` after the summary means done. `1` with `[seed] ended before Payload initialized` (or `… before the
seed finished`) means the run stopped early and silently would have looked like a success — the seed's
`guardSeedExit()` caught it (seeding.md); run it again.
The seed script and its dependencies must be in the image (they are when Coolify builds from the whole repo).
@@ -397,6 +400,25 @@ 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. The plugin itself gives an upload up after 30 s without a byte and
after 5 minutes in total (`attachments.submit.idleTimeoutMs` / `timeoutMs`), so a dropped connection never
holds a slot.
- **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
@@ -415,6 +437,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/<file>` → 200; media domain: no 403
- [ ] Coolify: health check green, a scheduled backup exists (§4.4, §4.6)
- [ ] Favicon in `<head>` (see seo.md — Google caches it slowly)
+17 -8
View File
@@ -57,14 +57,14 @@ tab, a missing Forms collection or a crash. In `package.json`:
```json
"pnpm": {
"overrides": {
"payload": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/storage-s3": "3.90.2"
"payload": "3.94.1",
"@payloadcms/ui": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/db-postgres": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/storage-s3": "3.94.1"
}
}
```
@@ -663,6 +663,15 @@ Do one item at a time, build, check. Order by importance:
| 53 | **1.14.4** — cookie texts retyped in every language; three cookie entries in the admin navigation | `pnpm payload generate:importmap` (`CookieReviewTab`, `CookieSiteCheckTab`); empty languages fill themselves (`fillEmptyLocales: false` to keep them empty); with `cookieScanner` one **Cookies** entry with tabs (`cookieScanner: { adminLayout: 'separate' }` for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration | consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4 |
| 54 | **1.14.6** (1.14.5 never published) — `/api/graphql` answers 500; graphql-scalars high advisory; theme stored as `ipal-theme`; hand-written `admin.meta` for the panel preview | Postgres: `migrate:create` for the title separator **plus `${sql.raw(titleSeparatorSql())}` after the first `SET DATA TYPE text;`**, and the cookie storage type; `graphql-scalars` override (Node 22 recommended); `THEME_STORAGE_KEY` instead of `'ipal-theme'`; `titleSeparatorChar()` for a raw `settings.titleSeparator`; remove hand-written panel `admin.meta`; `pnpm ipal:skills` (`--external` optional) | CHANGELOG 1.14.6 + 1.14.5, seo.md, theme.md, white-label.md, consent.md |
| 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md |
| 56 | **1.15.1** — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) | `guardSeedExit()` first in every seed script, `seed.summary()` at the end; check `echo $?` after a seed; `pnpm ipal:skills` | CHANGELOG 1.15.1, seeding.md |
| 57 | **1.15.2** — ipal-doctor reports missing routes for a site whose pages live in `app/(site)` (not `(frontend)`), or a `notFoundView.tsx` | nothing to change; remove the temporary `layout-required` silence; two candidates → `layout.frontend` in `ipal-doctor.json`; `pnpm ipal:skills` | CHANGELOG 1.15.2, doctor.md |
| 58 | **1.15.3** — ipal-audit / ipal-doctor report `adminText()` or `{ en, pl }` panel labels as hardcoded Polish text | `pnpm ipal:skills`; remove a temporary `i18n-literals` silence added for such labels; public text is still reported | CHANGELOG 1.15.3, ipal-audit skill |
| 59 | **1.15.4** — a seeded form / layout / global array shows only the last language (whole localized arrays) | nothing to change in the seed; repair: `SEED_UPDATE=1` locally, on production `SEED_ONLY` + `SEED_UPDATE=1` + `IPAL_SEED_ALLOW_PROD_UPDATE=1` after a backup; edited records and global arrays by hand | CHANGELOG 1.15.4, seeding.md |
| 60 | **1.15.5** — a seeded page with a required layout linking to a page or form fails validation ("… > Layout") | nothing to change in the seed; run it again (dry run first); a missing `$form` / `$page` is now an error in the dry run too; a required link cycle: make one link optional | CHANGELOG 1.15.5, seeding.md |
| 61 | **1.16.0 — files on forms** — a CV / drawing field built by hand (own upload collection, bucket, `<input type="file">` posting to an own route), or "send the file by e-mail" asked for and refused | `forms: { attachments: true }` + a **File** field (panel or seed) + one e-mail with a fixed recipient; Postgres/SQLite `migrate:create`; `generate:types`; `formClasses` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`; proxy body limit (nginx `client_max_body_size 12m`); Graph: `Mail.ReadWrite` limited to the forms mailbox, or SMTP settings, or ~2.8 MB; test e-mail with the 10 MB file; delete the hand-built upload path; `pnpm ipal:skills` | CHANGELOG 1.16.0, forms.md "Files", email.md "Attachments", deployment.md "Form files" |
| 62 | **1.16.1** — `pnpm dev` warns "Next.js 16.4.3 is affected by a known security vulnerability"; ipal-doctor `next-min` error below 16.4.5 (GHSA-mfr8-8qww-v76h) | `pnpm add [email protected] [email protected]`, `rm -rf .next`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no option, migration or import map change | CHANGELOG 1.16.1, AGENT.md §4 item 11 |
| 63 | **1.16.2** — `pnpm audit --prod` shows `mongoose` (critical, via `@payloadcms/db-mongodb`) or `happy-dom` (high, via `@payloadcms/richtext-lexical`); ipal-doctor `transitive-min` | `pnpm.overrides`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites) and `"happy-dom@<21.0.4": "^21.0.4"`; `pnpm install`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no migration | CHANGELOG 1.16.2, AGENT.md §4 item 12 |
| 64 | **1.16.3** — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or `node -v` (locally or in the Coolify app's Terminal) is below 22.23.5 | Recommended, not required (the plugin still accepts `^3.90.2`). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check `node -v`, update Coolify if lower). Then every `payload` / `@payloadcms/*` 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` / `react-dom` 19.3.1, `"engines": { "node": ">=22.23.5 <23" }`; overrides: keep `dompurify` and `happy-dom`, drop `mongoose`, `undici` and `graphql-scalars`; `pnpm install`, `generate:types`, `generate:importmap`, `rm -rf .next`, build, redeploy; Postgres/SQLite: `migrate:create`; `pnpm ipal:skills` | CHANGELOG 1.16.3, AGENT.md §4 items 11–12, ipal-upgrade "Every upgrade — Payload" |
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
+337
View File
@@ -0,0 +1,337 @@
# 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](../forms.md) "Files" and
> [email.md](../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.
```ts
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.
+8 -6
View File
@@ -79,12 +79,13 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
|---|---|---|---|
| versions | `plugin-installed` | error | `node_modules` has `@intecion/ipal-kit` and it satisfies `package.json` |
| | `plugin-latest` | warning; error two or more minors behind | the installed plugin is the newest on the team registry (registry) |
| | `next-min` | error | `next` ≥ 16.4.1; `eslint-config-next` on the same minor (warning) |
| | `next-min` | error | `next` ≥ 16.4.5 (below 16.4.1: RCE/DoS advisories; 16.3.0–16.4.4: GHSA-mfr8-8qww-v76h); `eslint-config-next` on the same minor (warning) |
| | `sharp-min` | error | `sharp` ≥ 0.35.5 |
| | `transitive-min` | error (`mongoose`), warning (`happy-dom`) | packages Payload pins below a security fix, in any depth of the tree (read from `pnpm-lock.yaml`, else `node_modules/.pnpm`): `mongoose` 8.x ≥ 8.24.7 (GHSA-pcrw-h46h-c93h and four more; Payload 3.90–3.93 pin 8.24.1, 3.94.0+ ship 8.24.7 — the fix it prints names the Payload upgrade first), `happy-dom` ≥ 21.0.4 (GHSA-c8p4-j97h-3vg8, GHSA-834v-8h66-3h79). The fix it prints is the `pnpm.overrides` line from AGENT.md §4 item 12 |
| | `node-22` | warning | `engines.node` only 22 (`">=22 <23"`), `.nvmrc` / `.node-version` = 22; with `--deep`, the running Node |
| | `pnpm-pinned` | info | `packageManager` is set |
| | `deps-audit` | error on critical/high, info on moderate/low | `pnpm audit --prod` (registry) |
| layout | `layout-required` | error | the AGENT.md §3 files (proxy, i18n config, instrumentation, `lib/content`, every route, the `(frontend)` files, `blocks/registry.ts`, `collections/{Pages,Media}.ts`, `components/layout`, `components/forms/formClasses.ts`); an `ipal-audit-skip` key (`llms`, `llms-full`, `markdown`, `mcp`, `indexnow`) drops its file |
| layout | `layout-required` | error | the AGENT.md §3 files (proxy, i18n config, instrumentation, `lib/content`, every route, the frontend files — `layout`, `actions`, `not-found`, `notFoundView` (`.ts` or `.tsx`), the catch-all page — in the route group found by structure: any `app/(<group>)` (or `app` itself) holding `[locale]/[[...slug]]/page.tsx` or `[[...slug]]/page.tsx`, a localized one first, `(frontend)` on a tie (two matches → a warning naming both); `layout.frontend` sets it, `blocks/registry.ts`, `collections/{Pages,Media}.ts`, `components/layout`, `components/forms/formClasses.ts`); an `ipal-audit-skip` key (`llms`, `llms-full`, `markdown`, `mcp`, `indexnow`) drops its file |
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
@@ -110,7 +111,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
| | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) |
| | `audit:<title>` | as reported | every other `ipal-audit --quick` finding, one per file |
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning |
| deep | `deep-status` | error | the deep check could not finish |
@@ -128,7 +129,7 @@ Every rule can be silenced, lowered or raised — **with a reason** — in `ipal
{
"domain": "example-studio.pl",
"launched": false,
"layout": { "allow": ["scripts"] },
"layout": { "allow": ["scripts"], "frontend": "src/app/(site)" },
"rules": {
"csp": { "off": true, "reason": "new site: report-only until the reports are clean", "until": "2026-12-01" },
"i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: the styleguide labels" },
@@ -144,6 +145,7 @@ Every rule can be silenced, lowered or raised — **with a reason** — in `ipal
| `domain` | the production domain (dots allowed) — the base of the database names. Without it: a non-local `NEXT_PUBLIC_SERVER_URL`, else the folder name minus `-web` |
| `launched` | the site is live: seeds must then name their records. Also true when "Project decisions" has a line with "launch" and a date |
| `layout.allow` | more top-level `src/` entries the convention allows |
| `layout.frontend` | the folder that holds the site's pages, e.g. `src/app/(site)` — only for a layout the doctor cannot tell (two route groups with pages); the route group's name is otherwise free |
| `rules.<id>` | `off` (silence), `severity` (`error` / `warning` / `info`), `reason` (**required** — an entry without one is ignored and reported), `until` (ISO date; after it the entry stops applying and the report says so), `files` (globs: only findings in those files). The id is the rule (`csp`) or an audit finding (`audit:collections-present`); `audit` covers all audit findings |
| `seen` | first-seen dates the doctor stores itself (`csp-report-only`, for the 4-week CSP rule). It writes this key only outside CI (`CI` unset), not with `--json`, and only when the file exists |
| `extraRules` | your own rule modules (paths relative to the project), each exporting `rules: DoctorRule[]` |
@@ -199,10 +201,10 @@ console.log(formatReport(report))
`runDoctor`, `runDoctorCli`, `doctorRules`, `applySettings`, `runDeepProbe`, `createDoctorContext`, `loadDoctorConfig`,
`formatReport`, `formatDriftTable`, `planSkills`, `parseToolOutput`, `AUDIT_RULE_MAP`, `AUDIT_SKIP_RULES`,
`DEFAULT_SRC_ALLOW`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`,
`DEFAULT_SRC_ALLOW`, `findFrontend`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`,
`readAuditSkips`, `bareHost`, `expandSites`, `parseDoctorArgs`, `DOCTOR_USAGE`; types `DoctorRule`, `DoctorFinding`,
`DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`,
`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`.
`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
## Environment variables
+80 -6
View File
@@ -139,8 +139,9 @@ [email protected] # 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 <GRAPH_CLIENT_ID> -PolicyScopeGroupId ipal-forms-mailbox `
-AccessRight RestrictAccess -Description "ipal-kit: only the forms mailbox"
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -Identity forms@intecion.pl # AccessCheckResult: Granted
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -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).
+201 -8
View File
@@ -33,7 +33,7 @@ configuration (see below) or extend the plugin. Do NOT hard-code your own form.
## Dependency
```json
"dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // same version as payload
"dependencies": { "@payloadcms/plugin-form-builder": "3.94.1" } // same version as payload
```
(the plugin's peer dependency: `^3.90.2`)
@@ -54,6 +54,7 @@ ipalKit({
| Option | Default | Description |
|---|---|---|
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
| `attachments` | `false` | files on forms: adds the **File** field; a file is checked, e-mailed to the company and dropped — never stored ("Files" below) |
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default ipal block |
| `redirectRelationships` | — | collections a form can redirect to |
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
@@ -87,7 +88,7 @@ import { RenderForm } from '@intecion/ipal-kit/rsc'
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required, fixed`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
next, submit, success, required, fixed, file, help, fileList, fileItem, fileRemove`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
(default `'page'`), `values` (below).
@@ -99,7 +100,8 @@ a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Under
### Field types in the panel
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state as text). Turning a type off: `forms.fields: { date: false }`.
message, **Step** (+ country/state as text), and **File** when `forms.attachments` is on ("Files" below).
Turning a type off: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
@@ -112,6 +114,7 @@ the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payl
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | a real date |
| time | `HH:MM` (`<input type="time">`) | a time 00:00–23:59 |
| File | files (never a text value) | field, count, size, type by content — "Files" below |
| Step | — (split) | not a field |
### Multi-step form
@@ -174,12 +177,201 @@ 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 File field shows "The file … was refused: …", 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`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) |
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.
**An upload that breaks off, stalls or never ends** is given up at once: the connection dropped (400), no byte
arrived for `submit.idleTimeoutMs` (408), the whole request ran past `submit.timeoutMs` (408), or a body without a
declared length went over the ceiling (413 — the read stops there). On every way out the endpoint lets go of what
it held: the buffered bytes, its slot in the concurrency guard and the attempt key, so the next upload — and the
browser's retry — work.
**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 **at the File field** — Form messages → **File not sent** ("We could not send the
file "cv.pdf". Choose a smaller file or another format and try again.") — keeps their answers and the selected
file, and can try again. The mail server's own words never reach the visitor. 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.
### What the visitor is told
**When a submission fails because of the file, the message says it is the file, why, and what to do** — and it
shows at the File field (the result carries `field`). Everything the visitor typed stays in the form.
| Problem | Code | Text (Form messages → Files) | English default |
|---|---|---|---|
| too large | `kind: 'file_too_large'` (`file`, `max`) | `fileTooLarge` | The file "cv.pdf" is too large. Choose a file of up to 10 MB. |
| a format the field does not take | `kind: 'file_type'` (`file`, `types`) | `fileType` | The file "cv.txt" is in a format we do not accept. Choose one of: PDF, DOC, DOCX. |
| refused: a program, an archive, macros, a doubled extension, content that does not match the type, the scanner said no | `kind: 'file_refused'` (`file`, `types`) | `fileRefused` | The file "cv.docx" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOC, DOCX). |
| too many files | `kind: 'file_count'` (`max`) | `fileCount` | Too many files in "Attachment". Remove some: the limit is 1. |
| the e-mail with the file could not be sent | `reason: 'delivery'` (`field`, `file`) | `fileNotSent` | We could not send the file "cv.pdf". Choose a smaller file or another format and try again. |
- On a File field that is **not required**, every one of these ends with `fileOptional` — "You can also send the
form without the file." (the result carries `optional: true`).
- A required File field left empty is `kind: 'required'` → the ordinary field text ("Check the field …").
- A failure that is **not** about the file keeps its own text: consent, a field error, the rate limit, the
general error.
- The texts are in the panel like every form message: Form messages → **Files**, per language, with English and
Polish defaults — fill the other languages of the site ([notifications.md](./notifications.md)). The browser
shows the size, format and count messages before anything is sent; the server answers with the same texts.
### Your own markup
`BuilderForm` renders a native `<input type="file">` with its label, the help text, the list of selected files
(`aria-live`) and a "Remove {file}" button per file. On `useBuilderForm`:
```tsx
const props = f.getFileProps(field) // id, name, type, accept, multiple, onChange, ref, aria-*
<label htmlFor={props.id}>{field.label}</label>
<input {...props} />
{field.help ? <p id={f.helpId(field)}>{field.help}</p> : null}
{f.getFiles(field).map((file, i) => (
<button key={file.name} onClick={() => f.removeFile(field, i)} type="button">Remove {file.name} ({formatFileSize(file.size)})</button>
))}
```
`fileFieldRules(field)` gives the limits in the browser, `fileFieldError(field, files, texts)` the first problem as
the visitor's message. `isSubmitting` is the pending state (there is no upload percentage).
### Your own transfer path
`submitForm({ data, files })` takes files as whole buffers (`{ [fieldKey]: [{ name, data }] }`) and runs the same
checks and the same delivery — for an action or route that receives files itself. `splitFormFiles(values)`
(`/server`) splits `File` values from the answers; `createSubmitAction` already does it, so a hand-built form may
pass `File`s through the action (then raise `experimental.serverActions.bodySizeLimit` in `next.config.ts`).
`mailAttachmentLimit(payload)` returns the transport's ceiling in bytes (or `null`).
### Turn off, override, extend
- Off: leave `attachments` out. Only the block: `forms.fields: { file: false }`. Your own block:
`forms.fields: { file: buildFileBlock({ maxSizeMB: 5 }) }` (`fileBlock` = the default one).
- The endpoint's gates and path: `attachments.submit`, `attachments.path`; the browser can post elsewhere with
`BuilderForm fileSubmitUrl`.
- Submission fields (`submissionFiles`, `filesDelivery`, `filesDeliveryNote`, `attemptKey`) are appended to the
default fields — change them in `formSubmissionOverrides.fields`.
## Front end — submitForm (server)
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
@@ -216,7 +408,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 +578,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_refused' | 'file_count'; file?: string; max?: number; types?: string; optional?: boolean }
| { success: false; reason: 'delivery'; field?: string; file?: string; optional?: boolean; 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 +831,7 @@ filter it out on the client.
## Turn off, override, extend
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
Single field types: `forms.fields.<type>: false`.
Single field types: `forms.fields.<type>: false`. Files: `forms.attachments` is off unless you set it ("Files").
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
+21
View File
@@ -57,6 +57,27 @@ 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:
Each one tells the visitor that the problem is the file, why, and what to do next.
| Key | Placeholders | English default |
|---|---|---|
| `fileTooLarge` | `{file}`, `{max}` (MB) | `The file "{file}" is too large. Choose a file of up to {max} MB.` |
| `fileType` | `{file}`, `{types}` | `The file "{file}" is in a format we do not accept. Choose one of: {types}.` |
| `fileRefused` | `{file}`, `{types}` | `The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).` |
| `fileCount` | `{field}`, `{max}` | `Too many files in "{field}". Remove some: the limit is {max}.` |
| `fileNotSent` | `{file}` | `We could not send the file "{file}". Choose a smaller file or another format and try again.` |
| `fileOptional` | — | `You can also send the form without the file.` — added to the five above when the File field is not required |
| `fileRemove` | `{file}` | `Remove {file}` |
Polish defaults ship too; any other language is filled in the panel (an empty field falls back to English there).
`resolveFormMessage` maps `kind: 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'` and
`reason: 'delivery'` to them and appends `fileOptional` when the result says `optional`; a texts object without
these keys falls back to `validation` / `error`. The result carries `field`, so the message shows at the File field.
## {field} interpolation
The `validation` text may contain `{field}` — it is replaced with the **technical name** of the field with
+19
View File
@@ -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
+44 -4
View File
@@ -152,6 +152,8 @@ Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSe
— the plan must name only the records the owner asked for.
3. Back up the database (**Backup now**).
4. The real run, without `SEED_DRY_RUN`.
5. Check the exit code (`echo $?`): `0` with the summary means done. A run that stops early prints
`[seed] ended before …` and exits `1` (`guardSeedExit`, below) — run it again; nothing after that point was written.
The seed script and its dependencies must be in the image. Env vars (`DATABASE_URI`, `PAYLOAD_SECRET`, …)
must be available at runtime, not only at build time. The container already has `NODE_ENV=production`, so
@@ -178,9 +180,10 @@ because that package throws outside a bundled server.
```ts
// scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
guardSeedExit() // first — an early exit becomes exit 1 with the reason, never a silent 0
const seed = createSeeder(await getPayload({ config }))
await seed.upsertBySlug('pages', [
{ title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] },
@@ -194,14 +197,30 @@ process.exit(seed.summary().errors ? 1 : 0)
**Seed values.** Write each value once, every language side by side. An object whose keys are all
locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same
in every locale. A locale missing from such an object is left untouched in that locale.
This works at any level: a text (`label: { pl, en }`) or a whole array, layout or group (`fields: { pl: [...], en: [...] }`).
Rows of a field that is not localized are shared by every language — the helper reuses their ids, so give each
language the same rows in the same order (its texts differ; non-localized values such as an option's `value` come
from the last language written). A field with `localized: true` keeps its own rows per language.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
is an error for that record, never an empty relation. Ready pages made of library blocks:
is an error for that record, never an empty relation.
**References and required fields.** A new record is created complete, so a required field (a `layout` whose block
links to a page or form) passes validation:
- a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write;
- a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the
field that holds it is required, the record waits until that page exists. Pages that link to each other belong in
one call (an array);
- required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not
planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed
one of the pages first;
- the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required
cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks:
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
| Method | What it does |
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
@@ -211,6 +230,26 @@ Each method prints one line per record (see [Running a seed](#running-a-seed)) a
with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production
guard refuses the run.
### A run that ends early fails loudly — `guardSeedExit()`
`payload run` starts the CLI with `void start()` and then imports the script. When the script's top-level
`await getPayload()` (or a later await) is left with nothing that keeps Node's event loop alive, Node simply exits:
**code 0, no output** — in Coolify's Terminal that looks exactly like a successful seed. Call `guardSeedExit()` first
in every seed script (the templates and the reference site do):
| The run | Exit | What you see |
|---|---|---|
| ends before Payload initialized | 1 | `[seed] ended before Payload initialized — the run stopped early …` |
| ends after `createSeeder` but before `summary()` | 1 | `[seed] ended before the seed finished — …` |
| finishes: `summary()`, then `process.exit(errors ? 1 : 0)` (or ends naturally after the summary, e.g. a dry run) | 0 / 1 | the summary, as before |
| a write fails | 1 | the `error` lines and the summary, as before |
| the production guard refuses (`full seed refused`, `update refused`) or the script throws | 1 | the error, as before (`payload run` prints it) |
`createSeeder` marks the run initialized and `summary()` marks it finished, so the guard needs nothing else.
`guardSeedExit({ label: '[seed-form]', log, process })` — label of the message, where it goes (default stderr), and
the process (tests). `dispose()` stops watching. Check: `pnpm seed` with a reachable database prints the summary as
before; an interrupted run prints the line above and `echo $?` shows `1`.
On a collection with drafts the helper reads the latest draft, both to match records and to tell
whether an editor changed them.
@@ -218,13 +257,14 @@ whether an editor changed them.
| Export | Use |
|---|---|
| `guardSeedExit({ label, log, process })` | the early-exit guard above → `{ initialized, finished, dispose, state }`; `activeSeedExitGuard()` returns the current one (`createSeeder` and `summary()` report to it) |
| `isLocalDatabase(url, { localHosts })` | the "local database" test of [Updates on production](#updates-on-production) |
| `writeLocales(payload, target, data, { context, draft })` | writes seed values to an existing record (`{ collection, id }` or `{ global }`) in every locale: the default locale first, then the others with `fallbackLocale: false` onto the same row ids |
| `seedHash(value)` | the hash stored in the hash field: key order, row ids and `null`s don't change it |
| `projectOnto(seed, current)` | the current values at the keys the seed writes, the input for `seedHash` on a re-run |
| `editedSinceSeed({ doc, currentHash, hashField, untouchedSeconds })` | `null` when untouched, otherwise why the record counts as edited |
Types: `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`,
Types: `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`, `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`,
`UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`.
## Turn off, override, extend
+4
View File
@@ -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://<ACCOUNT_ID>.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).
+5 -3
View File
@@ -188,9 +188,10 @@ function ContactForm() {
`reset()` → after submitting. `enabled` → false when the provider got `siteKey: null` (the widget does not
render; server-side verification is decided by `getTurnstileConfig` anyway).
`reset()` only **clears `token` in React state** — it does not call `turnstile.reset()` on the
Cloudflare widget. A new token appears only when the widget generates one again
(e.g. after expiry, about 300 s) or is mounted again.
`reset()` clears `token` **and makes the widget run its challenge again**, so a new token arrives a moment later
— a token is single-use, and a form the server refused can be sent again. (Up to 1.15.5 it only cleared the
React state, and the next send had no token until the old one expired.) Your own `<Turnstile>` outside the
provider: change its `resetSignal` prop to get the same.
`useTurnstile()` outside `<TurnstileProvider>` throws. `useOptionalTurnstile()`
(also from `/client`) returns `enabled: false` there instead of throwing — `BuilderForm` uses it.
@@ -202,6 +203,7 @@ Cloudflare widget. A new token appears only when the widget generates one again
| `siteKey` | `string` | — | empty → renders nothing |
| `onToken` | `(token: string \| null) => void` | — | token once solved; `null` on expiry / error / theme change |
| `theme` | `'page' \| 'auto' \| 'light' \| 'dark'` | `'page'` | `'page'` = the site's theme (`data-theme`, ThemeScript), no theme → `'auto'` |
| `resetSignal` | `number` | `0` | change the value → the widget issues a new token (what `reset()` does for the provider's widget) |
### Why Turnstile is NOT fully "drop in and forget" like CookieBanner
+33 -30
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.15.0",
"version": "1.16.3",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -108,7 +108,7 @@
"build:starter": "node scripts/build-starter.mjs",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --outDir dist --rootDir ./src",
"clean": "rimraf {dist,*.tsbuildinfo}",
"clean": "rimraf --glob dist \"*.tsbuildinfo\"",
"cookie-db:refresh": "node scripts/refresh-cookie-database.mjs",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"dev": "next dev dev --turbo",
@@ -130,8 +130,9 @@
"typecheck": "tsc --noEmit -p . && tsc -p test"
},
"dependencies": {
"busboy": "1.6.0",
"lucide-react": "0.400.0",
"nodemailer": "10.3.1",
"nodemailer": "10.6.1",
"server-only": "0.0.1",
"slugify": "1.6.9"
},
@@ -148,39 +149,41 @@
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/db-sqlite": "3.90.2",
"@eslint/eslintrc": "^3.3.7",
"@payloadcms/db-postgres": "3.94.1",
"@payloadcms/db-sqlite": "3.94.1",
"@payloadcms/eslint-config": "3.28.0",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@playwright/test": "1.64.0",
"@swc-node/register": "1.10.9",
"@swc/cli": "0.6.0",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/ui": "3.94.1",
"@playwright/test": "1.65.1",
"@swc-node/register": "1.12.1",
"@swc/cli": "0.8.2",
"@types/busboy": "1.5.5",
"@types/node": "22.20.5",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"copyfiles": "2.4.1",
"cross-env": "^7.0.3",
"cross-env": "^10.1.0",
"eslint": "^9.23.0",
"eslint-config-next": "16.4.3",
"eslint-config-next": "16.4.6",
"graphql": "^16.8.1",
"next": "16.4.3",
"open": "^10.1.0",
"payload": "3.90.2",
"prettier": "^3.4.2",
"qs-esm": "8.0.1",
"react": "19.3.0",
"react-dom": "19.3.0",
"rimraf": "3.0.2",
"next": "16.4.6",
"open": "^11.0.4",
"payload": "3.94.1",
"prettier": "^3.10.1",
"qs-esm": "8.0.2",
"react": "19.3.1",
"react-dom": "19.3.1",
"rimraf": "6.1.4",
"sharp": "0.35.5",
"sort-package-json": "^2.10.0",
"sort-package-json": "^4.1.0",
"typescript": "5.9.3",
"vite-tsconfig-paths": "6.0.5",
"vitest": "5.0.4"
"vite": "7.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.1"
},
"engines": {
"node": ">=20.9.0",
@@ -201,7 +204,7 @@
"dompurify@<3.4.17": "^3.4.17",
"fast-copy@<3.1.0": "^3.1.0",
"fast-uri@<3.1.9": "^3.1.9",
"graphql-scalars@<2.0.1": "^2.0.1",
"happy-dom@<21.0.4": "^21.0.4",
"js-yaml@>=4 <4.3.2": "^4.3.2",
"source-map-js@<1.2.2": "^1.2.2",
"undici@>=7 <7.30.1": "^7.30.1"
+1608 -1009
View File
File diff suppressed because it is too large Load Diff
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
@@ -27,7 +27,8 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
```
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
`layout.allow`, `seen` (written by the doctor), `extraRules`.
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
group name works), `seen` (written by the doctor), `extraRules`.
5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`).
## Options and exit codes
@@ -62,6 +62,7 @@ Underneath is `BuilderForm` (client) — clean, accessible HTML **without styles
checkbox, **Checkbox group** (multiple choice, min/max), message, **Step** (splits into steps),
country, state (on by default in form-builder, rendered as a text field).
Turning a type off: `forms.fields: { country: false, state: false }`.
With `forms: { attachments: true }` there is also **File** (section 3a).
- **Multi-step form:** the editor inserts a **Step** block (title, description) — the fields below it form one
screen. The Next/Back buttons and "Step 1 of 3" come from **Form messages → Form messages** (next, back,
stepOf). Next validates only the current step; a server error returns to the step with the field; focus
@@ -82,6 +83,41 @@ Custom field type in the panel: the `FormsOption['fields']` type only accepts `b
(at runtime the block object passes through to form-builder, but TS rejects it), and the server treats
an unknown type as text anyway — if you need a custom type or validation → **plugin gap** (`ipal-plugin-gap`).
## 3a. A file on a form (CV, specification, photo) — `forms.attachments`
The file is **e-mailed to the company and never stored**: no Media record, no bucket, no disk, no download link.
Never build this by hand (your own `<input type="file">`, upload route or upload collection = an error).
1. Config: `forms: { attachments: true }` (defaults: 10 MB per file and per submission, at most 3 files per field).
Options (`FormAttachmentsOption`): `maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes` (add / replace / `false`),
`allowRisky`, `scan` (antivirus hook), `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`
(`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`,
`idleTimeoutMs` 30 s, `timeoutMs` 5 min — a stalled or dropped upload is given up and frees its slot).
Postgres: `pnpm payload migrate:create`; then `pnpm generate:types`.
2. Form: a **File** field — in the seed
`{ blockType: 'file', name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], maxSizeMB: 10, maxFiles: 1, label: {…}, help: {…} }`
(the template has the line, commented). Types: `pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp`.
The label and the help text ("PDF or DOCX, up to 10 MB") are written per language in the panel / seed.
3. E-mails: the file goes to **every e-mail whose To / CC / BCC are fixed addresses** — the company notification.
An e-mail addressed with `{{email}}` (the confirmation to the customer) never gets it. A form with a File field
and no fixed-recipient e-mail cannot be saved. `{{attachment}}` / `{{*:table}}` show the file name.
4. Code: nothing. `RenderForm` renders the field (native input, help text, file list, "Remove" button), and the
browser posts files to the plugin's endpoint `POST /api/ipal/forms/submit` — no route file, no `next.config`
change. Classes: `file`, `help`, `fileList`, `fileItem`, `fileRemove` in `formClasses.ts`. Your own markup:
`f.getFileProps(field)`, `f.getFiles(field)`, `f.removeFile(field, i)`, `f.helpId(field)`.
5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`) — English and Polish defaults; fill every other language of the site. Each tells
the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
(email.md "Attachments"); without it they go over SMTP when the panel has SMTP settings, else the form's limit
drops to about 2.8 MB by itself. Keep Graph small on purpose: `mailAdapter({ graph: { largeAttachments: false } })`.
Tell the client plainly: **there is no antivirus scan** (the e-mail says so), the macro check of old `.doc` / `.xls`
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
@@ -144,6 +180,11 @@ Details the seed already covers, which you check after every manual change in th
- [ ] second language → labels and messages in that language;
- [ ] GTM Preview → an event with the name from the panel after success;
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values;
- [ ] form with a **File** field: a PDF arrives attached to the company e-mail, the customer e-mail has no file,
the submission shows *Files* and *File delivery: Handed to the mail server*, Media has no new record;
a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
still there; a file over the limit → "…is too large. Choose a file of up to N MB." before sending; each
message in every language of the site; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -155,6 +196,10 @@ Details the seed already covers, which you check after every manual change in th
| `reason: 'validation'`, `kind: 'unknown_fields'` | the frontend sends a field the form does not have (custom renderer with an extra field, typo in `name`) |
| "Next/Back" buttons in English | empty Form messages → next / back / stepOf in that language |
| `reason: 'not_found'` | `formId` from another database (seeded on dev, another ID on prod) — use a relationship from the panel, not a fixed ID in code |
| "We could not send the file …", submission says *Not sent* | the mail server refused the message (size limit: see the note on the submission), or Graph without `Mail.ReadWrite` and no SMTP settings → Test e-mail with the 10 MB file; lower the field's maximum or fix the transport (email.md "Attachments") |
| the form with a File field cannot be saved ("Add an e-mail with a fixed recipient…") | every e-mail of the form is addressed with a placeholder → add the company notification with a fixed address |
| the File field does not appear in the builder | `forms.attachments` is off, or `forms.fields.file: false` |
| a file is refused although its type is ticked | the content does not match the extension, the name has a second extension (`cv.pdf.docx`), the document has macros, or it is password-protected |
| submission exists, no email | missing `email: mailAdapter()`, empty Emails tab, transport in the panel; server logs |
| always `turnstile` | wrong key pair / domain in Cloudflare (BuilderForm resets the token after an error) |
| the page became dynamic (`ƒ`) | `headers()` in a component instead of in the action |
@@ -27,6 +27,12 @@ export const formClasses: BuilderFormClassNames = {
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium text-fg-strong',
choice: 'flex items-center gap-2',
// File field (forms.attachments): the native input, its help text, the list of picked files.
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
help: 'mt-1 text-sm text-fg-muted',
fileList: 'mt-2 grid gap-1 text-sm',
fileItem: 'flex flex-wrap items-center gap-2',
fileRemove: 'underline underline-offset-2',
error: 'mt-1 text-sm text-danger',
formError: 'rounded-control bg-danger-surface p-4 text-danger',
actions: 'flex flex-wrap gap-3',
@@ -25,7 +25,7 @@
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
@@ -44,6 +44,11 @@ const FORM = {
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// A file sent to the company by e-mail — never stored on the site (needs `forms: { attachments: true }`).
// It rides on the notification below (fixed recipient); the confirmation to {{email}} never carries it.
// { blockType: 'file', name: 'attachment', required: false, width: 100, allowedTypes: ['pdf', 'doc', 'docx'],
// maxSizeMB: 10, maxFiles: 1, label: { pl: 'Załącznik (opcjonalnie)', en: 'Attachment (optional)' },
// help: { pl: 'PDF, DOC lub DOCX, do 10 MB', en: 'PDF, DOC or DOCX, up to 10 MB' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
@@ -104,6 +109,8 @@ function richText(text: string) {
}
}
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit({ label: '[seed-form]' })
const payload = await getPayload({ config })
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
// A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
@@ -68,6 +68,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
@@ -110,7 +111,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| global `cookie-settings` | banner texts, categories, cookie list; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global `notifications` | form messages per language; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global revalidation hook | `afterChange` on the four globals → `revalidatePath('/', 'layout')` | `revalidatePath` | omit `revalidatePath` |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only); body `{ to, attachmentMB? }` — `attachmentMB` attaches a dummy file to measure the mail server's size limit | — | **currently always** |
| `POST /api/ipal/forms/submit` | a panel form **with files** posts here (multipart, read as a stream; same gates as `sendForm`); same-origin only | `forms.attachments` (`path`, `submit`) | off by default |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
@@ -144,7 +146,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
## 3. What the project wires itself
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md).
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason; the pages may sit in any route group — `layout.frontend` names it when two qualify; docs/doctor.md).
`$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`).
| element | file | minimal example | how to check | details |
@@ -178,6 +180,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → SMTP → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **ipal-form** |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
@@ -248,7 +251,7 @@ Details: env.md, deployment.md, PROGRAMISTA §3.
**DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11.
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding), with `guardSeedExit()` called first (an early exit → exit 1 with the reason, never a silent 0). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
| Seed env var (run time) | Effect |
|---|---|
@@ -277,7 +277,8 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
|---|---|---|
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | recommended adapter for `buildConfig({ email })`: on every send picks SMTP or Graph per the panel setting and saves the integration status; the plugin does not set `config.email` itself |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter that always sends through the SMTP configured in Site integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env) |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName?, largeAttachments?, cleanupDelaysMs? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env). Attachments under 3 MB ride in `sendMail`; larger ones go through a draft + upload session (needs `Mail.ReadWrite`) and the mailbox copy is deleted; `largeAttachments: false` turns that path off (email.md "Attachments") |
| `mailAttachmentLimit(payload)` | `@intecion/ipal-kit` | Total attachment bytes the site's e-mail adapter can carry, or `null` (no ceiling of its own). About 3 MB on Graph without the large-file path and without SMTP settings — form File fields use it for the limit they show |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | sends your own e-mail (your HTML) always through SMTP from the panel → `{ sent: true, messageId }` / `{ sent: false, error }`; does not throw; server code only |
**Types:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — adapter options; `SendEmailArgs`, `SendEmailResult` (`/server`) — `sendEmail` arguments and result.
@@ -378,6 +379,11 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wires `@payloadcms/plugin-form-builder` (Forms + Form Submissions, field types, closed REST for submissions); the plugin wires it itself with the `forms` option — do not call |
| `stepBlock` | `@intecion/ipal-kit` | Form-builder "Step" block (splits the form into steps, with "Show only when"); the plugin adds it itself (`forms.fields.step`) — only for your own form-builder configuration |
| `buildFileBlock(options?)`, `fileBlock` | `@intecion/ipal-kit` | "File" block of the form builder (label, help text, allowed types, maximum size and files); the plugin adds it with `forms.attachments`. `buildFileBlock({ maxSizeMB, fileTypes, … })` for your own variant in `forms.fields.file`; `fileBlock` = the default one |
| `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS` | `@intecion/ipal-kit` | Built-in file types of the File field (`pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp` → label, extensions, MIME type) and the extensions refused unless `attachments.allowRisky` lists them |
| `formatFileSize(bytes)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | "2.1 MB" / "640 KB" for a file list |
| `fileFieldRules(field)`, `fileFieldError(field, files, texts)` | `@intecion/ipal-kit/client` | The limits of a File field in the browser (from `field.resolved`, set by the server) and the first problem with the picked files as the visitor's message — `useBuilderForm` uses both |
| `splitFormFiles(values)` | `@intecion/ipal-kit/server` | Splits `File` values from the answers → `{ fields, files }` for `submitForm({ data: fields, files })` in your own action or route; `createSubmitAction` already does it |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | "Checkbox group" block (multiple choice, `minSelected`/`maxSelected`, value `string[]`); the plugin adds it itself (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | "Time" block (`<input type="time">`, value `HH:MM`); the plugin adds it itself (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Payload `placeholder` field (localized hint in an empty field) for your own form blocks |
@@ -411,7 +417,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -444,7 +450,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Turns `form.analytics` (panel) into an `onSuccess` handler that calls `pushDataLayer(event, params)` (a value like `$topic` — `$` + field name — is taken from the submitted data; empty event = no-op); `useBuilderForm` calls it itself — by hand only with `useForm`/`useContactForm` |
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFileLimits` (root, `/client`) — what the server resolved for a File field (`field.resolved`: `maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`, `typeLabels`); `BuilderFile` (`/client`) — `{ name, size }`, a browser `File` fits. `FormAttachmentsOption`, `FormSubmitEndpointOptions`, `FormFileType`, `FormFileDetect`, `FormFileScanInput`, `FormFileScanResult` (root) — the `forms.attachments` option, its `submit` gates, a file type and its `detect`, and the `scan` hook's input and result. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
## Links (`links`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -558,17 +564,18 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
**Types:** `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
**Types:** `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess` — the early-exit guard; `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
@@ -809,13 +816,14 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. |
| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. |
| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). |
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `ipal-doctor.json` wins. |
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. |
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`.
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
+11 -5
View File
@@ -93,10 +93,16 @@ legacy-peer-deps=true
pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
@payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss
```
**Next.js 16.4.1 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, AGENT.md §4 item 11):
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5` when create-payload-app gave you an older one.
**Node.js 20 or later** (the plugin's `nodemailer` 10 requires it). After the install, `pnpm audit --prod` → no high or
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars` and `undici` overrides from AGENT.md §4 item 12.
**Next.js 16.4.5 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, 16.3.0–16.4.4 have
GHSA-mfr8-8qww-v76h — AGENT.md §4 item 11): `pnpm add [email protected].6 [email protected].6 sharp@^0.35.5` when
create-payload-app gave you an older one.
**Payload 3.94.1** (what the reference site and the starter use; the plugin accepts `^3.90.2`): every `payload` /
`@payloadcms/*` on the same exact version, `react` and `react-dom` 19.3.1 (Payload 3.94 requires `^19.3.1`), and
**Node.js 22.23.5 or later** on the 22 line (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) — Payload 3.94's
minimum, also in Coolify (Nixpacks picks the patch: check `node -v` in the app's Terminal after the first deploy). After the install, `pnpm audit --prod` → no high or critical; add the `dompurify` and `happy-dom` overrides
from AGENT.md §4 item 12 (`"happy-dom@<21.0.4": "^21.0.4"` fixes two high advisories Lexical still brings in). On an
older Payload also the `mongoose` (MongoDB) and `undici` ones listed there. `pnpm exec ipal-doctor` → no
`transitive-min` finding.
`nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own
`lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then
@@ -104,7 +110,7 @@ plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact
`"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`.
**Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.1,
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.5,
sharp ≥ 0.35.5; `ls src/middleware.ts` → not found.
404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1).
@@ -32,7 +32,7 @@
*/
import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload'
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
const ONLY: string[] | undefined = undefined
// ----------------------------------------------------------------- /CONTENT --
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
guardSeedExit()
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
+118 -7
View File
@@ -82,13 +82,38 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`buildGlobalRevalidateHook({ revalidatePath })`; `consentFieldName` passed only because the option was ignored →
`forms.consentFieldName` works now; your own seed guard / upsert code → `@intecion/ipal-kit/seed` (`createSeeder`).
**Every upgrade — Next.js 16.4.1 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.1 →
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm dev` prints no security-upgrade warning.
**Every upgrade — Next.js 16.4.5 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.5 →
`pnpm add [email protected].6 [email protected].6 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev`
prints no security-upgrade warning.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; with `payload` 3.90.x add the
`dompurify`, `graphql-scalars` and `undici` overrides, `pnpm install`, audit again. **Check:** no high or critical (the
`deepmerge` low has no fix yet).
**Every upgrade — Payload** (AGENT.md §4 items 11–12): the reference site and the starter run Payload **3.94.1**; the
plugin still accepts `^3.90.2`, so moving is recommended, not forced. To move: every `payload` / `@payloadcms/*` (in
`dependencies` and in `pnpm.overrides`) to the same exact version, `react` and `react-dom` to 19.3.1 (Payload 3.94
requires `^19.3.1`), Node.js 22.23.5 or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) on every machine and
in Coolify — Payload 3.94 refuses older Node. Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes
from the Nixpacks release on the Coolify server, so check `node -v` in the app's Terminal (or the build log) and update
Coolify first if it is below 22.23.5 (until then, stay on 3.90.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
build, redeploy. Payload 3.91–3.94 change no schema the plugin defines: no migration from the plugin; on
Postgres/SQLite run `pnpm payload migrate:create` anyway and commit it if it is not empty.
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → one version, 3.94.1; the panel opens and a document
saves; `pnpm exec ipal-doctor` → no `versions` finding; Coolify app → Terminal → `node -v` → 22.23.5 or later.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; on Payload 3.94.x add the
`dompurify` and `happy-dom` overrides to `pnpm.overrides`; on an older Payload also `mongoose` (MongoDB sites; 3.90–3.93
pin 8.24.1, which has a critical advisory, GHSA-pcrw-h46h-c93h, and four more) and `undici` (3.90–3.91):
```json
"dompurify@<3.4.17": "^3.4.17",
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
The selectors match only vulnerable versions, so on 3.94.x the last two do nothing — remove them. A
`"graphql-scalars@<2.0.1": "^2.0.1"` line is no longer needed (the advisory no longer covers Payload's 1.22.2); remove
it or keep it. Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (no data or
schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom
mongoose undici` → 3.4.17, 21.0.4, 8.24.7, 7.30.1 or later; `pnpm exec ipal-doctor` → no `transitive-min` finding; the
panel opens and a document saves.
**→ 1.14.0 (PROGRAMISTA §6, items 48–49; CHANGELOG "What projects must update" — do all 8, in order):**
1. `pnpm payload generate:importmap` — `@intecion/ipal-kit/admin#FaviconCheck` (hint under Site settings → Site icon)
@@ -98,7 +123,7 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`engines`. Remove `nodemailer` and `@types/nodemailer` from the project's own `package.json` if someone added them
(the plugin's copy is the one `mailAdapter` uses). **Check:** Site integrations → E-mail sending → send a test
e-mail over SMTP (and over Microsoft Graph when the project uses it).
3. **Next.js 16.4.1 or later** — the "Every upgrade — Next.js" step above (`next@^16.4.3`, `sharp@^0.35.5`).
3. **Next.js** — the "Every upgrade — Next.js" step above (today 16.4.5 or later, `sharp@^0.35.5`).
4. **Dependency advisories** — the "Every upgrade — dependency advisories" step above (`dompurify` / `graphql-scalars` /
`undici` overrides on payload 3.90.x). **Check:** `pnpm audit --prod` → no high or critical.
5. **Cookie list kept by hand** → offer `cookieScanner: true` (+ `crawl: true` with `IPAL_COOKIE_SCAN_URL`,
@@ -217,6 +242,92 @@ and the browser tab shows the same separator.
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
`SEED_ONLY` stops with "full seed refused".
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
templates show it). `pnpm ipal:skills` for the updated templates.
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
(a `1` with `[seed] ended …` means the run stopped early — run it again).
**→ 1.15.2 (PROGRAMISTA §6, item 57; ipal-doctor route groups; doctor.md) — nothing required:**
1. `pnpm ipal:skills`; remove a temporary `layout-required` silence in `ipal-doctor.json` added for a route group with
another name or a `notFoundView.tsx`.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
**→ 1.16.0 (PROGRAMISTA §6, item 61; files on forms, e-mailed and never stored; forms.md "Files") — nothing required:**
1. `pnpm ipal:skills`. Existing forms need nothing; without `forms.attachments` nothing changes. No import map change.
2. Only if the site wants files on a form (ask the owner): `ipalKit({ forms: { attachments: true } })`, a **File** field on
the form (panel or seed — `ipal-form` skill), one e-mail of that form with a fixed recipient (no `{{field}}`),
`pnpm generate:types`; Postgres/SQLite: `pnpm payload migrate:create` (additive). Add the `formClasses` keys `file`,
`help`, `fileList`, `fileItem`, `fileRemove`; fill Form messages → Files for languages other than en/pl.
3. A hand-built upload path for a form (own collection, bucket, route): replace it with the File field and remove it
(after the owner confirms nothing else uses the stored files).
4. Deploy: a proxy body limit of at least 12 MB on `/api/ipal/forms/submit` (Coolify's Traefik: none by default;
nginx: `client_max_body_size 12m;`). Mail: Graph needs `Mail.ReadWrite` limited to the forms mailbox for files of
3 MB and more, or SMTP settings in Site integrations; otherwise the limit is about 2.8 MB.
**Check:** Site integrations → "Send test e-mail" with the 10 MB file arrives; a form submission with a file arrives with
the attachment, and the submission shows **File delivery: Sent**; with Graph, no draft or Sent Items copy is left in the
sender mailbox a minute later.
**→ 1.16.1 (PROGRAMISTA §6, item 62; Next.js minimum 16.4.5, GHSA-mfr8-8qww-v76h; AGENT.md §4 item 11) — required for
every site below Next.js 16.4.5:**
1. `pnpm add [email protected] [email protected]`, `rm -rf .next`, `pnpm build`; commit `package.json` and the lockfile,
redeploy on Coolify (the new image ships the fixed Next.js).
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev` prints no security warning.
**→ 1.16.2 (PROGRAMISTA §6, item 63; Payload's mongoose and happy-dom advisories; AGENT.md §4 item 12) — required for
every site:**
1. Add to `pnpm.overrides` in `package.json`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites only) and
`"happy-dom@<21.0.4": "^21.0.4"` (every site). Then `pnpm install`, `pnpm build`; commit `package.json` and the
lockfile, redeploy on Coolify. No data change, no migration.
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm why mongoose happy-dom` → mongoose 8.24.10, happy-dom 21.0.4; `pnpm audit --prod` → no high or critical;
`pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
**→ 1.16.3 (PROGRAMISTA §6, item 64; Payload 3.94.1 in the reference site and the starter; AGENT.md §4 items 11–12) —
recommended, not required (the plugin's peer range stays `^3.90.2`):**
1. **Node.js 22.23.5 or later first — everywhere the site runs.** Payload 3.94 refuses older Node. Locally: `node -v`.
Coolify: Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes from the Nixpacks release on the
server, so open the app → Terminal → `node -v` (or read the build log). Below 22.23.5: update Coolify first, and
stay on Payload 3.90.x until then. CI images must resolve to 22.23.5 or later as well.
2. Every `payload` / `@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1,
`"engines": { "node": ">=22.23.5 <23" }` (`.nvmrc` stays `22`). Overrides: keep `"dompurify@<3.4.17": "^3.4.17"`
and `"happy-dom@<21.0.4": "^21.0.4"`; remove the `mongoose`, `undici` and `graphql-scalars` lines (they do nothing
on 3.94.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
`pnpm build`; commit `package.json` and the lockfile, redeploy on Coolify.
3. Postgres/SQLite: `pnpm payload migrate:create`, commit it if it is not empty (3.94.1 changes long index and foreign
key names). MongoDB: no migration.
4. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → 3.94.1; `pnpm why dompurify happy-dom` → 3.4.17,
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+2
View File
@@ -56,4 +56,6 @@ INDEXNOW_KEY=
E2E_ADMIN_EMAIL=[email protected]
E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg
E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL
# Port of the mail sink the smoke tests start (e2e/smtp-sink.ts); create-test-admin.ts points e-mail sending at it
E2E_SMTP_PORT=2526
# @starter:endif
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.15.0 — agent guide
## ipal-kit 1.16.3 — agent guide
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+3 -2
View File
@@ -17,8 +17,9 @@ cp .env.example .env # then fill PAYLOAD_SECRET; DATABASE
pnpm seed # demo + base content, every language
pnpm dev # http://localhost:3000/pl
```
Production check: `pnpm build && ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start`, then
`pnpm payload run e2e/create-test-admin.ts && pnpm test:e2e`.
Production check: `pnpm build && pnpm payload run e2e/create-test-admin.ts && ALLOW_LOCAL_MEDIA=1 pnpm test:e2e`
(Playwright starts the built site on port 3100 itself; another port: `E2E_BASE_URL=http://localhost:3200`, built with
the same `NEXT_PUBLIC_SERVER_URL`; a server you started yourself: `E2E_REUSE_SERVER=1`).
## What is where
| Convention | Files |
+12 -1
View File
@@ -3,7 +3,8 @@
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -23,4 +24,14 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
+84
View File
@@ -1,5 +1,6 @@
import { expect, type Page, test } from '@playwright/test'
import { attachmentOf, startSmtpSink } from './smtp-sink'
import { totp } from './totp'
/**
@@ -66,6 +67,89 @@ for (const l of LOCALES) {
})
}
// Files on forms (forms: { attachments: true }): e-mailed to the studio, never stored. A real browser, the real
// endpoint and a local mail sink — the file must arrive as an attachment of the staff e-mail only.
test.describe('the quote form sends a file by e-mail', () => {
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(200_000, 0x20)])
let sink: Awaited<ReturnType<typeof startSmtpSink>>
test.beforeAll(async () => {
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
})
test.afterAll(async () => {
await sink.close()
})
async function fillQuote(page: Page) {
await page.goto('/en/quote')
await rejectCookies(page)
const form = page.locator('form[data-ipal="form"]').first()
await form.locator('input[name="name"]').fill('Test Smoke')
await form.locator('input[name="email"]').fill('[email protected]')
await form.locator('button[type="submit"]').click() // Next
await form.locator('input[name="scope"][value="building"]').check()
await form.locator('input[name="area"][value="s"]').check()
await form.locator('input[name="consent"]').check()
return form
}
test('a wrong file is refused at the field; a PDF arrives attached to the staff e-mail, not the customer one', async ({ page }) => {
const form = await fillQuote(page)
const input = form.locator('input[type="file"][name="attachment"]')
await expect(input).toHaveAttribute('accept', /\.pdf/)
// a type the field does not accept: the message shows at once, by the field
await input.setInputFiles({ buffer: Buffer.from('MZ'), mimeType: 'application/octet-stream', name: 'plan.exe' })
await expect(form.locator('[id$="attachment-error"]')).toContainText('The file "plan.exe" is in a format we do not accept. Choose one of: PDF, JPG, PNG.')
// keyboard: the Remove button is a real button — focus it and press Enter
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
await page.keyboard.press('Enter')
await expect(form.locator('[data-ipal="form-files"] li')).toHaveCount(0)
// a program renamed to .pdf passes the browser check and is stopped by the server (content, not name)
await input.setInputFiles({ buffer: Buffer.concat([Buffer.from('MZ\x90\x00'), Buffer.alloc(2000)]), mimeType: 'application/pdf', name: 'plan.pdf' })
const token = form.locator('input[name="cf-turnstile-response"]')
await expect(token).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
// the message is at the File field, names the file, says why and what to do; nothing the visitor typed is lost
const problem = form.locator('[id$="attachment-error"]')
await expect(problem).toContainText('The file "plan.pdf" was refused', { timeout: 15_000 })
await expect(problem).toContainText('Choose another file (PDF, JPG, PNG). You can also send the form without the file.')
await expect(input).toHaveAttribute('aria-invalid', 'true')
await expect(form.locator('input[name="scope"][value="building"]')).toBeChecked()
await expect(form.locator('input[name="consent"]')).toBeChecked()
await form.getByRole('button', { name: 'Back' }).click()
await expect(form.locator('input[name="name"]')).toHaveValue('Test Smoke')
await expect(form.locator('input[name="email"]')).toHaveValue('[email protected]')
await form.locator('button[type="submit"]').click() // Next
expect(sink.messages).toHaveLength(0)
// the real file (the field takes several: remove the refused one first)
await form.getByRole('button', { name: /Remove plan\.pdf/ }).click()
await input.setInputFiles({ buffer: PDF, mimeType: 'application/pdf', name: 'Floor plan (ground).pdf' })
await expect(form.locator('[data-ipal="form-files"] li')).toContainText('Floor plan (ground).pdf')
// After a refusal the spam check renews itself (a token is single-use). The test keys always give the same
// dummy token, so there is nothing to watch for: submit until the request goes out.
let status = 0
await expect(async () => {
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST', { timeout: 3000 })
await form.locator('button[type="submit"]').click()
status = (await posted).status()
}).toPass({ timeout: 25_000 })
expect(status).toBe(200)
await expect(page.locator('[data-ipal="form-success"]')).toBeVisible({ timeout: 15_000 })
await expect.poll(() => sink.messages.length, { timeout: 15_000 }).toBe(2)
const staff = sink.messages.find((m) => !m.to.join().includes('[email protected]'))!
const customer = sink.messages.find((m) => m.to.join().includes('[email protected]'))!
const attached = attachmentOf(staff.data, 'Floor plan (ground).pdf')
expect(attached && Buffer.compare(attached, PDF)).toBe(0)
const text = (raw: string) => raw.replace(/=\n/g, '') // undo quoted-printable soft line breaks
expect(text(staff.data)).toContain('not checked for viruses')
expect(customer.data).not.toContain('Content-Disposition: attachment')
expect(text(customer.data)).toContain('Floor plan (ground).pdf') // the name in the summary, never the file
})
})
test('every sitemap URL answers 200 with a title, canonical, hreflang and JSON-LD', async ({ page, request }) => {
const xml = await (await request.get('/sitemap.xml')).text()
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)
+64
View File
@@ -0,0 +1,64 @@
import { createServer, type Server } from 'node:net'
export type SinkMessage = { data: string; to: string[] }
/**
* A mail sink for the smoke tests: just enough SMTP for nodemailer to log in and deliver. It keeps every
* message in memory, so a test can read what the site really sent (recipients, attachments).
* e2e/create-test-admin.ts points Site integrations → E-mail sending at it (127.0.0.1:E2E_SMTP_PORT).
*/
export function startSmtpSink(port: number): Promise<{ close: () => Promise<void>; messages: SinkMessage[] }> {
const messages: SinkMessage[] = []
const server: Server = createServer((socket) => {
const mail: SinkMessage = { data: '', to: [] }
let inData = false
let buffer = ''
const reply = (line: string) => socket.write(`${line}\r\n`)
reply('220 localhost ESMTP smoke-sink')
socket.on('error', () => undefined)
socket.on('data', (chunk) => {
buffer += chunk.toString('latin1')
let index: number
while ((index = buffer.indexOf('\r\n')) >= 0) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 2)
if (inData) {
if (line === '.') {
inData = false
messages.push({ ...mail, to: [...mail.to] })
reply('250 2.0.0 Ok: queued')
} else {
mail.data += `${line}\n`
}
continue
}
const command = line.toUpperCase()
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
else if (command.startsWith('RCPT TO:')) {
mail.to.push(line.slice(8).trim())
reply('250 2.1.5 Ok')
} else if (command === 'DATA') {
inData = true
reply('354 End data with <CR><LF>.<CR><LF>')
} else if (command === 'QUIT') {
reply('221 2.0.0 Bye')
socket.end()
} else {reply('502 5.5.2 Command not recognized')}
}
})
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve({ close: () => new Promise((done) => server.close(() => done())), messages }))
})
}
/** The decoded bytes of the attachment named `filename` in a raw message, or null. */
export function attachmentOf(raw: string, filename: string): Buffer | null {
const at = raw.indexOf(`filename=${filename}`) >= 0 ? raw.indexOf(`filename=${filename}`) : raw.indexOf(`filename="${filename}"`)
if (at < 0) {return null}
const body = raw.slice(raw.indexOf('\n\n', at) + 2)
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
}
+28 -29
View File
@@ -5,7 +5,7 @@
"description": "Reference site for @intecion/ipal-kit: Example Studio (made-up architecture studio), Payload CMS 3 + Next 16",
"type": "module",
"engines": {
"node": ">=22 <23"
"node": ">=22.23.5 <23"
},
"packageManager": "[email protected]",
"scripts": {
@@ -25,29 +25,29 @@
"dependencies": {
"@clocklimited/payload-2fa": "3.0.0-beta.7",
"@intecion/ipal-kit": "file:..",
"@payloadcms/db-mongodb": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/storage-s3": "3.90.2",
"@payloadcms/ui": "3.90.2",
"cross-env": "^7.0.3",
"@payloadcms/db-mongodb": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/storage-s3": "3.94.1",
"@payloadcms/ui": "3.94.1",
"cross-env": "^10.1.0",
"graphql": "^16.8.1",
"next": "16.4.3",
"payload": "3.90.2",
"react": "19.3.0",
"react-dom": "19.3.0",
"next": "16.4.6",
"payload": "3.94.1",
"react": "19.3.1",
"react-dom": "19.3.1",
"sharp": "0.35.5"
},
"devDependencies": {
"@playwright/test": "1.64.0",
"@tailwindcss/postcss": "^4.1.0",
"@playwright/test": "1.65.1",
"@tailwindcss/postcss": "^4.3.5",
"@types/node": "22.20.5",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"postcss": "^8.5.0",
"tailwindcss": "^4.1.0",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"postcss": "^8.5.33",
"tailwindcss": "^4.3.5",
"typescript": "5.9.3"
},
"pnpm": {
@@ -57,17 +57,16 @@
"unrs-resolver"
],
"overrides": {
"payload": "3.90.2",
"@payloadcms/db-mongodb": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/storage-s3": "3.90.2",
"@payloadcms/ui": "3.90.2",
"payload": "3.94.1",
"@payloadcms/db-mongodb": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/storage-s3": "3.94.1",
"@payloadcms/ui": "3.94.1",
"dompurify@<3.4.17": "^3.4.17",
"graphql-scalars@<2.0.1": "^2.0.1",
"undici@>=7 <7.30.1": "^7.30.1"
"happy-dom@<21.0.4": "^21.0.4"
}
},
"dependenciesMeta": {
+6 -2
View File
@@ -7,7 +7,11 @@ try {
// no .env (CI)
}
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */
/**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'
export default defineConfig({
@@ -20,7 +24,7 @@ export default defineConfig({
webServer: {
command: 'pnpm start',
env: { PORT: new URL(baseURL).port || '3000' },
reuseExistingServer: true,
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
url: `${baseURL}/api/health`,
},
workers: 1,
+492 -491
View File
File diff suppressed because it is too large Load Diff
@@ -17,6 +17,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
+117
View File
@@ -757,6 +757,38 @@ export interface Form {
blockName?: string | null;
blockType: 'date';
}
| {
/**
* No spaces, e.g. attachment.
*/
name: string;
label?: string | null;
/**
* Shown under the field.
*/
help?: string | null;
width?: number | null;
required?: boolean | null;
/**
* The file is sent by e-mail and is not kept on the site.
*/
allowedTypes: ('doc' | 'docx' | 'jpg' | 'odt' | 'pdf' | 'png' | 'rtf' | 'webp' | 'xls' | 'xlsx')[];
maxSizeMB?: number | null;
maxFiles?: number | null;
showWhen?: {
/**
* Key of the field it depends on.
*/
field?: string | null;
/**
* Separate with commas; leave empty for any value.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'file';
}
| {
name: string;
label?: string | null;
@@ -1298,6 +1330,24 @@ export interface FormSubmission {
id?: string | null;
}[]
| null;
/**
* Sent by e-mail to the form recipients. The files are not kept on the site.
*/
submissionFiles?:
| {
name?: string | null;
type?: string | null;
size?: number | null;
field?: string | null;
id?: string | null;
}[]
| null;
filesDelivery?: ('sent' | 'failed') | null;
/**
* Ask the sender for the file again.
*/
filesDeliveryNote?: string | null;
attemptKey?: string | null;
updatedAt: string;
createdAt: string;
}
@@ -2242,6 +2292,26 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
blockName?: T;
};
file?:
| T
| {
name?: T;
label?: T;
help?: T;
width?: T;
required?: T;
allowedTypes?: T;
maxSizeMB?: T;
maxFiles?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
radio?:
| T
| {
@@ -2335,6 +2405,18 @@ export interface FormSubmissionsSelect<T extends boolean = true> {
value?: T;
id?: T;
};
submissionFiles?:
| T
| {
name?: T;
type?: T;
size?: T;
field?: T;
id?: T;
};
filesDelivery?: T;
filesDeliveryNote?: T;
attemptKey?: T;
updatedAt?: T;
createdAt?: T;
}
@@ -2850,6 +2932,34 @@ export interface Notification {
turnstile?: string | null;
rateLimited?: string | null;
notFound?: string | null;
/**
* Use {file} for the file name and {max} for the limit in MB.
*/
fileTooLarge?: string | null;
/**
* Use {file} for the file name and {types} for the accepted types.
*/
fileType?: string | null;
/**
* For a program, an archive, macros or content that does not match; use {file} and {types}.
*/
fileRefused?: string | null;
/**
* Use {field} for the field label and {max} for the limit.
*/
fileCount?: string | null;
/**
* Shown when the file could not be sent by e-mail; use {file} for the file name.
*/
fileNotSent?: string | null;
/**
* Added to a file message when the file field is not required.
*/
fileOptional?: string | null;
/**
* Use {file} for the file name.
*/
fileRemove?: string | null;
next?: string | null;
back?: string | null;
/**
@@ -3194,6 +3304,13 @@ export interface NotificationsSelect<T extends boolean = true> {
turnstile?: T;
rateLimited?: T;
notFound?: T;
fileTooLarge?: T;
fileType?: T;
fileRefused?: T;
fileCount?: T;
fileNotSent?: T;
fileOptional?: T;
fileRemove?: T;
next?: T;
back?: T;
stepOf?: T;
+6 -1
View File
@@ -69,7 +69,12 @@ export default buildConfig({
// @starter:endif
],
},
forms: { redirectRelationships: ['pages'], emailLayout: true },
// @starter:if demo
// attachments: the Quote form takes floor plans and photos — e-mailed to the studio, never stored (forms.md "Files")
forms: { attachments: true, emailLayout: true, redirectRelationships: ['pages'] },
// @starter:else
//: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files")
// @starter:endif
// @starter:if twoFactor
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
// @starter:else
+2 -2
View File
@@ -240,8 +240,8 @@ export async function seedDemoPages(seed: Seeder, media: Record<string, string>)
{
blockType: 'richText',
content: rich(
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, wspomnij o nich w formularzu — poprosimy o pliki w odpowiedzi. Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, mention them in the form — we will ask for the files in our reply. The quote is free and commits you to nothing.'],
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, dołącz je w formularzu (PDF, JPG lub PNG). Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, attach them in the form (PDF, JPG or PNG). The quote is free and commits you to nothing.'],
),
variant: 'narrow',
},
+12
View File
@@ -84,6 +84,18 @@ export async function seedForms(seed: Seeder, notifyTo: string) {
required: true,
},
{ blockType: 'date', label: tx('Planowany start', 'Planned start'), name: 'start' },
// @starter:if demo
// A File field (forms: { attachments: true }): sent with the notification to the studio, never stored on the site.
{
allowedTypes: ['pdf', 'jpg', 'png'],
blockType: 'file',
help: tx('Rzuty, zdjęcia lub mapa: PDF, JPG lub PNG, razem do 10 MB.', 'Floor plans, photos or a map: PDF, JPG or PNG, up to 10 MB together.'),
label: tx('Załączniki (opcjonalnie)', 'Attachments (optional)'),
maxFiles: 3,
maxSizeMB: 10,
name: 'attachment',
},
// @starter:endif
{ blockType: 'message', message: rich(tx('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.', 'We use your data only to prepare the quote.')) },
consent,
],
+3 -1
View File
@@ -13,7 +13,7 @@
* only with the owner's explicit OK). Pages are create-only; an edited record is skipped.
*/
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
import { seedBaseGlobals, seedBaseNavigation, seedBasePages, seedBaseTexts } from './base'
@@ -33,6 +33,8 @@ const withBase = layer === 'all' || layer === 'base'
//: const withBase = true // a new site has only the base layer (the reference site's demo is not copied)
// @starter:endif
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (seeding.md).
guardSeedExit()
const payload = await getPayload({ config })
const seed = createSeeder(payload)
+3 -2
View File
@@ -59,8 +59,9 @@ export const DESCRIPTIONS = {
'DESIGN.md': 'the human source of the look, matching src/design/tokens.ts',
'README.md': 'how to run the reference site and what is where',
'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback',
'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret (local / CI database only)',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret, and e-mail sending pointed at the tests\' mail sink (local / CI database only)',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test',
'ipal-doctor.json': 'the production domain and launch state for ipal-doctor',
'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By',
+4 -1
View File
@@ -29,11 +29,14 @@ export { ConstructionNotice } from '../modules/construction/ConstructionNotice.j
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { formatFileSize } from '../modules/forms/attachments/fileTypes.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type { BuilderFile } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFileLimits,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
+2 -1
View File
@@ -10,7 +10,8 @@ export { formatDriftTable, formatReport } from '../modules/doctor/format.js'
export { bareHost, createDoctorContext, loadDoctorConfig, parseEnvFile, readAuditSkips } from '../modules/doctor/project.js'
export type { DoctorContext } from '../modules/doctor/project.js'
export { planSkills } from '../modules/doctor/rules/agents.js'
export { DEFAULT_SRC_ALLOW } from '../modules/doctor/rules/layout.js'
export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.js'
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
+7 -1
View File
@@ -6,8 +6,9 @@
* // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
* import config from '@payload-config'
* import { getPayload } from 'payload'
* import { createSeeder } from '@intecion/ipal-kit/seed'
* import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
*
* guardSeedExit() // first: an early exit (no Payload, unfinished run) becomes exit 1, not a silent 0
* const seed = createSeeder(await getPayload({ config }))
* await seed.upsertBySlug('pages', [{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }])
* await seed.fillGlobal('header', { links: [] })
@@ -18,8 +19,10 @@
* package throws in plain Node, and `payload run` is plain Node.
*/
export {
activeSeedExitGuard,
createSeeder,
editedSinceSeed,
guardSeedExit,
isLocalDatabase,
projectOnto,
seedHash,
@@ -29,6 +32,9 @@ export type {
EditedSinceSeedArgs,
Seeder,
SeederOptions,
SeedExitGuard,
SeedExitGuardOptions,
SeedExitProcess,
SeedResult,
SeedStatus,
SeedSummary,
+1 -1
View File
@@ -1,6 +1,6 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { createSubmitAction } from '../modules/forms/createSubmitAction.js'
export { createSubmitAction, splitFormFiles } from '../modules/forms/createSubmitAction.js'
export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
+31
View File
@@ -59,6 +59,37 @@ export const notificationsFields: Field[] = [
formText('turnstile', { en: 'Spam check failed', pl: 'Błąd weryfikacji' }),
formText('rateLimited', { en: 'Too many attempts', pl: 'Zbyt wiele prób' }),
formText('notFound', { en: 'Form unavailable', pl: 'Formularz niedostępny' }),
{
type: 'collapsible',
admin: { initCollapsed: true },
fields: [
formText('fileTooLarge', { en: 'File too large', pl: 'Plik za duży' }, {
description: { en: 'Use {file} for the file name and {max} for the limit in MB.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {max} — limit w MB.' },
}),
formText('fileType', { en: 'Wrong file type', pl: 'Niedozwolony typ pliku' }, {
description: { en: 'Use {file} for the file name and {types} for the accepted types.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {types} — dozwolone typy.' },
}),
formText('fileRefused', { en: 'File refused', pl: 'Plik odrzucony' }, {
description: {
en: 'For a program, an archive, macros or content that does not match; use {file} and {types}.',
pl: 'Dla programu, archiwum, makr lub niezgodnej zawartości; użyj {file} i {types}.',
},
}),
formText('fileCount', { en: 'Too many files', pl: 'Za dużo plików' }, {
description: { en: 'Use {field} for the field label and {max} for the limit.', pl: 'Użyj {field}, aby wstawić etykietę pola, i {max} — limit.' },
}),
formText('fileNotSent', { en: 'File not sent', pl: 'Plik niewysłany' }, {
description: { en: 'Shown when the file could not be sent by e-mail; use {file} for the file name.', pl: 'Widoczny, gdy pliku nie udało się wysłać e-mailem; użyj {file}, aby wstawić nazwę pliku.' },
}),
formText('fileOptional', { en: 'Optional file hint', pl: 'Wskazówka: plik opcjonalny' }, {
description: { en: 'Added to a file message when the file field is not required.', pl: 'Dodawana do komunikatu o pliku, gdy pole pliku nie jest wymagane.' },
}),
formText('fileRemove', { en: 'Remove file button', pl: 'Przycisk usuwania pliku' }, {
description: { en: 'Use {file} for the file name.', pl: 'Użyj {file}, aby wstawić nazwę pliku.' },
}),
],
label: { en: 'Files', pl: 'Pliki' },
},
{
type: 'row',
fields: [
@@ -17,6 +17,7 @@ export const TestEmailButton = () => {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1], vars?: Record<string, unknown>) => ipalT(t as never, key, vars)
const [to, setTo] = useState('')
const [withFile, setWithFile] = useState(false)
const [status, setStatus] = useState<
{ kind: 'error'; msg: string } | { kind: 'idle' } | { kind: 'ok'; msg: string } | { kind: 'sending' }
>({ kind: 'idle' })
@@ -29,7 +30,7 @@ export const TestEmailButton = () => {
setStatus({ kind: 'sending' })
try {
const res = await fetch('/api/ipal/test-email', {
body: JSON.stringify({ to: to.trim() }),
body: JSON.stringify({ to: to.trim(), ...(withFile ? { attachmentMB: 10 } : {}) }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
@@ -69,6 +70,10 @@ export const TestEmailButton = () => {
{status.kind === 'sending' ? text('testEmailSending') : text('testEmailSend')}
</button>
</div>
<label htmlFor="ipal-test-email-file" style={{ alignItems: 'center', display: 'flex', fontSize: '.85rem', gap: '.4rem', marginTop: '.5rem' }}>
<input aria-label={text('testEmailWithFile')} checked={withFile} id="ipal-test-email-file" onChange={(e) => setWithFile(e.target.checked)} type="checkbox" />
{text('testEmailWithFile')}
</label>
{status.kind === 'ok' && (
<p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>
✓ {status.msg}
+7 -1
View File
@@ -172,6 +172,8 @@ export {
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
@@ -184,9 +186,13 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js'
export type { FormFileDetect, FormFileType } from './modules/forms/attachments/fileTypes.js'
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
export type { BuilderField, BuilderFileLimits, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -26,6 +26,8 @@ export const integrationsTexts = defineTexts({
statusWorkingSince: '{{label}}: working since {{date}}.',
// Status messages, by status code
statusEmailGraphLargeFiles:
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
statusEmailGraphUnavailable:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
@@ -53,6 +55,7 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Test e-mail sent to {{to}}.',
testEmailSubject: 'Test e-mail from {{site}}',
testEmailSubjectGeneric: 'Test e-mail from your website',
testEmailWithFile: 'Attach a 10 MB test file',
},
pl: {
alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.',
@@ -74,6 +77,8 @@ export const integrationsTexts = defineTexts({
statusWorking: '{{label}}: działa.',
statusWorkingSince: '{{label}}: działa od {{date}}.',
statusEmailGraphLargeFiles:
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
statusEmailGraphUnavailable:
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
@@ -100,5 +105,6 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
testEmailWithFile: 'Dołącz plik testowy 10 MB',
},
})
+25
View File
@@ -23,6 +23,11 @@ export type DoctorContext = {
importMap: null | string
/** Installed version of a package in the project's node_modules, or null. */
installed: (name: string) => null | string
/**
* Every version of a package in the project's dependency tree, direct or transitive: from `pnpm-lock.yaml`
* (what a deploy installs), else from `node_modules/.pnpm`, plus the top-level install. Empty when not found.
*/
installedAll: (name: string) => string[]
launched: boolean
list: (rel: string) => string[]
live: DoctorLive | null
@@ -121,6 +126,25 @@ export function createDoctorContext(options: ProjectOptions): DoctorContext {
}
}
const installedAll = (name: string) => {
const escaped = name.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
const found = new Set<string>()
// pnpm-lock.yaml v6+: ` [email protected]:` keys under packages: / snapshots: (the overrides: block comes before them)
const lock = read('pnpm-lock.yaml')
const packages = lock.slice(Math.max(0, lock.search(/^packages:\s*$/m)))
for (const m of packages.matchAll(new RegExp(`^ {2}'?${escaped}@(\\d+\\.\\d+\\.\\d+[\\w.+-]*)`, 'gm'))) {found.add(m[1])}
if (!found.size) {
const dir = new RegExp(`^${escaped.replace('\\/', '\\+')}@(\\d+\\.\\d+\\.\\d+[^_(]*)`)
for (const entry of list('node_modules/.pnpm')) {
const m = entry.match(dir)
if (m) {found.add(m[1])}
}
}
const top = installed(name)
if (top) {found.add(top)}
return [...found]
}
let pkg: DoctorContext['pkg'] = {}
try {
pkg = JSON.parse(read('package.json') || '{}') as DoctorContext['pkg']
@@ -166,6 +190,7 @@ export function createDoctorContext(options: ProjectOptions): DoctorContext {
exists,
importMap: adminDir ? `${src}app/(payload)/${adminDir}/importMap.js` : null,
installed,
installedAll,
launched: config.launched ?? launchedInAgents,
list,
live: options.live ?? null,
+78 -32
View File
@@ -33,35 +33,72 @@ export const DEFAULT_SRC_ALLOW = [
/** The project renders blocks through the library registry — then components/ui/ only holds overrides. */
export const usesBlockRegistry = (ctx: DoctorContext) => /createBlockRegistry\s*\(/.test(stripComments(ctx.read(`${ctx.src}blocks/registry.ts`)))
/** Files AGENT.md §3 expects, with the `ipal-audit-skip` key that drops each one. */
function requiredFiles(ctx: DoctorContext): Array<[string, string?]> {
const multi = ctx.exists(`${ctx.src}app/(frontend)/[locale]`)
const fe = multi ? 'app/(frontend)/[locale]' : 'app/(frontend)'
/** Where the site's pages live: the route group (any name) and whether it has a `[locale]` segment. */
export type FrontendLayout = {
/** Other folders that look like the frontend too (set `layout.frontend` to choose). */
ambiguous: string[]
/** Folder relative to src/, e.g. `app/(site)`, `app/(frontend)` or `app` (no route group). */
dir: string
/** `layout.frontend` names a folder that does not exist. */
missingOverride?: string
multi: boolean
}
const PAGE = ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n) => ctx.exists(`${ctx.src}${dir}/${n}`))
/**
* The frontend folder, found by structure rather than by name (a route group's name never reaches the URL):
* `ipal-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
* holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention).
*/
export function findFrontend(ctx: DoctorContext): FrontendLayout {
const override = ctx.config.layout?.frontend?.trim()
if (override) {
const dir = override.replace(/^\.?\//, '').replace(/^src\//, '').replace(/\/+$/, '')
return { ambiguous: [], dir, missingOverride: ctx.exists(`${ctx.src}${dir}`) ? undefined : override, multi: ctx.exists(`${ctx.src}${dir}/[locale]`) }
}
const groups = ['app', ...ctx.list(`${ctx.src}app`).filter((n) => /^\(.+\)$/.test(n) && n !== '(payload)').map((n) => `app/${n}`)]
const localized = groups.filter((g) => has(ctx, `${g}/[locale]/[[...slug]]`, PAGE))
const single = groups.filter((g) => has(ctx, `${g}/[[...slug]]`, PAGE))
const best = localized.length ? localized : single
if (!best.length) {return { ambiguous: [], dir: 'app/(frontend)', multi: ctx.exists(`${ctx.src}app/(frontend)/[locale]`) }}
const dir = best.includes('app/(frontend)') ? 'app/(frontend)' : best[0]
return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 }
}
/** Files AGENT.md §3 expects — each as its accepted names — with the `ipal-audit-skip` key that drops it. */
function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> {
const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir
const ts = (base: string) => [`${base}.ts`, `${base}.tsx`]
const tsx = (base: string) => [`${base}.tsx`, `${base}.ts`, `${base}.jsx`, `${base}.js`]
const route = (dir: string) => [`${dir}/route.ts`, `${dir}/route.js`]
return [
['proxy.ts'],
['i18n.config.ts'],
['instrumentation.ts'],
['payload.config.ts'],
['lib/content.ts'],
['app/manifest.ts'],
['app/robots.ts'],
['app/sitemap.xml/route.ts'],
['app/llms.txt/route.ts', 'llms'],
['app/llms-full.txt/route.ts', 'llms-full'],
[multi ? 'app/md/[locale]/[[...slug]]/route.ts' : 'app/md/[[...slug]]/route.ts', 'markdown'],
['app/api/mcp/route.ts', 'mcp'],
['app/api/health/route.ts'],
['app/indexnow-key.txt/route.ts', 'indexnow'],
[`${fe}/layout.tsx`],
[`${fe}/actions.ts`],
[`${fe}/not-found.tsx`],
[`${fe}/notFoundView.ts`],
[`${fe}/[[...slug]]/page.tsx`],
['blocks/registry.ts'],
['collections/Pages.ts'],
['collections/Media.ts'],
['components/layout'],
['components/forms/formClasses.ts'],
[ts('proxy')],
[ts('i18n.config')],
[ts('instrumentation')],
[ts('payload.config')],
[ts('lib/content')],
[tsx('app/manifest')],
[tsx('app/robots')],
[route('app/sitemap.xml')],
[route('app/llms.txt'), 'llms'],
[route('app/llms-full.txt'), 'llms-full'],
[route(frontend.multi ? 'app/md/[locale]/[[...slug]]' : 'app/md/[[...slug]]'), 'markdown'],
[route('app/api/mcp'), 'mcp'],
[route('app/api/health')],
[route('app/indexnow-key.txt'), 'indexnow'],
[tsx(`${fe}/layout`)],
[ts(`${fe}/actions`)],
[tsx(`${fe}/not-found`)],
// the lazy 404's server action: .tsx when its fallback holds JSX (pages.md)
[ts(`${fe}/notFoundView`)],
[tsx(`${fe}/[[...slug]]/page`)],
[ts('blocks/registry')],
[ts('collections/Pages')],
[ts('collections/Media')],
[['components/layout']],
[ts('components/forms/formClasses')],
// components/ui/: blocks-ui-required (only without createBlockRegistry)
]
}
@@ -74,10 +111,19 @@ export const layoutRules: DoctorRule[] = [
id: 'layout-required',
check: (ctx) => {
if (!ctx.src) {return [{ message: 'no src/ folder (AGENT.md §3)', severity: 'error' }]}
const missing = requiredFiles(ctx).filter(([file, key]) => !(key && ctx.auditSkips.has(key)) && !ctx.exists(`${ctx.src}${file}`))
return missing.length
? [{ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([f]) => `${ctx.src}${f}`).join(', ')}`, severity: 'error' }]
: []
const frontend = findFrontend(ctx)
const out: RuleFinding[] = []
if (frontend.missingOverride) {
out.push({ file: 'ipal-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
}
if (frontend.ambiguous.length) {
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in ipal-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
}
const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`)))
if (missing.length) {
out.push({ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
}
return out
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
+55 -1
View File
@@ -3,6 +3,33 @@ import type { DoctorRule, RuleFinding } from '../types.js'
import { compareVersions, isSemverSpec, lt, parseVersion, run } from '../util.js'
const PKG = '@intecion/ipal-kit'
/** Lowest Next.js without a known advisory: 16.4.5 fixes GHSA-mfr8-8qww-v76h (16.3.0–16.4.4). */
export const NEXT_MIN_SAFE = '16.4.5'
/** The version the plugin, the reference site and the starter use. */
export const NEXT_RECOMMENDED = '16.4.6'
/**
* Packages from Payload's own dependency tree that Payload pins below a security fix (AGENT.md §4 item 12). Only the
* project's lockfile can lift them, with a `pnpm.overrides` entry. `major` limits the check to the line Payload uses.
*/
export const TRANSITIVE_MIN_SAFE: { major?: number; min: string; name: string; override: string; severity: 'error' | 'warning'; upgrade?: string; why: string }[] = [
{
name: 'mongoose',
major: 8,
min: '8.24.7',
override: '"mongoose@>=8 <8.24.7": "~8.24.10"',
severity: 'error',
upgrade: 'upgrade payload and every @payloadcms/* to 3.94.1 (@payloadcms/db-mongodb 3.94.0+ ships 8.24.7), or ',
why: 'GHSA-pcrw-h46h-c93h (critical, sanitizeFilter not applied on countDocuments) and four more; @payloadcms/db-mongodb 3.90–3.93 pins 8.24.1',
},
{
name: 'happy-dom',
min: '21.0.4',
override: '"happy-dom@<21.0.4": "^21.0.4"',
severity: 'warning',
why: 'GHSA-c8p4-j97h-3vg8 and GHSA-834v-8h66-3h79 (high); comes with @payloadcms/richtext-lexical → @lexical/headless',
},
]
export const versionRules: DoctorRule[] = [
{
@@ -26,7 +53,13 @@ export const versionRules: DoctorRule[] = [
const out: RuleFinding[] = []
const next = ctx.installed('next')
if (!next) {return [{ fix: 'pnpm install', message: 'next is not installed', severity: 'error' }]}
if (lt(next, '16.4.1')) {out.push({ fix: 'pnpm add [email protected] [email protected]', message: `next ${next} < 16.4.1 (RCE and DoS advisories)`, severity: 'error' })}
// The minimum safe version and the advisories behind it (AGENT.md §4 item 11).
if (lt(next, NEXT_MIN_SAFE)) {
const why = lt(next, '16.4.1')
? 'RCE and DoS advisories, and GHSA-mfr8-8qww-v76h'
: 'GHSA-mfr8-8qww-v76h: information disclosure across root params in \'use cache\''
out.push({ fix: `pnpm add next@${NEXT_RECOMMENDED} eslint-config-next@${NEXT_RECOMMENDED}`, message: `next ${next} < ${NEXT_MIN_SAFE} (${why})`, severity: 'error' })
}
const eslint = ctx.installed('eslint-config-next')
if (eslint && parseVersion(eslint)?.slice(0, 2).join('.') !== parseVersion(next)?.slice(0, 2).join('.')) {
out.push({ fix: `pnpm add -D eslint-config-next@${next}`, message: `eslint-config-next ${eslint} is not on next's ${next}`, severity: 'warning' })
@@ -48,6 +81,27 @@ export const versionRules: DoctorRule[] = [
group: 'versions',
source: 'static',
},
{
id: 'transitive-min',
check: (ctx) => {
const out: RuleFinding[] = []
for (const dep of TRANSITIVE_MIN_SAFE) {
const old = ctx.installedAll(dep.name).filter((v) => (dep.major === undefined || parseVersion(v)?.[0] === dep.major) && lt(v, dep.min))
if (old.length) {
out.push({
file: 'package.json',
fix: `${dep.upgrade ?? ''}add ${dep.override} to pnpm.overrides in package.json, then pnpm install (AGENT.md §4 item 12)`,
message: `${dep.name} ${old.join(', ')} < ${dep.min} — ${dep.why}`,
severity: dep.severity,
})
}
}
return out
},
docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build',
group: 'versions',
source: 'static',
},
{
id: 'node-22',
check: (ctx) => {
+5 -1
View File
@@ -42,7 +42,11 @@ export type DoctorConfig = {
extraRules?: string[]
/** true once the site is live: seeds must then name their records. */
launched?: boolean
layout?: { allow?: string[] }
/**
* `allow`: more top-level src/ entries. `frontend`: the folder that holds the site's pages, e.g. `src/app/(site)` —
* by default the doctor finds it by structure (any route group with the catch-all page).
*/
layout?: { allow?: string[]; frontend?: string }
rules?: Record<string, DoctorRuleSetting>
/** First time a condition was seen (ISO date), e.g. `{ "csp-report-only": "2026-10-29" }`. */
seen?: Record<string, string>
+17
View File
@@ -0,0 +1,17 @@
import type { BasePayload } from 'payload'
/**
* The largest total attachment size (bytes) the site's e-mail adapter says it
* can carry, or null when it names no ceiling. mailAdapter and graphAdapter
* report one; any other adapter is taken to have none. Never throws.
*/
export async function mailAttachmentLimit(payload: BasePayload): Promise<null | number> {
const limit = (payload.email as { attachmentLimit?: () => null | number | Promise<null | number> } | undefined)?.attachmentLimit
if (typeof limit !== 'function') {return null}
try {
const value = await limit()
return typeof value === 'number' && value >= 0 ? value : null
} catch {
return null
}
}
+99 -8
View File
@@ -1,6 +1,15 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
import {
attachmentBytes,
GRAPH_INLINE_MAX_BYTES,
GRAPH_LARGE_PERMISSION,
inlineGraphAttachments,
sendLargeGraphMail,
toGraphAttachments,
tokenRoles,
} from './graphAttachments.js'
/**
* From/To settings the adapter reads from SiteIntegrations (panel). The Graph
@@ -19,8 +28,42 @@ type GraphIntegrations = {
}
export type GraphAdapterArgs = {
/** Waits before the sent copy of a large-attachment message is deleted from the mailbox (ms). Default 2 s, 5 s, 15 s, 60 s. */
cleanupDelaysMs?: number[]
fallbackFromAddress?: string
fallbackFromName?: string
/** For tests: the `fetch` to call Microsoft with. */
fetchImpl?: typeof fetch
/**
* Attachments of 3 MB and more (in total): the message goes through a draft
* in the sender mailbox and an upload session, and the mailbox copy is deleted
* afterwards. Needs the `Mail.ReadWrite` application permission. Default true;
* `false` keeps Graph to small attachments (larger ones go over SMTP when the
* panel has SMTP settings — see mailAdapter).
*/
largeAttachments?: boolean
}
/**
* Can this Graph setup send attachments of 3 MB and more?
* - 'ok' — yes
* - 'off' — `largeAttachments: false`
* - 'no-permission' — the app's token lacks Mail.ReadWrite
* - 'unavailable' — Graph is not configured, or no token could be fetched
*/
export type GraphLargeSupport = 'no-permission' | 'off' | 'ok' | 'unavailable'
export async function graphLargeAttachmentSupport(args: Pick<GraphAdapterArgs, 'fetchImpl' | 'largeAttachments'> = {}): Promise<GraphLargeSupport> {
if (args.largeAttachments === false) {return 'off'}
const env = readGraphEnv()
if (!env) {return 'unavailable'}
try {
const roles = tokenRoles(await getAccessToken(env, args.fetchImpl))
// A token we cannot read says nothing — let the send try and report.
return !roles || roles.includes(GRAPH_LARGE_PERMISSION) ? 'ok' : 'no-permission'
} catch {
return 'unavailable'
}
}
type GraphEnv = {
@@ -43,11 +86,18 @@ function readGraphEnv(): GraphEnv | null {
/**
* Fetches an app-only access token via the OAuth2 client-credentials flow.
* Scope MUST be '.../.default' — passing 'Mail.Send' directly is rejected
* (AADSTS1002012). Tokens last ~1h; we fetch per send for simplicity and to
* avoid holding state in a possibly multi-instance deployment. If you send at
* high volume, cache by expiry.
* (AADSTS1002012). Tokens last ~1h and are cached per process until a minute
* before they expire.
*/
async function getAccessToken(env: GraphEnv): Promise<string> {
const tokenCache = new Map<string, { expiresAt: number; token: string }>()
/** Forgets cached Graph tokens (after rotating the client secret in a running process; tests). */
export const clearGraphTokenCache = (): void => tokenCache.clear()
async function getAccessToken(env: GraphEnv, fetchImpl: typeof fetch = fetch): Promise<string> {
const cacheKey = `${env.tenantId}:${env.clientId}`
const cached = tokenCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) {return cached.token}
const url = `https://login.microsoftonline.com/${env.tenantId}/oauth2/v2.0/token`
const body = new URLSearchParams({
client_id: env.clientId,
@@ -56,7 +106,7 @@ async function getAccessToken(env: GraphEnv): Promise<string> {
scope: 'https://graph.microsoft.com/.default',
})
const res = await fetch(url, {
const res = await fetchImpl(url, {
body,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
@@ -65,8 +115,10 @@ async function getAccessToken(env: GraphEnv): Promise<string> {
const detail = await res.text()
throw new Error(`Graph token request failed (${res.status}): ${detail}`)
}
const data = (await res.json()) as { access_token?: string }
const data = (await res.json()) as { access_token?: string; expires_in?: number }
if (!data.access_token) {throw new Error('Graph token response had no access_token')}
// Kept until a minute before it expires (tokens last about an hour).
tokenCache.set(cacheKey, { expiresAt: Date.now() + Math.max(0, (data.expires_in ?? 0) - 60) * 1000, token: data.access_token })
return data.access_token
}
@@ -103,6 +155,11 @@ export const graphAdapter =
(args: GraphAdapterArgs = {}): PayloadEmailAdapter =>
({ payload }) => ({
name: 'ipal-graph',
/** Total attachment bytes this adapter can carry; null = no ceiling of its own (see mailAdapter). */
attachmentLimit: async (): Promise<null | number> => {
const support = await graphLargeAttachmentSupport(args)
return support === 'ok' || support === 'unavailable' ? null : GRAPH_INLINE_MAX_BYTES - 1
},
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
defaultFromName: args.fallbackFromName ?? 'Website',
@@ -166,10 +223,44 @@ export const graphAdapter =
...(replyTo.length > 0 ? { replyTo } : {}),
}
// Attachments: small ones ride in the same call; larger ones need a draft and an upload session.
const attachments = toGraphAttachments(message)
if (!attachments) {
payload.logger.error('[ipal] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.')
return { detail: 'Attachment content must be a Buffer or a string.', error: 'The e-mail was not sent.', sent: false }
}
const fetchImpl = args.fetchImpl ?? fetch
try {
const token = await getAccessToken(env)
const token = await getAccessToken(env, fetchImpl)
if (attachments.length > 0 && attachmentBytes(attachments) >= GRAPH_INLINE_MAX_BYTES) {
if (args.largeAttachments === false) {
return {
code: 'graph-large-off',
detail: 'Attachments of 3 MB and more are switched off for Microsoft Graph (largeAttachments: false).',
error: 'The e-mail was not sent.',
sent: false,
}
}
const roles = tokenRoles(token)
if (roles && !roles.includes(GRAPH_LARGE_PERMISSION)) {
const detail = `The Microsoft Graph app lacks the ${GRAPH_LARGE_PERMISSION} application permission, so it cannot send attachments of 3 MB and more.`
payload.logger.error(`[ipal] ${detail}`)
return { code: 'graph-permission', detail, error: 'The e-mail was not sent.', sent: false }
}
const large = await sendLargeGraphMail(attachments, {
cleanupDelaysMs: args.cleanupDelaysMs,
fetchImpl,
log: payload.logger,
message: graphMessage,
sender: env.sender,
token,
})
return large.sent ? large : { ...large, error: 'The e-mail was not sent.' }
}
if (attachments.length > 0) {graphMessage.attachments = inlineGraphAttachments(attachments)}
// App-only: MUST target /users/{sender}, never /me.
const res = await fetch(
const res = await fetchImpl(
`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(env.sender)}/sendMail`,
{
body: JSON.stringify({ message: graphMessage, saveToSentItems: false }),
+198
View File
@@ -0,0 +1,198 @@
import type { SendEmailOptions } from 'payload'
/**
* Attachments over Microsoft Graph.
*
* - Small (all attachments together under GRAPH_INLINE_MAX_BYTES): inside the
* one `sendMail` call. Needs only `Mail.Send`; nothing is left in the mailbox.
* - Large: Graph has no single call for it. The message is created as a DRAFT
* in the sender mailbox, each file is added (an upload session for files of
* 3 MiB and more), the draft is sent, and the copy the mailbox keeps in Sent
* Items is deleted afterwards. Needs the `Mail.ReadWrite` application
* permission — limit it to the sender mailbox with an application access
* policy (docs/email.md).
*/
/**
* Microsoft documents inline attachments "under 3 MB"; the request also has to
* fit base64 (+33 %) and the message body, so the plugin switches at 3,000,000 bytes.
*/
export const GRAPH_INLINE_MAX_BYTES = 3_000_000
/** Files of this size and more need an upload session; smaller ones are refused by it. */
const UPLOAD_SESSION_MIN_BYTES = 3 * 1024 * 1024
/** Bytes per PUT — Microsoft: keep it under 4 MB. A multiple of 320 KiB. */
const CHUNK_BYTES = 10 * 320 * 1024
export const GRAPH_LARGE_PERMISSION = 'Mail.ReadWrite'
export type GraphAttachment = { content: Buffer; contentType: string; name: string }
/** nodemailer-style attachments → buffers. `null` when one cannot be read into memory (a path or a stream). */
export function toGraphAttachments(message: SendEmailOptions): GraphAttachment[] | null {
const list = (message as { attachments?: unknown }).attachments
if (!Array.isArray(list) || list.length === 0) {return []}
const out: GraphAttachment[] = []
for (const raw of list as { content?: unknown; contentType?: unknown; filename?: unknown }[]) {
const content =
Buffer.isBuffer(raw.content) ? raw.content
: raw.content instanceof Uint8Array ? Buffer.from(raw.content.buffer, raw.content.byteOffset, raw.content.byteLength)
: typeof raw.content === 'string' ? Buffer.from(raw.content, 'utf8')
: null
if (!content) {return null}
out.push({
name: typeof raw.filename === 'string' && raw.filename ? raw.filename : 'attachment',
content,
contentType: typeof raw.contentType === 'string' && raw.contentType ? raw.contentType : 'application/octet-stream',
})
}
return out
}
export const attachmentBytes = (attachments: GraphAttachment[]) => attachments.reduce((sum, a) => sum + a.content.length, 0)
/** The attachments as `fileAttachment` objects for an inline `sendMail`. */
export const inlineGraphAttachments = (attachments: GraphAttachment[]) =>
attachments.map((a) => ({
name: a.name,
'@odata.type': '#microsoft.graph.fileAttachment',
contentBytes: a.content.toString('base64'),
contentType: a.contentType,
}))
/** Application permissions (`roles`) of an app-only access token; `null` when the token is not a readable JWT. */
export function tokenRoles(token: string): null | string[] {
try {
const payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8')) as { roles?: unknown }
return Array.isArray(payload.roles) ? payload.roles.filter((r): r is string => typeof r === 'string') : null
} catch {
return null
}
}
export type GraphLargeResult =
| { cleanup: Promise<GraphCleanup>; sent: true }
| { code: 'graph-error' | 'graph-permission'; detail: string; sent: false }
/** What happened to the copy in the sender mailbox. */
export type GraphCleanup = 'deleted' | 'left'
type LargeArgs = {
/** Waits between looks at the sent message before deleting it. Default 2 s, 5 s, 15 s, 60 s. */
cleanupDelaysMs?: number[]
fetchImpl: typeof fetch
log: { error: (msg: string) => void; warn: (msg: string) => void }
message: Record<string, unknown>
sender: string
token: string
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
const permissionDetail =
`Microsoft Graph refused to create the message: the app needs the ${GRAPH_LARGE_PERMISSION} application permission ` +
'for the sender mailbox to send attachments of 3 MB and more.'
/**
* Sends a message with large attachments: draft → attachments → send → delete
* the mailbox copy. Any failure before the send deletes the draft, so no file
* is left in the mailbox. Never throws.
*/
export async function sendLargeGraphMail(attachments: GraphAttachment[], { cleanupDelaysMs = [2000, 5000, 15_000, 60_000], fetchImpl, log, message, sender, token }: LargeArgs): Promise<GraphLargeResult> {
const base = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(sender)}`
// Every call on the draft asks for (and addresses it by) its immutable id — the id that survives the move to Sent Items.
const auth = { Authorization: `Bearer ${token}`, Prefer: 'IdType="ImmutableId"' }
const json = { ...auth, 'Content-Type': 'application/json' }
const describe = async (res: Response) => `${res.status} ${(await res.text().catch(() => '')).slice(0, 300)}`
/** Removes a message from the mailbox for good; falls back to a plain delete. */
const remove = async (id: string): Promise<boolean> => {
try {
const purge = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}/permanentDelete`, { headers: auth, method: 'POST' })
if (purge.status === 204 || purge.status === 200) {return true}
const res = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}`, { headers: auth, method: 'DELETE' })
return res.status === 204 || res.status === 200 || res.status === 404
} catch {
return false
}
}
let draftId: string | undefined
try {
// An immutable id stays the same when the draft moves to Sent Items — that is how the copy is found again.
const created = await fetchImpl(`${base}/messages`, {
body: JSON.stringify(message),
headers: json,
method: 'POST',
})
if (created.status === 401 || created.status === 403) {
log.error(`[ipal] ${permissionDetail} (${await describe(created)})`)
return { code: 'graph-permission', detail: permissionDetail, sent: false }
}
if (created.status !== 201 && created.status !== 200) {
throw new Error(`create draft failed (${await describe(created)})`)
}
draftId = ((await created.json()) as { id?: string }).id
if (!draftId) {throw new Error('create draft returned no id')}
const item = `${base}/messages/${encodeURIComponent(draftId)}`
for (const attachment of attachments) {
if (attachment.content.length < UPLOAD_SESSION_MIN_BYTES) {
const added = await fetchImpl(`${item}/attachments`, { body: JSON.stringify(inlineGraphAttachments([attachment])[0]), headers: json, method: 'POST' })
if (added.status !== 201 && added.status !== 200) {throw new Error(`add attachment failed (${await describe(added)})`)}
continue
}
const session = await fetchImpl(`${item}/attachments/createUploadSession`, {
body: JSON.stringify({ AttachmentItem: { name: attachment.name, attachmentType: 'file', contentType: attachment.contentType, size: attachment.content.length } }),
headers: json,
method: 'POST',
})
if (session.status !== 201 && session.status !== 200) {throw new Error(`create upload session failed (${await describe(session)})`)}
const { uploadUrl } = (await session.json()) as { uploadUrl?: string }
if (!uploadUrl) {throw new Error('upload session returned no uploadUrl')}
const total = attachment.content.length
for (let start = 0; start < total; start += CHUNK_BYTES) {
const end = Math.min(start + CHUNK_BYTES, total)
// The upload URL is pre-authenticated: no Authorization header (Microsoft's rule).
const put = await fetchImpl(uploadUrl, {
body: new Uint8Array(attachment.content.buffer, attachment.content.byteOffset + start, end - start) as unknown as BodyInit,
headers: { 'Content-Length': String(end - start), 'Content-Range': `bytes ${start}-${end - 1}/${total}`, 'Content-Type': 'application/octet-stream' },
method: 'PUT',
})
if (put.status !== 200 && put.status !== 201) {throw new Error(`upload failed at byte ${start} (${await describe(put)})`)}
}
}
const sent = await fetchImpl(`${item}/send`, { headers: { ...auth, 'Content-Length': '0' }, method: 'POST' })
if (sent.status !== 202) {throw new Error(`send failed (${await describe(sent)})`)}
} catch (err) {
const detail = err instanceof Error ? err.message : String(err)
log.error(`[ipal] Graph send with a large attachment failed: ${detail}`)
// Nothing went out: take the draft (and the file in it) out of the mailbox.
if (draftId && !(await remove(draftId))) {
log.error(`[ipal] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`)
}
return { code: 'graph-error', detail, sent: false }
}
// Sent. Exchange keeps a copy in Sent Items; delete it once the message has left Drafts.
const sentId = draftId
const cleanup = (async (): Promise<GraphCleanup> => {
for (const delay of cleanupDelaysMs) {
await sleep(delay)
try {
const look = await fetchImpl(`${base}/messages/${encodeURIComponent(sentId)}?$select=isDraft`, { headers: auth })
if (look.status === 404) {return 'deleted'}
if (look.ok && ((await look.json()) as { isDraft?: boolean }).isDraft === false) {
if (await remove(sentId)) {return 'deleted'}
}
} catch {
/* try again after the next delay */
}
}
log.warn(`[ipal] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`)
return 'left'
})()
cleanup.catch(() => undefined)
return { cleanup, sent: true }
}
+47 -7
View File
@@ -2,15 +2,24 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
type TransportIntegrations = {
emailStatus?: IntegrationStatus | null
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'graph' | 'smtp' | null
smtpHost?: null | string
smtpPassword?: null | string
smtpUser?: null | string
}
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
const STATUS_FIELD = 'emailStatus'
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
const describe = (err: unknown) =>
@@ -68,8 +77,24 @@ export const mailAdapter =
const { payload } = deps
/**
* The largest total attachment size (bytes) the current transport can
* carry, or null when the plugin knows no ceiling (the mail server's own
* limit still applies). Read by the forms module, so a File field never
* promises more than can be sent: on Graph without the large-file path and
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
*/
const attachmentLimit = async (): Promise<null | number> => {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null}
const support = await graphLargeAttachmentSupport(args.graph)
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
return GRAPH_INLINE_MAX_BYTES - 1
}
return {
name: 'ipal-mail-dispatcher',
attachmentLimit,
defaultFromAddress: smtp.defaultFromAddress,
defaultFromName: smtp.defaultFromName,
@@ -88,11 +113,24 @@ export const mailAdapter =
)
}
const transport = useGraph ? 'Microsoft Graph' : 'SMTP'
const code = useGraph ? 'graph-error' : 'smtp-error'
// A large attachment Graph cannot carry (switched off, or the app lacks
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
const attachments = useGraph ? toGraphAttachments(message) : []
const large = Boolean(attachments?.length) && attachmentBytes(attachments ?? []) >= GRAPH_INLINE_MAX_BYTES
const support = large ? await graphLargeAttachmentSupport(args.graph) : 'ok'
const largeOverSmtp = large && support !== 'ok' && support !== 'unavailable' && smtpConfigured(settings)
const viaGraph = useGraph && !largeOverSmtp
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
const code = viaGraph ? 'graph-error' : 'smtp-error'
let result: unknown
try {
result = await (useGraph ? graph : smtp).sendEmail(message)
result = await (viaGraph ? graph : smtp).sendEmail(message)
// Graph found out only while sending (a token it could not read): one try over SMTP. Graph sent nothing.
const refused = result as { code?: string; sent?: boolean } | null
if (viaGraph && refused?.sent === false && GRAPH_TOO_LARGE.has(refused.code ?? '') && smtpConfigured(settings)) {
result = await smtp.sendEmail(message)
}
} catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code,
@@ -104,10 +142,10 @@ export const mailAdapter =
// The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission).
const failed = result as { detail?: string; error?: string; sent?: boolean } | null
const failed = result as { code?: string; detail?: string; error?: string; sent?: boolean } | null
if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code,
code: GRAPH_TOO_LARGE.has(failed.code ?? '') ? 'graph-large-files' : code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
state: 'degraded',
})
@@ -119,7 +157,9 @@ export const mailAdapter =
payload,
STATUS_FIELD,
previous,
graphFallback
large && support === 'no-permission'
? { code: 'graph-large-files', state: 'degraded' }
: graphFallback
? {
code: 'graph-unavailable',
message:
@@ -15,6 +15,9 @@ import { serverText } from '../../integrations/texts.js'
* authenticated admin user — a test-send button must never be open to the
* public (it would be an open relay / spam vector).
*
* Body: `{ to, attachmentMB? }` — `attachmentMB` (1–25) attaches a dummy file of
* that size, to measure what the mail server really accepts.
*
* Returns the adapter's own result so the panel can show exactly what happened,
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
*/
@@ -51,12 +54,20 @@ export const testEmailEndpoint: Endpoint = {
return Response.json({ error: serverText(i18n, 'testEmailInvalidRecipient'), ok: false }, { status: 400 })
}
// Optional: a dummy attachment of N MB — proves that a form file of that size
// really gets through this mail server (form files are delivered by e-mail only).
const requested = Number(req.data?.attachmentMB)
const attachmentMB = Number.isFinite(requested) && requested > 0 ? Math.min(Math.floor(requested), 25) : 0
const site = await siteName(req)
const subject = site ? serverText(i18n, 'testEmailSubject', { site }) : serverText(i18n, 'testEmailSubjectGeneric')
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
try {
const info = await req.payload.sendEmail({
...(attachmentMB
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'ipal-kit test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
: {}),
html: `<p>${escapeHtml(text)}</p>`,
subject,
text,
+28 -3
View File
@@ -8,7 +8,7 @@ import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
import { honeypotInputProps } from './honeypot.js'
import { formatFileSize } from './attachments/fileTypes.js'
import { useBuilderForm } from './useBuilderForm.js'
/**
@@ -19,7 +19,8 @@ import { useBuilderForm } from './useBuilderForm.js'
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'file' | 'fileItem' | 'fileList' | 'fileRemove' | 'fixed'
| 'form' | 'formError' | 'help' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
@@ -161,6 +162,30 @@ export function BuilderForm({
{errorOf(field)}
</fieldset>
)
case 'file': {
// A native file input: keyboard, touch and screen readers work as everywhere else.
const props = f.getFileProps(field)
const files = f.getFiles(field)
const remove = options.texts.fileRemove ?? 'Remove {file}'
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<input {...props} className={cn.file ?? cn.input} />
{field.help ? <p className={cn.help} id={f.helpId(field)}>{field.help}</p> : null}
<ul aria-live="polite" className={cn.fileList} data-ipal="form-files">
{files.map((file, i) => (
<li className={cn.fileItem} key={`${file.name}-${file.size}-${i}`}>
<span>{file.name} ({formatFileSize(file.size)})</span>{' '}
<button className={cn.fileRemove} onClick={() => f.removeFile(field, i)} type="button">
{remove.replace('{file}', file.name)}
</button>
</li>
))}
</ul>
{errorOf(field)}
</>
)
}
case 'select': {
const props = f.getSelectProps(field)
return (
@@ -202,7 +227,7 @@ export function BuilderForm({
return (
<form className={cn.form} data-ipal="form" data-step={f.stepIndex + 1} noValidate onSubmit={f.submit}>
<input {...honeypotInputProps()} />
<input {...f.getHoneypotProps()} />
{f.total > 1 && progress ? <p aria-live="polite" className={cn.progress}>{progress}</p> : null}
<div className={cn.step} data-ipal="form-step" ref={stepRef} tabIndex={-1}>
{step.title ? <p className={cn.stepTitle}>{step.title}</p> : null}
+4
View File
@@ -52,6 +52,7 @@ export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
analytics: form.analytics,
confirmationType: form.confirmationType,
fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field),
fileSubmitUrl: form.fileSubmitUrl,
redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null,
submitButtonLabel: form.submitButtonLabel,
title: form.title,
@@ -68,6 +69,8 @@ export type PreparedBuilderForm = {
action: (values: Record<string, unknown>, turnstileToken?: string) => Promise<SubmitActionResult>
confirmation: ReactNode
form: BuilderFormDoc
/** The page language — sent with a submission that carries files. */
locale: string
messages: Record<number, ReactNode>
redirectHref: null | string
}
@@ -116,6 +119,7 @@ export function prepareBuilderForm({
action: action.bind(null, String(form.id), locale),
confirmation: rich(form.confirmationMessage),
form: publicForm(form),
locale,
messages,
redirectHref,
}
+159
View File
@@ -0,0 +1,159 @@
import type { BasePayload } from 'payload'
import type { ClientIpOptions } from '../../shared/rateLimit.js'
import type { FormFileType } from './fileTypes.js'
import { FORM_FILE_TYPES, MB, RISKY_FILE_EXTENSIONS } from './fileTypes.js'
/** A file handed to `attachments.scan` — in memory, after every other check passed. */
export type FormFileScanInput = {
data: Uint8Array
/** The field key of the File field it came from. */
field: string
/** The cleaned name the attachment will carry. */
name: string
size: number
/** Type key, e.g. 'pdf'. */
type: string
}
export type FormFileScanResult = { ok: boolean; reason?: string }
/**
* `ipalKit({ forms: { attachments } })` — files on panel forms. They are
* NEVER stored: a file is checked, attached to the company e-mail, and dropped.
*/
export type FormAttachmentsOption = {
/**
* Extensions from the refused list (RISKY_FILE_EXTENSIONS: programs, macro-enabled
* Office files, archives, HTML/SVG…) this project accepts after all, e.g. `['zip']`.
* The extension still has to belong to a file type of the field (`fileTypes`).
*/
allowRisky?: string[]
/**
* Add a file type (`{ dwg: { label, extensions, mimeType, detect } }`), replace
* a built-in one, or remove one with `false`.
*/
fileTypes?: Record<string, false | FormFileType>
/** File submissions handled at the same time, per instance. More get "try again". Default 2; 0 = no guard. */
maxConcurrent?: number
/** Ceiling for a field's "Maximum files". Default 3. */
maxFiles?: number
/** Ceiling for a field's "Maximum size (MB)". Default 10. */
maxSizeMB?: number
/** Ceiling for all files of one submission, in MB. Default 10. */
maxTotalMB?: number
/**
* The line added to the e-mail that carries a file ("…was not checked for
* viruses"). `false` leaves it out; a string or a function replaces it.
*/
notice?: ((locale: string | undefined) => string) | false | string
/** Path of the submit endpoint under the API route. Default '/ipal/forms/submit'. */
path?: string
/**
* Antivirus hook. The plugin has NO malware scanner; plug one in here
* (ClamAV, a scanning API). Return `{ ok: false }` to refuse the file.
* A thrown error refuses the file too.
*/
scan?: (file: FormFileScanInput) => FormFileScanResult | Promise<FormFileScanResult>
/** Refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search). Default false. */
strictPdf?: boolean
/**
* The submit endpoint's gates — the same options createSubmitAction takes,
* so both paths behave alike. `allowedOrigins`: other origins that may post
* to it (a front end on another domain); the site's own origin always may.
*/
submit?: FormSubmitEndpointOptions
}
export type FormSubmitEndpointOptions = {
allowedOrigins?: string[]
clientIp?: ClientIpOptions
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
/**
* A stalled upload: no byte of the request body for this long (ms) and the request is given up (408).
* Default 30000; 0 = no idle limit.
*/
idleTimeoutMs?: number
/** Max submissions per IP per minute. Default 5; 0 turns it off. */
maxPerMinute?: number
/**
* Ceiling for the whole request — upload, checks and e-mail (ms). Past it the request is answered 408 and
* everything it held is released. Default 300000 (5 minutes); 0 = no ceiling.
*/
timeoutMs?: number
turnstileHostnames?: string[]
turnstileOnConfigError?: 'allow' | 'reject'
}
export type ResolvedFormAttachments = {
maxConcurrent: number
maxFiles: number
maxSizeMB: number
maxTotalMB: number
notice: FormAttachmentsOption['notice']
path: string
risky: ReadonlySet<string>
scan?: FormAttachmentsOption['scan']
strictPdf: boolean
submit: FormSubmitEndpointOptions
types: Record<string, FormFileType>
}
export const FORM_SUBMIT_PATH = '/ipal/forms/submit'
const positive = (value: number | undefined, fallback: number) => (typeof value === 'number' && value > 0 ? value : fallback)
/** Defaults applied; `true` = everything default. */
export function resolveFormAttachments(option: FormAttachmentsOption | true): ResolvedFormAttachments {
const o = option === true ? {} : option
const types: Record<string, FormFileType> = { ...FORM_FILE_TYPES }
for (const [key, type] of Object.entries(o.fileTypes ?? {})) {
if (type === false) {delete types[key]}
else {types[key] = { ...type, extensions: type.extensions.map((e) => e.replace(/^\./, '').toLowerCase()) }}
}
const allowed = new Set((o.allowRisky ?? []).map((e) => e.replace(/^\./, '').toLowerCase()))
return {
maxConcurrent: typeof o.maxConcurrent === 'number' && o.maxConcurrent >= 0 ? o.maxConcurrent : 2,
maxFiles: Math.floor(positive(o.maxFiles, 3)),
maxSizeMB: positive(o.maxSizeMB, 10),
maxTotalMB: positive(o.maxTotalMB, positive(o.maxSizeMB, 10)),
notice: o.notice,
path: o.path ? `/${o.path.replace(/^\/+/, '')}` : FORM_SUBMIT_PATH,
risky: new Set(RISKY_FILE_EXTENSIONS.filter((e) => !allowed.has(e))),
scan: o.scan,
strictPdf: o.strictPdf === true,
submit: o.submit ?? {},
types,
}
}
/** The resolved option of this Payload instance, or null when `forms.attachments` is off. */
export function getFormAttachments(payload: BasePayload): null | ResolvedFormAttachments {
const value = (payload.config?.custom as { ipal?: { formAttachments?: ResolvedFormAttachments } } | undefined)?.ipal?.formAttachments
return value ?? null
}
/** A File field as the panel stores it. */
export type FileFieldConfig = {
allowedTypes?: null | string[]
maxFiles?: null | number
maxSizeMB?: null | number
name?: null | string
}
/**
* The limits that really apply to a File field: the editor's values, capped by
* the plugin option and by what the e-mail transport can carry (`transportMaxBytes`).
*/
export function fileFieldLimits(field: FileFieldConfig, options: ResolvedFormAttachments, transportMaxBytes?: null | number) {
const sizeMB = Math.min(positive(field.maxSizeMB ?? undefined, options.maxSizeMB), options.maxSizeMB)
const cap = typeof transportMaxBytes === 'number' ? transportMaxBytes : Infinity
return {
allowedTypes: (field.allowedTypes ?? []).filter((key) => options.types[key]),
maxBytes: Math.floor(Math.min(sizeMB * MB, cap)),
maxFiles: Math.max(1, Math.min(Math.floor(positive(field.maxFiles ?? undefined, 1)), options.maxFiles)),
maxTotalBytes: Math.floor(Math.min(options.maxTotalMB * MB, cap)),
}
}
+197
View File
@@ -0,0 +1,197 @@
import type { BeforeEmail, FormattedEmail } from '@payloadcms/plugin-form-builder/types'
import type { BasePayload } from 'payload'
import type { FormAttachmentsOption } from './config.js'
import type { AcceptedFormFile } from './fileGate.js'
import { formatFileSize } from './fileTypes.js'
/**
* Form files are delivered by e-mail and nowhere else. The files of one
* submission travel in the request context (memory only) from submitForm to
* form-builder's `beforeEmail`; these hooks attach them to the e-mails that go
* to the company, send those themselves — to see whether the mail server took
* them — and record the outcome on the same context object for submitForm.
*/
export const FORM_FILES_CONTEXT = 'ipalFormFiles'
export type FormFileDelivery = {
files: AcceptedFormFile[]
/** Set by the delivery hook; absent = no e-mail was attempted. */
result?: { note?: string; state: 'failed' | 'sent' }
}
type EmailRow = { bcc?: null | string; cc?: null | string; emailTo?: null | string }
type FormWithEmails = { emails?: EmailRow[] | null }
/** Addresses in a To/CC/BCC value ("Anna <[email protected]>, [email protected]"), lowercase. */
export function emailAddresses(value: unknown): string[] {
const text = Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? v : ((v as { address?: string })?.address ?? ''))).join(',') : typeof value === 'string' ? value : ''
return text
.split(/[,;]/)
.map((part) => (part.match(/<([^>]+)>/)?.[1] ?? part).trim().toLowerCase())
.filter((address) => address.includes('@'))
}
const isFixedRow = (row: EmailRow) => ![row.emailTo, row.cc, row.bcc].some((v) => typeof v === 'string' && v.includes('{{'))
/**
* True when the form has an e-mail whose To, CC and BCC are written in the
* panel as fixed addresses (no `{{field}}` placeholder). Only such e-mails may
* carry a file; without one a file could not be delivered at all.
*/
export function canCarryFiles(form: FormWithEmails | null | undefined): boolean {
return (form?.emails ?? []).some(isFixedRow)
}
/**
* Every address the panel names as a fixed recipient. An e-mail with an empty
* "To" goes to the site's default address (form-builder's rule), so that one counts.
*/
export function fixedRecipients(form: FormWithEmails | null | undefined, defaultAddress?: string): Set<string> {
const fixed = new Set<string>()
for (const row of (form?.emails ?? []).filter(isFixedRow)) {
const to = emailAddresses(row.emailTo)
for (const address of [...(to.length ? to : emailAddresses(defaultAddress)), ...emailAddresses(row.cc), ...emailAddresses(row.bcc)]) {fixed.add(address)}
}
return fixed
}
/**
* May this (already formatted) e-mail carry the file? Only when EVERY recipient
* is a fixed address from the panel. The confirmation to the visitor is
* addressed with a placeholder, so it never qualifies — whatever its template says.
*/
export function mayCarryFiles(email: Pick<FormattedEmail, 'bcc' | 'cc' | 'to'>, fixed: ReadonlySet<string>): boolean {
const recipients = [...emailAddresses(email.to), ...emailAddresses(email.cc), ...emailAddresses(email.bcc)]
return recipients.length > 0 && recipients.every((address) => fixed.has(address))
}
const isPolish = (locale: unknown) => typeof locale === 'string' && locale.toLowerCase().startsWith('pl')
const escapeHtml = (text: string) =>
text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
const NOTICE_OPEN = '<p data-ipal-file-notice style="margin:16px 0 0;font-size:13px;color:#6b7280;">'
const NOTICE = /<p data-ipal-file-notice[^>]*>[\s\S]*?<\/p>/
/** Default line under an e-mail that carries a form file. */
export const fileNoticeText = (locale?: string) =>
isPolish(locale)
? 'Plik pochodzi z publicznego formularza i nie został sprawdzony pod kątem wirusów.'
: 'This file came from a public form and was not checked for viruses.'
const fileList = (files: AcceptedFormFile[]) => files.map((f) => `${f.name} (${formatFileSize(f.size)})`).join(', ')
const failureText = (files: AcceptedFormFile[], locale?: string) =>
isPolish(locale)
? `Odwiedzający dołączył plik: ${fileList(files)}, ale nie udało się go wysłać. Poproś o ponowne przesłanie.`
: `The visitor attached a file: ${fileList(files)}, but it could not be sent. Ask them to send it again.`
type HookArgs = Parameters<BeforeEmail>[1]
const contextOf = (args: HookArgs): FormFileDelivery | undefined => {
const value = (args.req.context as Record<string, unknown> | undefined)?.[FORM_FILES_CONTEXT] as FormFileDelivery | undefined
return value?.files?.length ? value : undefined
}
async function loadFixed(args: HookArgs, formsSlug: string): Promise<Set<string>> {
const formRef = (args.data as { form?: unknown } | undefined)?.form
const id = formRef && typeof formRef === 'object' ? (formRef as { id: number | string }).id : (formRef as number | string)
const form = (await args.req.payload.findByID({ id, collection: formsSlug as never, depth: 0, req: args.req })) as FormWithEmails
return fixedRecipients(form, args.req.payload.email?.defaultFromAddress)
}
/**
* First hook (before the e-mail layout): adds the "not checked for viruses"
* line to the e-mails that will carry the file, so the layout wraps it.
*/
export function buildFileNoticeHook({ formsSlug = 'forms', notice }: { formsSlug?: string; notice?: FormAttachmentsOption['notice'] } = {}): BeforeEmail {
return async (emails, args) => {
const delivery = contextOf(args)
if (!delivery || notice === false) {return emails}
try {
const fixed = await loadFixed(args, formsSlug)
const locale = typeof args.req.locale === 'string' ? args.req.locale : undefined
const text = typeof notice === 'function' ? notice(locale) : typeof notice === 'string' ? notice : fileNoticeText(locale)
return emails.map((email) => (mayCarryFiles(email, fixed) ? { ...email, html: `${email.html ?? ''}${NOTICE_OPEN}${escapeHtml(text)}</p>` } : email))
} catch {
return emails // the delivery hook reports the real problem
}
}
}
type SendOutcome = { detail?: string; ok: boolean }
/** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */
async function send(payload: BasePayload, message: { attachments?: unknown } & FormattedEmail): Promise<SendOutcome> {
try {
const result = (await payload.sendEmail(message as never)) as { detail?: string; error?: string; sent?: boolean } | null | undefined
if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false }}
return { ok: true }
} catch (err) {
return { detail: err instanceof Error ? err.message : String(err), ok: false }
}
}
const firstLine = (text: string | undefined) => (text ?? '').split('\n')[0].slice(0, 200)
/**
* Last hook (after the layout and the project's own beforeEmail): takes the
* e-mails that may carry the file, sends them WITH the attachments and records
* the outcome. The other e-mails (the confirmation to the visitor) are handed
* back to form-builder only when the file was handed to the mail server — a
* failed attempt confirms nothing to the visitor.
*
* On failure the staff e-mail goes out once more WITHOUT the file, saying that
* a file was attached and could not be sent. Each e-mail is sent once; there
* is no automatic retry (the file is not kept).
*/
export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}): BeforeEmail {
return async (emails, args) => {
const delivery = contextOf(args)
if (!delivery) {return emails}
const { payload } = args.req
const locale = typeof args.req.locale === 'string' ? args.req.locale : undefined
try {
const fixed = await loadFixed(args, formsSlug)
const carriers = emails.filter((email) => mayCarryFiles(email, fixed))
if (carriers.length === 0) {
delivery.result = { note: 'No e-mail of this form has a fixed recipient, so the file had nowhere to go.', state: 'failed' }
return []
}
const attachments = delivery.files.map((file) => ({
content: Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength),
contentDisposition: 'attachment' as const,
contentType: file.mimeType,
filename: file.name,
}))
const outcomes: SendOutcome[] = []
for (const email of carriers) {outcomes.push(await send(payload, { ...email, attachments }))}
if (outcomes.some((o) => o.ok)) {
delivery.result = { state: 'sent' }
// A recipient whose copy failed still learns about the submission, without the file.
await Promise.all(carriers.filter((_, i) => !outcomes[i].ok).map((email) => send(payload, withFailureNotice(email, delivery.files, locale))))
return emails.filter((email) => !carriers.includes(email))
}
const detail = firstLine(outcomes.find((o) => o.detail)?.detail)
delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' }
payload.logger.error(`[ipal] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`)
await Promise.all(carriers.map((email) => send(payload, withFailureNotice(email, delivery.files, locale))))
return []
} catch (err) {
delivery.result = { note: firstLine(err instanceof Error ? err.message : String(err)), state: 'failed' }
payload.logger.error(`[ipal] Form file delivery failed: ${(err as Error).message}`)
return []
}
}
}
/** The staff e-mail without the file: the virus line gives way to "could not be sent — ask again". */
function withFailureNotice(email: FormattedEmail, files: AcceptedFormFile[], locale?: string): FormattedEmail {
const notice = `<p data-ipal-file-notice style="margin:16px 0 0;font-weight:600;">${escapeHtml(failureText(files, locale))}</p>`
const html = email.html ?? ''
return { ...email, html: NOTICE.test(html) ? html.replace(NOTICE, notice) : `${html}${notice}` }
}
+19
View File
@@ -0,0 +1,19 @@
import type { Endpoint } from 'payload'
import type { ResolvedFormAttachments } from './config.js'
/**
* POST /api/ipal/forms/submit — where a panel form with a file posts
* (multipart/form-data: the answers first, the files last). Registered by the
* plugin when `forms.attachments` is on; a project wires nothing.
*
* The handler is loaded on the first request: it pulls in the submit pipeline
* (server-only) and the multipart parser, which a config load must not.
*/
export function buildFormSubmitEndpoint(options: ResolvedFormAttachments): Endpoint {
return {
handler: async (req) => (await import('./submitHandler.js')).handleFormSubmit(req),
method: 'post',
path: options.path,
}
}
@@ -0,0 +1,97 @@
import type { Block, Field } from 'payload'
import type { FormAttachmentsOption, ResolvedFormAttachments } from './config.js'
import { withShowWhen } from '../builderBlocks.js'
import { resolveFormAttachments } from './config.js'
import { DEFAULT_FORM_FILE_TYPES } from './fileTypes.js'
/**
* The "File" field of the form builder. The file a visitor attaches is never
* stored: it is checked and sent with the company e-mail (docs/forms.md).
*
* forms: { attachments: true } // adds the block
* forms: { attachments: true, fields: { file: buildFileBlock({ maxSizeMB: 5 }) } } // your own variant
*/
export function buildFileBlock(option: FormAttachmentsOption | ResolvedFormAttachments | true = true): Block {
const o = option !== true && 'types' in option ? option : resolveFormAttachments(option)
const half = { width: '50%' }
const fields: Field[] = [
{
type: 'row',
fields: [
{
name: 'name',
type: 'text',
admin: { ...half, description: { en: 'No spaces, e.g. attachment.', pl: 'Bez spacji, np. zalacznik.' } },
label: { en: 'Field key', pl: 'Klucz pola' },
required: true,
},
{ name: 'label', type: 'text', admin: half, label: { en: 'Label', pl: 'Etykieta' }, localized: true },
],
},
{
name: 'help',
type: 'text',
admin: {
description: { en: 'Shown under the field.', pl: 'Widoczny pod polem.' },
placeholder: { en: 'e.g. PDF or DOCX, up to 10 MB', pl: 'np. PDF lub DOCX, do 10 MB' },
},
label: { en: 'Help text', pl: 'Tekst pomocy' },
localized: true,
},
{
type: 'row',
fields: [
{ name: 'width', type: 'number', admin: half, label: { en: 'Width (%)', pl: 'Szerokość (%)' } },
{ name: 'required', type: 'checkbox', admin: half, label: { en: 'Required', pl: 'Wymagane' } },
],
},
{
name: 'allowedTypes',
type: 'select',
admin: {
description: {
en: 'The file is sent by e-mail and is not kept on the site.',
pl: 'Plik jest wysyłany e-mailem i nie jest przechowywany w witrynie.',
},
},
defaultValue: DEFAULT_FORM_FILE_TYPES.filter((key) => o.types[key]),
hasMany: true,
label: { en: 'Allowed file types', pl: 'Dozwolone typy plików' },
options: Object.entries(o.types).map(([value, type]) => ({ label: type.label, value })),
required: true,
},
{
type: 'row',
fields: [
{
name: 'maxSizeMB',
type: 'number',
admin: half,
defaultValue: o.maxSizeMB,
label: { en: 'Maximum size (MB)', pl: 'Maksymalny rozmiar (MB)' },
max: o.maxSizeMB,
min: 1,
},
{
name: 'maxFiles',
type: 'number',
admin: half,
defaultValue: 1,
label: { en: 'Maximum files', pl: 'Maksymalna liczba plików' },
max: o.maxFiles,
min: 1,
},
],
},
]
return withShowWhen({
slug: 'file',
fields,
labels: { plural: { en: 'File fields', pl: 'Pola pliku' }, singular: { en: 'File', pl: 'Plik' } },
})
}
/** The File block with default limits — `forms.fields.file: fileBlock`, or build your own with buildFileBlock. */
export const fileBlock: Block = buildFileBlock(true)
+196
View File
@@ -0,0 +1,196 @@
import type { FormFileType } from './fileTypes.js'
import { fileExtensions } from './fileTypes.js'
/**
* Content checks for form files — by the bytes, never by the name or the
* browser's MIME type alone. They stop the wrong KIND of file. They are not an
* antivirus: a well-formed PDF or DOC can still be malicious (attachments.scan).
*/
const startsWith = (bytes: Uint8Array, signature: readonly number[], offset = 0) =>
bytes.length >= offset + signature.length && signature.every((b, i) => bytes[offset + i] === b)
const ascii = (text: string) => [...text].map((c) => c.charCodeAt(0))
const OLE = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]
const ZIP = [0x50, 0x4b, 0x03, 0x04]
/** How many leading bytes `signatureMatches` needs. */
export const SIGNATURE_BYTES = 16
/** Programs, whatever they are named: Windows (MZ), Linux (ELF), macOS (Mach-O), scripts (#!). */
export function looksExecutable(bytes: Uint8Array): boolean {
return (
startsWith(bytes, [0x4d, 0x5a]) ||
startsWith(bytes, [0x7f, 0x45, 0x4c, 0x46]) ||
startsWith(bytes, [0xfe, 0xed, 0xfa, 0xce]) ||
startsWith(bytes, [0xfe, 0xed, 0xfa, 0xcf]) ||
startsWith(bytes, [0xce, 0xfa, 0xed, 0xfe]) ||
startsWith(bytes, [0xcf, 0xfa, 0xed, 0xfe]) ||
startsWith(bytes, [0xca, 0xfe, 0xba, 0xbe]) ||
startsWith(bytes, ascii('#!'))
)
}
/**
* First-bytes check for a built-in type key; `undefined` for a key without one
* (a project's own type — its `detect` runs on the whole file instead).
*/
export function signatureMatches(key: string, head: Uint8Array): boolean | undefined {
switch (key) {
case 'doc':
case 'xls':
return startsWith(head, OLE)
case 'docx':
case 'odt':
case 'xlsx':
return startsWith(head, ZIP)
case 'jpg':
return startsWith(head, [0xff, 0xd8, 0xff])
case 'pdf':
return startsWith(head, ascii('%PDF-'))
case 'png':
return startsWith(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
case 'rtf':
return startsWith(head, ascii('{\\rtf'))
case 'webp':
return startsWith(head, ascii('RIFF')) && startsWith(head, ascii('WEBP'), 8)
default:
return undefined
}
}
type ZipEntry = { encrypted: boolean; name: string }
const u16 = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8)
const u32 = (b: Uint8Array, o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0
/**
* Entry names from a ZIP's central directory — read WITHOUT unpacking anything,
* so a zip bomb costs nothing. `null` when the archive has no readable directory.
*/
export function zipEntries(bytes: Uint8Array, maxEntries = 5000): null | ZipEntry[] {
// End-of-central-directory record: in the last 22 bytes + up to 64 KB of comment.
const min = Math.max(0, bytes.length - 22 - 0xffff)
let eocd = -1
for (let i = bytes.length - 22; i >= min; i--) {
if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) {
eocd = i
break
}
}
if (eocd < 0) {return null}
const count = u16(bytes, eocd + 10)
let offset = u32(bytes, eocd + 16)
if (count > maxEntries) {return null}
const entries: ZipEntry[] = []
const decoder = new TextDecoder()
for (let i = 0; i < count; i++) {
if (offset + 46 > bytes.length || u32(bytes, offset) !== 0x02014b50) {return null}
const flags = u16(bytes, offset + 8)
const nameLength = u16(bytes, offset + 28)
const extraLength = u16(bytes, offset + 30)
const commentLength = u16(bytes, offset + 32)
if (offset + 46 + nameLength > bytes.length) {return null}
entries.push({ name: decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)), encrypted: (flags & 1) === 1 })
offset += 46 + nameLength + extraLength + commentLength
}
return entries
}
/** Entries a container of this type must have. */
const REQUIRED_ENTRIES: Record<string, string[]> = {
docx: ['[Content_Types].xml', 'word/document.xml'],
odt: ['mimetype', 'content.xml'],
xlsx: ['[Content_Types].xml', 'xl/workbook.xml'],
}
const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)$/i
const indexOfBytes = (bytes: Uint8Array, needle: readonly number[]) => {
outer: for (let i = 0; i <= bytes.length - needle.length; i++) {
for (let j = 0; j < needle.length; j++) {
if (bytes[i + j] !== needle[j]) {continue outer}
}
return i
}
return -1
}
const utf16 = (text: string) => [...text].flatMap((c) => [c.charCodeAt(0), 0])
/**
* VBA macros in a legacy Office file: the macro storage holds a stream named
* `_VBA_PROJECT` (Word: Macros/VBA/_VBA_PROJECT, Excel: _VBA_PROJECT_CUR), and
* the compound file's directory stores names as UTF-16. BEST-EFFORT — it finds
* ordinary macro-enabled documents, not one built to hide.
*/
export function oleHasMacros(bytes: Uint8Array): boolean {
return indexOfBytes(bytes, utf16('_VBA_PROJECT')) >= 0
}
/** PDF features that run code or carry other files — a plain byte search (attachments.strictPdf). */
export function pdfHasActiveContent(bytes: Uint8Array): boolean {
return ['/JavaScript', '/JS ', '/JS(', '/Launch', '/EmbeddedFile', '/OpenAction'].some((token) => indexOfBytes(bytes, ascii(token)) >= 0)
}
export type FileRefusal =
/** The name: no extension the field allows, a double extension, a blocked extension. */
| 'content'
/** The bytes are not what the extension claims. */
| 'name'
/** The right container, but with something refused inside (macros, encryption, a program). */
| 'signature'
/**
* Name check, before any byte of the file: the last extension must belong to
* one of the allowed types (else `type`: simply another format), and NO
* extension of the name may be a risky one ("cv.pdf.exe", "cv.exe.pdf") unless
* the project allowed it, nor a second known one ("cv.pdf.docx") — else `refused`.
*/
export function matchFileType(
name: string,
allowed: readonly string[],
types: Record<string, FormFileType>,
risky: ReadonlySet<string>,
): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
const last = extensions.at(-1)
// A program, an archive, a macro-enabled file — refused as such, not as "another format".
if (extensions.some((e) => risky.has(e))) {return { refused: 'refused' }}
if (!last) {return { refused: 'type' }}
// "cv.pdf.docx": an extra extension that names another known type hides what the file is.
const known = new Set(Object.values(types).flatMap((t) => t.extensions))
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'refused' }}
for (const key of allowed) {
const type = types[key]
if (type?.extensions.includes(last)) {return { type, key }}
}
return { refused: 'type' }
}
/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */
export async function checkFileContent(
key: string,
type: FormFileType,
bytes: Uint8Array,
{ strictPdf = false }: { strictPdf?: boolean } = {},
): Promise<FileRefusal | null> {
if (bytes.length === 0 || looksExecutable(bytes)) {return 'signature'}
const signature = signatureMatches(key, bytes.subarray(0, SIGNATURE_BYTES))
if (signature === false) {return 'signature'}
if (type.detect && !(await type.detect(bytes))) {return 'signature'}
const required = REQUIRED_ENTRIES[key]
if (required) {
const entries = zipEntries(bytes)
if (!entries) {return 'signature'}
const names = new Set(entries.map((e) => e.name))
if (required.some((name) => !names.has(name))) {return 'signature'}
if (entries.some((e) => e.encrypted || /vbaProject\.bin$/i.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'}
}
if ((key === 'doc' || key === 'xls') && oleHasMacros(bytes)) {return 'content'}
if (key === 'pdf' && strictPdf && pdfHasActiveContent(bytes)) {return 'content'}
return null
}
+178
View File
@@ -0,0 +1,178 @@
import type { FileFieldConfig, ResolvedFormAttachments } from './config.js'
import { fileFieldLimits } from './config.js'
import { checkFileContent, looksExecutable, matchFileType, SIGNATURE_BYTES, signatureMatches } from './fileChecks.js'
import { describeFileTypes, MB, safeFileName, UNSAFE_NAME_CHARACTERS } from './fileTypes.js'
/** A file that passed every check — in memory, ready for the e-mail. */
export type AcceptedFormFile = {
data: Uint8Array
/** Field key of the File field. */
field: string
mimeType: string
/** Cleaned name with the extension of the detected type. */
name: string
size: number
/** Type key, e.g. 'pdf'. */
type: string
}
/** Why a file was refused — a code for resolveFormMessage, never text. */
export type FormFileFailure = {
field: string
/** The file's name as the visitor knows it (cleaned of control characters). */
file?: string
/**
* - `file_too_large` — over the limit (`max`, MB)
* - `file_type` — a format the field does not accept (`types`)
* - `file_refused` — the right extension but not acceptable: the content does not match it, macros, a
* program, an archive, a doubled extension, or the project's scanner said no
* - `file_count` — more files than the field takes (`max`)
*/
kind: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
/** The limit: MB for file_too_large, a count for file_count. */
max?: number
/** True when the field is not required — the visitor may send the form without the file. */
optional?: boolean
/** "PDF, DOC, DOCX" — the formats the field accepts. */
types?: string
}
type FileField = { name: string; required?: boolean | null } & FileFieldConfig
/** One file being received. */
export type FileSlot = {
/** Feed the first bytes as they arrive (any chunking). Returns a failure as soon as the signature is wrong. */
checkStart: (head: Uint8Array) => FormFileFailure | null
/** Bytes this file may have; reading must stop past it. */
maxBytes: number
/** Call when a read went past `maxBytes`. */
tooLarge: () => FormFileFailure
}
const displayName = (name: string) => (name.split(/[/\\]/).pop() ?? '').replace(UNSAFE_NAME_CHARACTERS, '').slice(0, 120)
/** A limit in MB for a message: whole number, or one decimal rounded DOWN (never promise more). */
export const limitInMB = (bytes: number) => {
const mb = bytes / MB
return Number.isInteger(mb) ? mb : Math.floor(mb * 10) / 10
}
/**
* The file checks of one submission, in the order the wall needs them:
* `begin` (field, count, name — before any byte), the slot (size while reading,
* signature on the first bytes), `finish` (whole-file checks, scan), `end`
* (required fields). Used by the streaming endpoint and, with whole buffers,
* by submitForm({ files }).
*/
export function createFileGate({
fields,
options,
transportMaxBytes,
}: {
/** The form's File fields the visitor could see. */
fields: FileField[]
options: ResolvedFormAttachments
/** What the e-mail transport can carry, when it has a ceiling. */
transportMaxBytes?: null | number
}) {
const byName = new Map(fields.map((f) => [f.name, f]))
const counts = new Map<string, number>()
const accepted: AcceptedFormFile[] = []
let total = 0
const begin = (fieldName: string, rawName: string): { failure: FormFileFailure } | { slot: FileSlot; token: BeginToken } => {
const field = byName.get(fieldName)
if (!field) {return { failure: { field: fieldName, kind: 'unknown_fields' } }}
const limits = fileFieldLimits(field, options, transportMaxBytes)
const file = displayName(rawName)
const count = (counts.get(fieldName) ?? 0) + 1
counts.set(fieldName, count)
const optional = !field.required
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles, optional } }}
const types = describeFileTypes(limits.allowedTypes, options.types).labels
const refusedFailure: FormFileFailure = { field: fieldName, file, kind: 'file_refused', optional, types }
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
if ('refused' in match) {return { failure: match.refused === 'type' ? { ...refusedFailure, kind: 'file_type' } : refusedFailure }}
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
// The limit the message names is what this file may really have: the per-file limit, or what is left of
// the submission's total when other files used part of it (the whole total when nothing is left).
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(maxBytes > 0 ? maxBytes : limits.maxTotalBytes), optional })
let checked = false
return {
slot: {
checkStart: (head) => {
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
checked = true
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? refusedFailure : null
},
maxBytes,
tooLarge,
},
token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
}
}
const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => {
if (data.length > token.maxBytes) {return token.tooLarge()}
const type = options.types[token.key]
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.refusedFailure}
const file: AcceptedFormFile = {
name: safeFileName(token.rawName, type.extensions[0]),
type: token.key,
data,
field: token.field,
mimeType: type.mimeType,
size: data.length,
}
if (options.scan) {
try {
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
if (!verdict?.ok) {return token.refusedFailure}
} catch {
return token.refusedFailure
}
}
total += data.length
accepted.push(file)
return null
}
/** After the last file: a required File field without a file. */
const end = (): FormFileFailure | null => {
for (const field of fields) {
if (field.required && !accepted.some((f) => f.field === field.name)) {return { field: field.name, kind: 'required' }}
}
return null
}
return { accepted, begin, end, finish }
}
type BeginToken = {
field: string
file: string
key: string
maxBytes: number
rawName: string
refusedFailure: FormFileFailure
tooLarge: () => FormFileFailure
}
export type FileGate = ReturnType<typeof createFileGate>
/** Whole buffers through the same checks, in order. */
export async function checkBufferedFiles(gate: FileGate, files: Record<string, { data: Uint8Array; name: string }[]>): Promise<FormFileFailure | null> {
for (const [field, list] of Object.entries(files)) {
for (const file of list) {
const started = gate.begin(field, file.name)
if ('failure' in started) {return started.failure}
if (file.data.length > started.slot.maxBytes) {return started.slot.tooLarge()}
const failure = started.slot.checkStart(file.data.subarray(0, 64)) ?? (await gate.finish(started.token, file.data))
if (failure) {return failure}
}
}
return gate.end()
}
+110
View File
@@ -0,0 +1,110 @@
/**
* File types a form's File field can accept — pure data and helpers, shared by
* the panel block, the browser (accept, instant checks) and the server (the
* real checks, fileChecks.ts). No Node APIs here.
*/
/** What a custom `detect` receives: the whole file. */
export type FormFileDetect = (bytes: Uint8Array) => boolean | Promise<boolean>
export type FormFileType = {
/**
* Content check for a project's own type: true when the bytes really are this
* type. Built-in types have their own checks (fileChecks.ts). A type without
* `detect` and without a built-in check is accepted by extension only.
*/
detect?: FormFileDetect
/** Lowercase, without the dot. The first one names the attachment. */
extensions: string[]
/** Shown to the editor (panel option) and the visitor ("Accepted: PDF, DOCX"). */
label: string
mimeType: string
}
/** Built-in types. Keys are what the File field stores in `allowedTypes`. */
export const FORM_FILE_TYPES: Record<string, FormFileType> = {
doc: { extensions: ['doc'], label: 'DOC', mimeType: 'application/msword' },
docx: { extensions: ['docx'], label: 'DOCX', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
jpg: { extensions: ['jpg', 'jpeg'], label: 'JPG', mimeType: 'image/jpeg' },
odt: { extensions: ['odt'], label: 'ODT', mimeType: 'application/vnd.oasis.opendocument.text' },
pdf: { extensions: ['pdf'], label: 'PDF', mimeType: 'application/pdf' },
png: { extensions: ['png'], label: 'PNG', mimeType: 'image/png' },
rtf: { extensions: ['rtf'], label: 'RTF', mimeType: 'application/rtf' },
webp: { extensions: ['webp'], label: 'WebP', mimeType: 'image/webp' },
xls: { extensions: ['xls'], label: 'XLS', mimeType: 'application/vnd.ms-excel' },
xlsx: { extensions: ['xlsx'], label: 'XLSX', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
}
/** Ticked on a new File field. */
export const DEFAULT_FORM_FILE_TYPES = ['pdf', 'doc', 'docx']
/**
* Extensions refused whatever a field allows: programs and scripts, macro-enabled
* Office files, archives, disk images, and files a browser or mail client may run.
* A project lifts single ones with `attachments.allowRisky`.
*/
export const RISKY_FILE_EXTENSIONS = [
// programs and scripts
'apk', 'app', 'bat', 'bin', 'cmd', 'com', 'cpl', 'dll', 'exe', 'gadget', 'hta', 'jar', 'js', 'jse', 'lnk', 'mjs', 'msc',
'msi', 'msp', 'pif', 'ps1', 'psm1', 'py', 'reg', 'scr', 'sh', 'vb', 'vbe', 'vbs', 'ws', 'wsf', 'wsh',
// macro-enabled Office
'docm', 'dotm', 'potm', 'ppam', 'ppsm', 'pptm', 'xlam', 'xlsm', 'xltm',
// archives and disk images
'7z', 'bz2', 'cab', 'dmg', 'gz', 'img', 'iso', 'rar', 'tar', 'tgz', 'xz', 'zip',
// markup a browser or mail client renders
'htm', 'html', 'mht', 'mhtml', 'shtml', 'svg', 'xhtml', 'xml',
]
export const MB = 1024 * 1024
/** "2.1 MB", "640 KB" — for the file list, the answers row and e-mails. */
export function formatFileSize(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 0) {return ''}
if (bytes < 1024) {return `${bytes} B`}
if (bytes < MB) {return `${Math.round(bytes / 1024)} KB`}
const mb = bytes / MB
return `${mb >= 10 ? Math.round(mb) : Math.round(mb * 10) / 10} MB`
}
/** Every extension of a name, lowercase: "CV.final.PDF" → ['final', 'pdf']. */
export function fileExtensions(name: string): string[] {
const parts = name.split('.').slice(1)
return parts.map((p) => p.trim().toLowerCase()).filter(Boolean)
}
// Control characters, zero-width characters and bidi overrides (a name like "cv<RLO>fdp.exe" reads as "cvexe.pdf").
// eslint-disable-next-line no-control-regex
export const UNSAFE_NAME_CHARACTERS = /[\u0000-\u001F\u007F\u200B-\u200F\u202A-\u202E\u2066-\u2069]/g
const UNSAFE = UNSAFE_NAME_CHARACTERS
/**
* The name shown to staff and used on the attachment — never the raw client
* string: no path, no control or bidi characters, only letters, digits, space
* and `.-_()` in the stem, at most 80 characters, and the extension of the
* DETECTED type. An empty stem becomes "attachment".
*/
export function safeFileName(name: string, extension: string): string {
const base = (name.split(/[/\\]/).pop() ?? '').replace(UNSAFE, '').normalize('NFC')
const stem = base
.replace(/\.[^.]*$/, '')
.replace(/[^\p{L}\p{N} ._()-]+/gu, ' ')
.replace(/\.{2,}/g, '.')
.replace(/\s+/g, ' ')
.replace(/^[\s.]+|[\s.]+$/g, '')
.slice(0, 80)
.trim()
return `${stem || 'attachment'}.${extension}`
}
/** What a File field resolves to for the given type keys (unknown keys are skipped). */
export function describeFileTypes(keys: null | readonly string[] | undefined, types: Record<string, FormFileType> = FORM_FILE_TYPES) {
const list = (keys ?? []).map((key) => types[key]).filter((t): t is FormFileType => Boolean(t))
const extensions = [...new Set(list.flatMap((t) => t.extensions))]
return {
/** For `<input accept>`: extensions first (what browsers filter on), then MIME types. */
accept: [...extensions.map((e) => `.${e}`), ...new Set(list.map((t) => t.mimeType))].join(','),
extensions,
/** "PDF, DOC, DOCX" */
labels: list.map((t) => t.label).join(', '),
}
}
+124
View File
@@ -0,0 +1,124 @@
import type { CollectionAfterReadHook, CollectionBeforeValidateHook, Field } from 'payload'
import { ValidationError } from 'payload'
import type { FileFieldConfig, ResolvedFormAttachments } from './config.js'
import { mailAttachmentLimit } from '../../email/attachmentLimit.js'
import { fileFieldLimits } from './config.js'
import { canCarryFiles } from './delivery.js'
import { limitInMB } from './fileGate.js'
import { describeFileTypes } from './fileTypes.js'
type Block = { blockType?: string; resolved?: unknown } & FileFieldConfig
type FormDoc = { emails?: { bcc?: null | string; cc?: null | string; emailTo?: null | string }[] | null; fields?: Block[] | null; fileSubmitUrl?: string }
const fileBlocks = (doc: FormDoc | null | undefined) => (Array.isArray(doc?.fields) ? doc.fields.filter((f) => f?.blockType === 'file') : [])
/**
* Forms afterRead: every File field gets `resolved` — the limits that REALLY
* apply (the editor's values, capped by the plugin option and by what the
* e-mail transport can carry) and the `accept` list of its types — and the form
* gets `fileSubmitUrl`. The browser shows and checks exactly what the server
* will enforce, also for a project's own file types. Nothing is stored.
*/
export function buildFormFilesAfterRead(options: ResolvedFormAttachments): CollectionAfterReadHook {
return async ({ doc, req }) => {
const blocks = fileBlocks(doc as FormDoc)
if (blocks.length === 0) {return doc}
const transportMax = await mailAttachmentLimit(req.payload)
for (const block of blocks) {
const limits = fileFieldLimits(block, options, transportMax)
const types = describeFileTypes(limits.allowedTypes, options.types)
block.resolved = {
accept: types.accept,
extensions: types.extensions,
maxFiles: limits.maxFiles,
maxSizeMB: limitInMB(limits.maxBytes),
maxTotalMB: limitInMB(limits.maxTotalBytes),
typeLabels: types.labels,
}
}
;(doc as FormDoc).fileSubmitUrl = `${req.payload.config.routes?.api ?? '/api'}${options.path}`
return doc
}
}
/**
* Forms beforeValidate: a form with a File field needs an e-mail whose
* recipients are fixed addresses — files are delivered by e-mail only, and an
* e-mail addressed with a placeholder (the confirmation to the visitor) never
* carries one. Without such an e-mail the file would have nowhere to go.
*/
export function buildFormFilesBeforeValidate(): CollectionBeforeValidateHook {
return ({ data, originalDoc, req }) => {
const form = { ...(originalDoc as FormDoc | undefined), ...(data as FormDoc | undefined) }
if (fileBlocks(form).length === 0 || canCarryFiles(form)) {return data}
const polish = req.i18n?.language === 'pl'
throw new ValidationError({
collection: 'forms',
errors: [
{
message: polish
? 'Dodaj e-mail ze stałym adresem odbiorcy. Pliki z formularza są wysyłane wyłącznie e-mailem.'
: 'Add an e-mail with a fixed recipient address. Files from the form are sent by e-mail only.',
path: 'emails',
},
],
})
}
}
/**
* Fields the submission keeps about files — metadata only, never the file:
* name, type and size, whether the mail server took the message, and the key
* that makes a repeated request harmless.
*/
export const submissionFileFields: Field[] = [
{
name: 'submissionFiles',
type: 'array',
admin: {
description: {
en: 'Sent by e-mail to the form recipients. The files are not kept on the site.',
pl: 'Wysłane e-mailem do odbiorców formularza. Pliki nie są przechowywane w witrynie.',
},
readOnly: true,
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '40%' }, label: { en: 'File name', pl: 'Nazwa pliku' } },
{ name: 'type', type: 'text', admin: { width: '20%' }, label: { en: 'Type', pl: 'Typ' } },
{ name: 'size', type: 'number', admin: { width: '20%' }, label: { en: 'Size (bytes)', pl: 'Rozmiar (bajty)' } },
{ name: 'field', type: 'text', admin: { width: '20%' }, label: { en: 'Field key', pl: 'Klucz pola' } },
],
},
],
label: { en: 'Files', pl: 'Pliki' },
labels: { plural: { en: 'Files', pl: 'Pliki' }, singular: { en: 'File', pl: 'Plik' } },
},
{
name: 'filesDelivery',
type: 'select',
admin: { position: 'sidebar', readOnly: true },
label: { en: 'File delivery', pl: 'Dostarczenie pliku' },
options: [
{ label: { en: 'Handed to the mail server', pl: 'Przekazano do serwera poczty' }, value: 'sent' },
{ label: { en: 'Not sent', pl: 'Nie wysłano' }, value: 'failed' },
],
},
{
name: 'filesDeliveryNote',
type: 'text',
admin: {
condition: (data) => Boolean(data?.filesDeliveryNote),
description: { en: 'Ask the sender for the file again.', pl: 'Poproś nadawcę o ponowne przesłanie pliku.' },
position: 'sidebar',
readOnly: true,
},
label: { en: 'Delivery note', pl: 'Uwaga o dostarczeniu' },
},
{ name: 'attemptKey', type: 'text', admin: { hidden: true }, index: true },
]
@@ -0,0 +1,380 @@
import 'server-only'
import type { BasePayload, PayloadRequest } from 'payload'
import busboy from 'busboy'
import { Readable } from 'node:stream'
import type { FormNotificationTexts } from '../../notifications/types.js'
import type { SubmitActionResult } from '../createSubmitAction.js'
import type { SubmitFormResult } from '../submitForm.js'
import type { FileGate } from './fileGate.js'
import { mailAttachmentLimit } from '../../email/attachmentLimit.js'
import { getNotificationTexts } from '../../notifications/getNotificationTexts.js'
import { resolveFormMessage } from '../../notifications/resolveFormMessage.js'
import { clientIp } from '../../shared/rateLimit.js'
import { HONEYPOT_FIELD, isHoneypotTripped } from '../honeypot.js'
import {
cleanAttemptKey,
fileFailure,
findSubmitAttempt,
passRateLimit,
passTurnstile,
storeSubmission,
validateSubmitFields,
} from '../submitForm.js'
import { getFormAttachments } from './config.js'
import { canCarryFiles } from './delivery.js'
import { createFileGate } from './fileGate.js'
import { MB } from './fileTypes.js'
/** Room for the text parts and the multipart envelope, on top of the files. */
const ENVELOPE_BYTES = 256 * 1024
/** The answers as JSON: every field is capped at 5000 characters by validation; this is the outer ceiling. */
const VALUES_BYTES = 128 * 1024
const STATUS: Record<string, number> = { consent: 422, delivery: 502, error: 500, not_found: 404, rate_limited: 429, turnstile: 403, validation: 422 }
/** File submissions in flight in this process — the concurrency guard. */
let active = 0
/** Attempt keys being handled right now → their outcome, so a duplicate request waits instead of sending twice. */
const inflight = new Map<string, Promise<SubmitFormResult>>()
/** No byte of the body for this long → the upload is given up (a stalled or dropped connection). */
const IDLE_TIMEOUT_MS = 30_000
/** The whole request — upload, checks and e-mail — may take this long. */
const REQUEST_TIMEOUT_MS = 300_000
/** What the endpoint is holding right now — for monitoring and tests: both are 0 when nothing is in flight. */
export const formSubmitState = () => ({ active, inflight: inflight.size })
function originAllowed(req: PayloadRequest, allowed: readonly string[] = []): boolean {
const headers = req.headers
const origin = headers.get('origin')
if (origin && allowed.some((a) => a.replace(/\/$/, '') === origin)) {return true}
const site = headers.get('sec-fetch-site')
if (site) {return site === 'same-origin'}
if (!origin) {return true} // not a browser — the gates below still apply
try {
const host = new URL(origin).host
return host === (headers.get('x-forwarded-host') ?? headers.get('host'))
} catch {
return false
}
}
function localeOf(payload: BasePayload, value: unknown): string | undefined {
if (typeof value !== 'string' || !value) {return undefined}
const localization = payload.config.localization
if (!localization) {return undefined}
return localization.localeCodes.includes(value) ? value : undefined
}
/**
* The submit endpoint for forms with files. The request body is read as a
* stream, and every step runs before the next starts:
*
* origin → rate limit → declared size → concurrency guard → the answers
* (honeypot, Turnstile, validation, consent) → is there an e-mail to carry a
* file → per file: field, count, name → size while reading, signature on the
* first bytes → whole-file checks, scan → e-mail → the buffers are dropped.
*
* After a refusal nothing more is kept: the rest of the body is read and
* thrown away (so the browser gets the answer instead of a broken connection),
* and past the hard ceiling the connection is cut.
*
* A body that breaks off, stalls (`submit.idleTimeoutMs`) or runs past the
* request ceiling (`submit.timeoutMs`) is aborted: streams torn down, buffers
* dropped, the request answered. On EVERY way out the slot of the concurrency
* guard and the attempt key are released.
*/
export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const { payload } = req
const options = getFormAttachments(payload)
if (!options) {return Response.json({ success: false }, { status: 404 })}
const submit = options.submit
let locale = localeOf(payload, new URL(req.url ?? 'http://localhost').searchParams.get('locale'))
let texts: FormNotificationTexts | undefined
const respond = async (result: SubmitFormResult, status?: number): Promise<Response> => {
texts ??= (await getNotificationTexts({ locale, payload })).form
const body: SubmitActionResult = result.success
? { message: resolveFormMessage(result, texts), success: true }
: {
message: resolveFormMessage(result, texts),
reason: result.reason,
success: false,
...('field' in result && result.field ? { field: result.field } : {}),
}
return Response.json(body, { headers: { 'Cache-Control': 'no-store' }, status: status ?? (result.success ? 200 : (STATUS[result.reason] ?? 400)) })
}
// 1. Same origin, the right kind of request.
if (!originAllowed(req, submit.allowedOrigins)) {return respond({ reason: 'error', success: false }, 403)}
const contentType = req.headers.get('content-type') ?? ''
if (!/^multipart\/form-data/i.test(contentType) || !req.body) {return respond({ reason: 'error', success: false }, 415)}
// 2. Rate limit — from the headers alone, before a byte of the body.
const ip = clientIp(req.headers, submit.clientIp) || undefined
const limited = await passRateLimit({ ip, maxPerMinute: submit.maxPerMinute })
if (limited) {return respond(limited)}
// 3. A body that declares itself too large is refused unread.
const hardCap = Math.floor(options.maxTotalMB * MB) + ENVELOPE_BYTES
const declared = Number(req.headers.get('content-length'))
if (Number.isFinite(declared) && declared > hardCap) {return respond({ reason: 'error', success: false }, 413)}
// 4. Concurrency guard — each file submission holds its files in memory.
if (options.maxConcurrent > 0 && active >= options.maxConcurrent) {return respond({ reason: 'rate_limited', success: false })}
active++
let registered: string | undefined
let settle: ((result: SubmitFormResult) => void) | undefined
let final: SubmitFormResult = { reason: 'error', success: false }
/** HTTP status of an aborted request (413 over the ceiling, 408 timed out, 400 broken body). */
let abortStatus: number | undefined
try {
final = await new Promise<SubmitFormResult>((resolve) => {
const fields: Record<string, string> = {}
/** Set once → nothing more is kept; the rest of the body is discarded. */
let outcome: null | SubmitFormResult = null
let gate: FileGate | null = null
let stored: null | Parameters<typeof storeSubmission>[0] = null
let pre: null | Promise<void> = null
let chain: Promise<void> = Promise.resolve()
let received = 0
const source = Readable.fromWeb(req.body as never)
const parser = busboy({
// browsers send file names as UTF-8 ("Życiorys.pdf"); the parser's default would read them as Latin-1
defParamCharset: 'utf8',
headers: { 'content-type': contentType },
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
})
const stop = (result: SubmitFormResult) => {
outcome ??= result
}
/** File parts not read to their end yet — torn down when the request is aborted. */
const open = new Set<Readable>()
let settled = false
/** The parser reached the end of the body, or the request was aborted — no second ending. */
let done = false
/** The submission is being stored and e-mailed: its files must stay until that is over. */
let storing = false
let idleTimer: ReturnType<typeof setTimeout> | undefined
let requestTimer: ReturnType<typeof setTimeout> | undefined
/** The one way out: answers the request and stops the timers. Later calls do nothing. */
const conclude = (result: SubmitFormResult) => {
if (settled) {return}
settled = true
clearTimeout(idleTimer)
clearTimeout(requestTimer)
resolve(result)
}
/**
* Gives the request up NOW — a body that broke off (the visitor's connection dropped), stalled, or went
* over the ceiling. Waiting for the parser would wait forever: a file part of a broken body never ends.
* So everything is torn down here — the file streams (their read loops throw and let go of what they
* hold), the parser, the body — the buffers are dropped, and the request is answered. The slot of the
* concurrency guard and the attempt key are released by the `finally` below, as on every other way out.
*/
const abort = (status: number) => {
if (settled) {return}
done = true
stop({ reason: 'error', success: false })
abortStatus = status
source.unpipe(parser)
for (const stream of open) {stream.destroy(new Error('upload aborted'))}
open.clear()
parser.destroy()
source.destroy()
if (gate && !storing) {gate.accepted.length = 0}
conclude(outcome ?? { reason: 'error', success: false })
}
/**
* 5–8: everything that must hold before the first file byte is accepted.
*
* The request can be aborted (and answered, and its `finally` run) while one of the awaits below is
* still pending. So after EVERY await: if the request is over, stop — above all before the attempt key
* is registered, or the key would be left behind with nobody to release it.
*/
const beforeFiles = async () => {
locale = localeOf(payload, fields._locale) ?? locale
const formId = fields._form
let values: unknown
try {
values = JSON.parse(fields._values ?? '')
} catch {
values = null
}
if (!formId || !values || typeof values !== 'object' || Array.isArray(values)) {return stop({ reason: 'error', success: false })}
const data = values as Record<string, unknown>
// Honeypot: a fake success, nothing checked further, nothing kept.
const honeypot = submit.honeypotField ?? HONEYPOT_FIELD
if (isHoneypotTripped(data, honeypot)) {return stop({ submissionId: '', success: true })}
const { [honeypot]: _honeypot, ...answers } = data
const token = fields._token?.trim() || undefined
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
if (settled) {return}
if (blocked) {return stop(blocked)}
const checked = await validateSubmitFields({ data: answers, formId, locale, payload })
if (settled) {return}
if ('failure' in checked) {return stop(checked.failure)}
// A repeated request (same attempt key) gets the first answer; nothing is sent twice.
const attemptKey = cleanAttemptKey(fields._attempt)
if (attemptKey) {
const running = inflight.get(attemptKey)
if (running) {
const first = await running
return settled ? undefined : stop(first)
}
// No await between the check above and this registration: a request that is already over never
// gets here, and a twin request arriving now finds the key and waits for this one.
registered = attemptKey
inflight.set(attemptKey, new Promise<SubmitFormResult>((done) => (settle = done)))
const earlier = await findSubmitAttempt(payload, attemptKey)
if (settled) {return}
if (earlier) {return stop(earlier)}
}
if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })}
const transportMaxBytes = await mailAttachmentLimit(payload)
if (settled) {return}
gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes })
stored = { attemptKey, formId, locale, payload, validation: checked.validation }
}
const receiveFile = async (name: string, stream: { truncated?: boolean } & Readable, filename: string) => {
pre ??= beforeFiles()
await pre
if (outcome || !gate || !stored) {return void stream.resume()}
const { formId } = stored
const refuse = async (failure: Parameters<typeof fileFailure>[2]) => stop(await fileFailure(payload, formId, failure, locale))
// 9–10. Field, count and name — before any byte of this file.
const started = gate.begin(name, filename)
if ('failure' in started) {
stream.resume()
return refuse(started.failure)
}
const { slot, token } = started
let chunks: Buffer[] = []
let size = 0
let headChecked = false
// An aborted request destroys this stream: the loop throws and `chunks` goes with it.
for await (const chunk of stream as AsyncIterable<Buffer>) {
if (outcome) {continue} // refused: read on and keep nothing
size += chunk.length
// 11. Size, counted while reading.
if (size > slot.maxBytes) {
chunks = []
await refuse(slot.tooLarge())
continue
}
chunks.push(chunk)
// 12. Signature, as soon as the first bytes are here.
if (!headChecked && size >= 16) {
headChecked = true
const wrong = slot.checkStart(chunks.length === 1 ? chunk : Buffer.concat(chunks))
if (wrong) {
chunks = []
await refuse(wrong)
}
}
}
open.delete(stream)
if (outcome) {return}
if (stream.truncated) {return refuse(slot.tooLarge())}
// 13–14. Whole-file checks and the optional scan.
const failure = await gate.finish(token, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
if (failure) {await refuse(failure)}
}
parser.on('field', (name, value, info) => {
if (info.valueTruncated || info.nameTruncated) {return stop({ reason: 'error', success: false })}
fields[name] = value
})
parser.on('file', (name, stream, info) => {
open.add(stream)
stream.on('error', () => undefined) // a torn-down part must not become an unhandled stream error
chain = chain.then(() => receiveFile(name, stream, info.filename ?? '')).catch((err) => {
open.delete(stream)
if (settled) {return} // aborted: already answered, nothing to add
stream.resume()
payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
})
})
for (const event of ['fieldsLimit', 'filesLimit', 'partsLimit'] as const) {
parser.on(event, () => stop({ kind: 'unknown_fields', reason: 'validation', success: false }))
}
const finish = async () => {
try {
await chain
if (!outcome) {
pre ??= beforeFiles() // a request without a file part still runs every gate
await pre
}
if (!outcome && gate && stored) {
const missing = (gate).end()
if (missing) {stop(await fileFailure(payload, (stored as { formId: string }).formId, missing, locale))}
}
// 15. Store the answers and the file metadata, e-mail the files, drop the buffers.
if (!outcome && !settled && gate && stored) {
storing = true
stop(await storeSubmission({ ...(stored), files: (gate).accepted }))
}
} catch (err) {
payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
}
conclude(outcome ?? { reason: 'error', success: false })
}
parser.on('close', () => {
if (done) {return}
done = true
void finish()
})
// A body that breaks off mid-upload (or a parser error) never reaches 'close' on its own: abort.
const broken = () => {
if (!done) {abort(400)}
}
parser.on('error', broken)
source.on('error', broken)
// A stalled upload: no byte for too long while the body is still coming. And a ceiling on the whole request.
const idleMs = submit.idleTimeoutMs ?? IDLE_TIMEOUT_MS
const requestMs = submit.timeoutMs ?? REQUEST_TIMEOUT_MS
const watchIdle = () => {
clearTimeout(idleTimer)
if (idleMs > 0 && !settled && !done) {idleTimer = setTimeout(() => !done && abort(408), idleMs)}
}
watchIdle()
if (requestMs > 0) {requestTimer = setTimeout(() => abort(408), requestMs)}
source.on('end', () => clearTimeout(idleTimer)) // the body is in; from here only the request ceiling applies
source.on('data', (chunk: Buffer) => {
watchIdle()
// Hard ceiling on what is read at all, whatever Content-Length said (or did not say: a chunked body).
received += chunk.length
if (received > hardCap) {abort(413)}
})
source.pipe(parser)
})
} finally {
active--
if (registered) {inflight.delete(registered)}
settle?.(final)
}
return respond(final, abortStatus)
}
+61 -4
View File
@@ -1,5 +1,6 @@
import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
import type { BuilderField, BuilderFileLimits, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
import { describeFileTypes, fileExtensions, MB } from './attachments/fileTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js'
@@ -102,12 +103,64 @@ export function visibleFields<F extends ConditionalField>(fields: F[] | null | u
return list.filter((field) => visible(field))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
/** A selected file as the logic needs it — a browser `File` fits. */
export type BuilderFile = { name: string; size: number }
/**
* The limits of a File field in the browser: what the server resolved
* (`field.resolved`), else the field's own values with the built-in types.
*/
export function fileFieldRules(field: BuilderField): Required<BuilderFileLimits> {
const own = describeFileTypes(field.allowedTypes)
const r = field.resolved ?? {}
const maxSizeMB = r.maxSizeMB ?? field.maxSizeMB ?? 10
return {
accept: r.accept ?? own.accept,
extensions: r.extensions ?? own.extensions,
maxFiles: r.maxFiles ?? field.maxFiles ?? 1,
maxSizeMB,
maxTotalMB: r.maxTotalMB ?? maxSizeMB,
typeLabels: r.typeLabels ?? own.labels,
}
}
/**
* The first problem with the files picked for a File field, as the visitor's
* message — the same rules the server enforces (it checks the content too).
*/
export function fileFieldError(
field: BuilderField,
files: readonly BuilderFile[],
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
): string | undefined {
const rules = fileFieldRules(field)
const label = field.label || field.name || ''
const generic = texts.validation.replace('{field}', label)
// On a field that is not required the visitor may also send the form without the file — say so.
const say = (text: string | undefined, fill: (text: string) => string) =>
text ? `${fill(text)}${!field.required && texts.fileOptional ? ` ${texts.fileOptional}` : ''}` : generic
if (files.length > rules.maxFiles) {return say(texts.fileCount, (t) => t.replace('{field}', label).replace('{max}', String(rules.maxFiles)))}
for (const file of files) {
if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) {
return say(texts.fileType, (t) => t.replace('{file}', file.name).replace('{types}', rules.typeLabels))
}
if (file.size > rules.maxSizeMB * MB || file.size === 0) {
return say(texts.fileTooLarge, (t) => t.replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB)))
}
}
if (files.reduce((sum, f) => sum + f.size, 0) > rules.maxTotalMB * MB) {
return say(texts.fileTooLarge, (t) => t.replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB)))
}
return undefined
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], file → File[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries(
inputFields(fields).map((f) => {
if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]}
if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]}
if (f.blockType === 'file') {return [f.name, []]}
const v = f.defaultValue
return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : '']
}),
@@ -120,7 +173,7 @@ const isBlank = isBlankValue
export function validateBuilderFields(
fields: BuilderField[],
values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'validation'>,
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
): Record<string, string> {
const errors: Record<string, string> = {}
for (const f of inputFields(fields)) {
@@ -130,7 +183,11 @@ export function validateBuilderFields(
if (f.required) {errors[f.name] = msg}
continue
}
if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
if (f.blockType === 'file') {
const problem = Array.isArray(v) ? fileFieldError(f, v as BuilderFile[], texts) : msg
if (problem) {errors[f.name] = problem}
}
else if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg}
else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) {
if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg}
+37 -1
View File
@@ -13,16 +13,42 @@ export type BuilderOption = { label?: null | string; value: string }
*/
export type FieldCondition = { field?: null | string; values?: null | string }
/**
* What the server resolved for a File field (forms afterRead): the limits that
* really apply and the types as the browser needs them. Absent when the form
* was not read through Payload — the hook falls back to the field's own values.
*/
export type BuilderFileLimits = {
/** For `<input accept>`. */
accept?: string
/** Lowercase, without the dot. */
extensions?: string[]
maxFiles?: number
maxSizeMB?: number
/** All files of one submission together. */
maxTotalMB?: number
/** "PDF, DOC, DOCX" */
typeLabels?: string
}
export type BuilderField = {
/** file — type keys ticked in the panel */
allowedTypes?: null | string[]
blockName?: null | string
/** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
/** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · file · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
description?: null | string
/** file — text under the field */
help?: null | string
id?: null | string
label?: null | string
/** file */
maxFiles?: null | number
maxSelected?: null | number
/** file */
maxSizeMB?: null | number
/** message — rich text, rendered on the server (RenderForm) */
message?: unknown
minSelected?: null | number
@@ -30,6 +56,8 @@ export type BuilderField = {
options?: BuilderOption[] | null
placeholder?: null | string
required?: boolean | null
/** file — see BuilderFileLimits */
resolved?: BuilderFileLimits | null
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
showWhen?: FieldCondition | null
/** step */
@@ -42,6 +70,8 @@ export type BuilderFormDoc = {
confirmationMessage?: unknown
confirmationType?: 'message' | 'redirect' | null
fields?: BuilderField[] | null
/** Where a submission with files is posted (set by the server for forms with a File field). */
fileSubmitUrl?: null | string
id: number | string
redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null
submitButtonLabel?: null | string
@@ -52,6 +82,12 @@ export type BuilderFormDoc = {
export type BuilderFormTexts = {
back?: string
error?: string
/** File field — see FormNotificationTexts. */
fileCount?: string
fileOptional?: string
fileRemove?: string
fileTooLarge?: string
fileType?: string
next?: string
/** "Step {current} of {total}" */
stepOf?: string
+30 -1
View File
@@ -32,6 +32,31 @@ export type SubmitActionResult = {
success: boolean
}
type BlobLike = { arrayBuffer: () => Promise<ArrayBuffer>; name?: string }
const isBlob = (v: unknown): v is BlobLike => typeof v === 'object' && v !== null && typeof (v as BlobLike).arrayBuffer === 'function'
/**
* Splits `File` values (one or an array, under a File field's key) from the
* answers — for an action or route that receives files itself and hands them to
* `submitForm({ data: fields, files })`.
*/
export async function splitFormFiles(values: Record<string, unknown>): Promise<{
fields: Record<string, unknown>
files?: Record<string, { data: Uint8Array; name: string }[]>
}> {
const fields: Record<string, unknown> = {}
const files: Record<string, { data: Uint8Array; name: string }[]> = {}
for (const [key, value] of Object.entries(values)) {
const list = Array.isArray(value) ? value : [value]
if (list.length > 0 && list.every(isBlob)) {
files[key] = await Promise.all(list.map(async (file) => ({ name: file.name ?? '', data: new Uint8Array(await file.arrayBuffer()) })))
} else {
fields[key] = value
}
}
return Object.keys(files).length ? { fields, files } : { fields }
}
/**
* The one server action every panel form posts to — honeypot → client IP →
* submitForm (rate limit, Turnstile, schema validation, GDPR consent, storage)
@@ -68,12 +93,16 @@ export function createSubmitAction({
const texts = (await getNotificationTexts({ locale, payload })).form
const data = values && typeof values === 'object' ? values : {}
if (isHoneypotTripped(data, honeypotField)) {return { message: texts.success, success: true }}
const { [honeypotField]: _honeypot, ...fields } = data
const { [honeypotField]: _honeypot, ...rest } = data
// Files a project sends through the action itself (panel forms post files to
// the streaming endpoint instead): split them from the answers.
const { fields, files } = await splitFormFiles(rest)
const ip = clientIp(await headers(), ipOptions) || undefined
const result = await submitForm({
consentFieldName,
data: fields,
...(files ? { files } : {}),
formId: String(formId),
ip,
locale,
+51 -8
View File
@@ -7,6 +7,11 @@ import type { AdminText } from '../admin-i18n/define.js'
import type { FormsOption } from './types.js'
import { userMeetsRole } from '../access/predicates.js'
import { resolveFormAttachments } from './attachments/config.js'
import { buildFileDeliveryHook, buildFileNoticeHook } from './attachments/delivery.js'
import { buildFormSubmitEndpoint } from './attachments/endpoint.js'
import { buildFileBlock } from './attachments/fileBlock.js'
import { buildFormFilesAfterRead, buildFormFilesBeforeValidate, submissionFileFields } from './attachments/formHooks.js'
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
@@ -206,15 +211,25 @@ function hideEmails(fields: Field[]): Field[] {
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? { en: 'Forms', pl: 'Formularze' } : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
const formsSlug = forms.formOverrides?.slug ?? 'forms'
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug }) : undefined
// Files (forms.attachments): never stored — attached to the company e-mail by
// the two hooks around the layout, and dropped (attachments/delivery).
const attachments = forms.attachments ? resolveFormAttachments(forms.attachments) : null
const fileNotice = attachments ? buildFileNoticeHook({ formsSlug, notice: attachments.notice }) : undefined
const fileDelivery = attachments ? buildFileDeliveryHook({ formsSlug }) : undefined
const beforeEmail: BeforeEmail | undefined =
layout || forms.beforeEmail
layout || forms.beforeEmail || attachments
? async (emails, args) => {
const laidOut = layout ? await layout(emails, args) : emails
return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut
const noticed = fileNotice ? await fileNotice(emails, args) : emails
const laidOut = layout ? await layout(noticed, args) : noticed
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
return fileDelivery ? fileDelivery(changed, args) : changed
}
: undefined
return formBuilderPlugin({
const fileBlockOption = forms.fields?.file
const formHooks = forms.formOverrides?.hooks
const builder = formBuilderPlugin({
...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
@@ -225,6 +240,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: builtin('date'),
email: withHint('email'),
// File (ipal): only with forms.attachments; `false` hides it, a block object replaces it.
...(attachments && fileBlockOption !== false
? { file: (typeof fileBlockOption === 'object' ? fileBlockOption : buildFileBlock(attachments)) as never }
: {}),
message: builtin('message'),
number: withHint('number'),
payment: false,
@@ -236,7 +255,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
time: forms.fields?.time === false ? false : timeBlock,
...Object.fromEntries(
// `true` keeps ipal's block (with "Show only when"); false / an object override it
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'file' && k !== 'step' && k !== 'time' && v !== true),
),
},
...(forms.redirectRelationships
@@ -258,6 +277,15 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
...forms.formOverrides?.access,
},
admin: { ...group, ...forms.formOverrides?.admin },
...(attachments
? {
hooks: {
...formHooks,
afterRead: [...(formHooks?.afterRead ?? []), buildFormFilesAfterRead(attachments)],
beforeValidate: [...(formHooks?.beforeValidate ?? []), buildFormFilesBeforeValidate()],
},
}
: {}),
fields: ({ defaultFields }) => {
const protectedFields = hideEmails(localizeFormBuilder(defaultFields))
return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields
@@ -272,11 +300,26 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
read: submissionsReadAccess,
...forms.formSubmissionOverrides?.access,
},
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
admin: {
...group,
defaultColumns: attachments ? ['form', 'filesDelivery', 'createdAt'] : ['form', 'createdAt'],
...forms.formSubmissionOverrides?.admin,
},
fields: ({ defaultFields }) => {
const labelled = labelSubmissionFields(defaultFields)
const labelled = [...labelSubmissionFields(defaultFields), ...(attachments ? submissionFileFields : [])]
return forms.formSubmissionOverrides?.fields ? forms.formSubmissionOverrides.fields({ defaultFields: labelled }) : labelled
},
},
})
if (!attachments) {return builder}
// The submit endpoint for forms with files, and the resolved option where
// submitForm and the endpoint read it (payload.config.custom.ipal.formAttachments).
return (incoming) => {
const config = builder(incoming)
return {
...config,
custom: { ...config.custom, ipal: { ...(config.custom?.ipal as object | undefined), formAttachments: attachments } },
endpoints: [...(config.endpoints ?? []), buildFormSubmitEndpoint(attachments)],
}
}
}
+11 -2
View File
@@ -1,8 +1,17 @@
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { fileFieldLimits, FORM_SUBMIT_PATH, getFormAttachments, resolveFormAttachments } from './attachments/config.js'
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions, ResolvedFormAttachments } from './attachments/config.js'
export { canCarryFiles, fileNoticeText, fixedRecipients, mayCarryFiles } from './attachments/delivery.js'
export { buildFileBlock, fileBlock } from './attachments/fileBlock.js'
export type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.js'
export { DEFAULT_FORM_FILE_TYPES, describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from './attachments/fileTypes.js'
export type { FormFileDetect, FormFileType } from './attachments/fileTypes.js'
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
export { fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
export type { BuilderFile } from './builderLogic.js'
export type { BuilderField, BuilderFileLimits, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+265 -53
View File
@@ -2,12 +2,26 @@ import 'server-only'
import type { BasePayload } from 'payload'
import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.js'
import type { FormValidationResult } from './validateSubmission.js'
import { mailAttachmentLimit } from '../email/attachmentLimit.js'
import { getTurnstileConfig } from '../turnstile/config.js'
import { verifyTurnstile } from '../turnstile/verify.js'
import { getFormAttachments } from './attachments/config.js'
import { canCarryFiles, FORM_FILES_CONTEXT, type FormFileDelivery } from './attachments/delivery.js'
import { checkBufferedFiles, createFileGate } from './attachments/fileGate.js'
import { formatFileSize } from './attachments/fileTypes.js'
import { consumeRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
export type SubmitFormArgs = {
/**
* A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`).
* A second request with the same key returns the first outcome and sends no
* e-mail again. Stored only with `forms.attachments`.
*/
attemptKey?: string
/**
* Name of the GDPR consent checkbox. A field with this name must be checked
* for the submission to succeed (enforced server-side). Defaults to
@@ -16,6 +30,11 @@ export type SubmitFormArgs = {
consentFieldName?: string
/** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown>
/**
* Files by File-field key, as whole buffers — for a project's own transfer
* path (needs `forms.attachments`). Checked like any upload and e-mailed, never stored.
*/
files?: Record<string, { data: Uint8Array; name: string }[]>
/** Form-builder form ID this submission belongs to. */
formId: string
/** Client IP — used for Turnstile and rate limiting. */
@@ -59,18 +78,42 @@ export type SubmitFormArgs = {
* at fault (absent for whole-payload problems like unknown keys)
* - `not_found` — no form with this id
* - `consent` — a required GDPR consent checkbox was left unchecked
* - `delivery` — the attached file could not be sent by e-mail
* - `error` — persistence failed unexpectedly
*/
export type SubmitFailure =
| {
/**
* The file could not be handed to the mail server (or the form has no
* e-mail that may carry it). The file is gone — the visitor must send it
* again. `submissionId`: the stored attempt, marked "Not sent". `field`
* and `file`: the File field and the file name(s), so the message shows
* at the field and names the file; `optional`: the field is not required.
*/
field?: string
file?: string
optional?: boolean
reason: 'delivery'
submissionId?: number | string
success: false
}
| {
/** The offending field's name, when one field is at fault. */
field?: string
/** The refused file's name (file_too_large, file_type, file_refused). */
file?: string
/** What was wrong with it. */
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
kind?: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
label?: string
/** The limit behind file_too_large (MB) or file_count (files). */
max?: number
/** A file problem on a field that is not required — the form can be sent without the file. */
optional?: boolean
reason: 'validation'
success: false
/** Accepted types, "PDF, DOCX" (file_type). */
types?: string
}
| {
field?: string
@@ -85,96 +128,265 @@ export type SubmitFailure =
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
* against the form's own schema, then store.
*
* The order is cost-ascending on purpose — the cheapest checks reject first, so
* a flood never reaches Turnstile's network call or the database.
*
* Emails aren't sent here. The form-builder sends whatever an editor configured
* under the form's "Emails" tab (form-submissions hook → payload.sendEmail),
* which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.
*
* server-only: touches the Turnstile secret.
*/
export async function submitForm({
consentFieldName,
data,
formId,
/** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */
export async function passSubmitGates({
ip,
locale,
maxPerMinute = 5,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
// No IP → the limiter's shared "unknown" bucket, never a free pass.
if (maxPerMinute > 0) {
if (!(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) {
return { reason: 'rate_limited', success: false }
}
}
}: Pick<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken }))
}
// 2. Turnstile — decided by the SERVER's config, never by whether the client
// sent a token: configured → a token is required and verified (a bot can't
// opt out by omitting it); not configured → skipped, the widget isn't shown.
/** 1. Rate limit — cheapest gate, drops a flood before any real work. No IP → the shared "unknown" bucket, never a free pass. */
export async function passRateLimit({ ip, maxPerMinute = 5 }: Pick<SubmitFormArgs, 'ip' | 'maxPerMinute'>): Promise<null | SubmitFailure> {
if (maxPerMinute > 0 && !(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) {
return { reason: 'rate_limited', success: false }
}
return null
}
/**
* 2. Turnstile — decided by the SERVER's config, never by whether the client
* sent a token: configured → a token is required and verified (a bot can't opt
* out by omitting it); not configured → skipped, the widget isn't shown.
*/
export async function passTurnstile({
ip,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileToken,
}: Pick<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
if ((await getTurnstileConfig(payload)).enabled) {
const ok =
Boolean(turnstileToken) &&
(await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
if (!ok) {
return { reason: 'turnstile', success: false }
}
if (!ok) {return { reason: 'turnstile', success: false }}
}
return null
}
// 3. Validate against the form's schema. A public endpoint can't trust the
// shape of `data` — drop unknown keys, enforce required, cap length.
type ValidSubmission = Extract<FormValidationResult, { ok: true }>
/**
* 3. Validate against the form's schema. A public endpoint can't trust the
* shape of `data` — drop unknown keys, enforce required, cap length, enforce consent.
*/
export async function validateSubmitFields({
consentFieldName,
data,
formId,
locale,
payload,
}: Pick<SubmitFormArgs, 'consentFieldName' | 'data' | 'formId' | 'locale' | 'payload'>): Promise<{ failure: SubmitFailure } | { validation: ValidSubmission }> {
// Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'.
const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName
const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined)
const validation = await validateSubmission(payload, formId, data, consentField)
if (!validation.ok) {
if (validation.reason === 'not_found') {
return { reason: 'not_found', success: false }
}
if (validation.reason === 'consent') {
return { field: validation.field, reason: 'consent', success: false }
}
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
return {
if (validation.ok) {return { validation }}
if (validation.reason === 'not_found') {return { failure: { reason: 'not_found', success: false } }}
if (validation.reason === 'consent') {return { failure: { field: validation.field, reason: 'consent', success: false } }}
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
return {
failure: {
reason: 'validation',
success: false,
...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}),
...(label ? { label } : {}),
}
},
}
}
// 4. Persist (form-builder shape: submissionData array). Triggers the email
// hook. Only validated, known fields are stored.
/** A refused file as a submit failure, with the field's label for the message. */
export async function fileFailure(payload: BasePayload, formId: string, failure: FormFileFailure, locale?: string): Promise<SubmitFailure> {
if (failure.kind === 'unknown_fields') {return { kind: 'unknown_fields', reason: 'validation', success: false }}
const label = await fieldLabel(payload, formId, failure.field, locale)
return {
field: failure.field,
kind: failure.kind,
reason: 'validation',
success: false,
...(failure.file ? { file: failure.file } : {}),
...(label ? { label } : {}),
...(failure.max !== undefined ? { max: failure.max } : {}),
...(failure.optional ? { optional: true } : {}),
...(failure.types ? { types: failure.types } : {}),
}
}
const ATTEMPT_KEY = /^[\w-]{16,64}$/
/** A usable attempt key, or undefined. */
export const cleanAttemptKey = (key: unknown): string | undefined => (typeof key === 'string' && ATTEMPT_KEY.test(key) ? key : undefined)
/**
* The outcome of an earlier request with this attempt key, when one was stored —
* a repeated request (double click, a proxy or browser resend) gets the first
* answer and sends nothing again. Only with `forms.attachments` (the field exists then).
*/
export async function findSubmitAttempt(payload: BasePayload, attemptKey: string | undefined): Promise<null | SubmitFormResult> {
if (!attemptKey || !getFormAttachments(payload)) {return null}
try {
const found = await payload.find({
collection: 'form-submissions',
depth: 0,
limit: 1,
where: { attemptKey: { equals: attemptKey } },
} as never)
const doc = found.docs[0] as { filesDelivery?: string; id: number | string; submissionFiles?: { field?: string; name?: string }[] } | undefined
if (!doc) {return null}
if (doc.filesDelivery !== 'failed') {return { submissionId: doc.id, success: true }}
const kept = doc.submissionFiles ?? []
return {
reason: 'delivery',
submissionId: doc.id,
success: false,
...(kept[0]?.field ? { field: kept[0].field } : {}),
...(kept.length ? { file: kept.map((f) => f.name).join(', ') } : {}),
}
} catch {
return null
}
}
/**
* 4. Persist (form-builder shape: submissionData array). Triggers the e-mail
* hook. Only validated, known fields are stored.
*
* Files are NOT stored. They ride in the request context to the e-mail hook
* (attachments/delivery), which attaches them to the company e-mail; the
* submission keeps their name, type and size and whether the mail server took them.
*/
export async function storeSubmission({
attemptKey,
files = [],
formId,
locale,
payload,
validation,
}: {
attemptKey?: string
/** Files that passed the file gate. */
files?: AcceptedFormFile[]
validation: ValidSubmission
} & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> {
const attachments = getFormAttachments(payload)
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
const fileNames = files.map((f) => ({ name: f.name, field: f.field }))
const text = (value: unknown) =>
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
// Rows in the form's field order; a File field's row is "CV.pdf (2.1 MB)".
const rows: { field: string; value: string }[] = []
for (const field of validation.form.fields ?? []) {
if (typeof field.name !== 'string') {continue}
if (field.name in validation.cleaned) {rows.push({ field: field.name, value: text(validation.cleaned[field.name]) })}
const own = files.filter((f) => f.field === field.name)
if (own.length) {rows.push({ field: field.name, value: own.map((f) => `${f.name} (${formatFileSize(f.size)})`).join(', ') })}
}
try {
const submission = await payload.create({
collection: 'form-submissions',
...(locale ? { locale: locale as never } : {}),
...(delivery ? { context: { [FORM_FILES_CONTEXT]: delivery } } : {}),
data: {
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
submissionData: rows,
...(attachments && attemptKey ? { attemptKey } : {}),
// "Not sent" until the mail server has taken the message — a crash in between must not read as sent.
...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}),
} as never,
})
return { submissionId: submission.id, success: true }
if (!delivery) {return { submissionId: submission.id, success: true }}
const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const }
try {
await payload.update({
id: submission.id,
collection: 'form-submissions',
data: { filesDelivery: result.state, filesDeliveryNote: result.note ?? '' } as never,
depth: 0,
})
} catch (err) {
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
}
if (result.state === 'sent') {return { submissionId: submission.id, success: true }}
// The message belongs at the File field and names the file — never the mail server's own words.
const fileField = validation.fileFields.find((f) => f.name === fileNames[0]?.field)
return {
field: fileNames[0]?.field,
file: fileNames.map((f) => f.name).join(', '),
reason: 'delivery',
submissionId: submission.id,
success: false,
...(fileField && !fileField.required ? { optional: true } : {}),
}
} catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { reason: 'error', success: false }
} finally {
// The buffers are not needed past this point — drop the references now.
if (delivery) {delivery.files = []}
}
}
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
* against the form's own schema, check the files, then store and e-mail.
*
* The order is cost-ascending on purpose — the cheapest checks reject first, so
* a flood never reaches Turnstile's network call or the database.
*
* Emails aren't composed here. The form-builder sends whatever an editor
* configured under the form's "Emails" tab (form-submissions hook →
* payload.sendEmail), over the configured email adapter (mailAdapter).
*
* `files` (whole buffers) is for a project's own transfer path; panel forms
* send files to the streaming endpoint (attachments/endpoint), which runs
* these same stages around the read.
*
* server-only: touches the Turnstile secret.
*/
export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult> {
const { attemptKey: rawKey, files, formId, locale, payload } = args
const blocked = await passSubmitGates(args)
if (blocked) {return blocked}
const checked = await validateSubmitFields(args)
if ('failure' in checked) {return checked.failure}
const { validation } = checked
const attemptKey = cleanAttemptKey(rawKey)
const repeated = await findSubmitAttempt(payload, attemptKey)
if (repeated) {return repeated}
const hasFiles = Object.values(files ?? {}).some((list) => list.length > 0)
const attachments = getFormAttachments(payload)
if (!attachments || validation.fileFields.length === 0) {
// A file without the feature (or without a File field) is an unknown field.
if (hasFiles) {
// Never dropped silently: the caller sent files this site (or this form) does not take.
payload.logger.warn(
attachments
? `[ipal] submitForm: files were sent to form ${formId}, which has no File field — refused.`
: '[ipal] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in ipalKit({ forms: { attachments: true } }).',
)
return { kind: 'unknown_fields', reason: 'validation', success: false }
}
return storeSubmission({ attemptKey, formId, locale, payload, validation })
}
if (hasFiles && !canCarryFiles(validation.form)) {return { field: Object.keys(files ?? {})[0], reason: 'delivery', success: false }}
const gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) })
const refused = await checkBufferedFiles(gate, files ?? {})
if (refused) {return fileFailure(payload, formId, refused, locale)}
return storeSubmission({ attemptKey, files: gate.accepted, formId, locale, payload, validation })
}
/**
* The label of one form field in the page's language, so a message names the
* field the way the visitor sees it ("E-mail address", not "email"). Only read
+12 -1
View File
@@ -1,5 +1,7 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { CollectionConfig, Field } from 'payload'
import type { Block, CollectionConfig, Field } from 'payload'
import type { FormAttachmentsOption } from './attachments/config.js'
/**
* Receives the collection's default fields and returns the final list — add,
@@ -26,6 +28,13 @@ export type FormsOption = {
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: false | Record<string, string> | string
/**
* Files on panel forms: adds the "File" field to the form builder. A file is
* checked, attached to the company e-mail and dropped — it is NEVER stored
* (no collection, no bucket, no download route). Default off; `true` = the
* defaults (10 MB, PDF/DOC/DOCX ticked on a new field). See docs/forms.md.
*/
attachments?: boolean | FormAttachmentsOption
/**
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
* the ipal layout when `emailLayout` is on.
@@ -51,6 +60,8 @@ export type FormsOption = {
country?: boolean
date?: boolean
email?: boolean
/** File field (ipal) — exists only with `attachments`. `false` hides it, a block replaces it. */
file?: Block | boolean
message?: boolean
number?: boolean
payment?: boolean
+136 -5
View File
@@ -8,14 +8,22 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.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 = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
/**
* Where a submission WITH files is posted. Default: the form's own
* `fileSubmitUrl` (set by the server), then '/api/ipal/forms/submit'.
*/
fileSubmitUrl?: string
form: BuilderFormDoc
/** The page language — sent with a submission that carries files (prepareBuilderForm sets it). */
locale?: string
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
navigate?: (href: string) => void
/** After a successful submit — on top of the panel's analytics event. */
@@ -46,7 +54,7 @@ export type UseBuilderFormOptions = {
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
@@ -56,10 +64,42 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
// One key per submit attempt: a repeated request (double click, a resend by the
// 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<HTMLInputElement | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const shown = new Set(visibleInputs(values).map((field) => field.name))
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
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: Record<string, unknown> = 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<ReturnType<BuilderFormAction>>
if (files.length > 0) {
// Files never go through the server action: one multipart request to the
// plugin's endpoint — the answers first, the files last — read there as a stream.
attemptKey.current ||= (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`).replace(/[^\w-]/g, '')
const body = new FormData()
body.append('_form', String(form.id))
if (locale) {body.append('_locale', locale)}
body.append('_attempt', attemptKey.current)
if (token) {body.append('_token', token)}
body.append('_values', JSON.stringify(answers))
for (const { name, file } of files) {body.append(name, file, file.name)}
const url = fileSubmitUrl ?? form.fileSubmitUrl ?? '/api/ipal/forms/submit'
const response = await fetch(locale ? `${url}?locale=${encodeURIComponent(locale)}` : url, { body, credentials: 'omit', method: 'POST' })
result = (await response.json()) as Awaited<ReturnType<BuilderFormAction>>
attemptKey.current = ''
} else {
result = await action(answers, token)
}
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {
// No message from the server → name the field by its label, as the visitor sees it.
@@ -68,7 +108,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
}
return result
},
[action, fields, texts.validation, visibleInputs],
[action, fields, fileSubmitUrl, form.fileSubmitUrl, form.id, locale, texts.validation, visibleInputs],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
@@ -242,6 +282,92 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
[f, getFieldProps, textValue],
)
/** Props of the hidden honeypot input — render one `<input {...f.getHoneypotProps()} />` 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
// inputs are kept in step with them, so removing a file really removes it.
const fileInputs = useRef(new Map<string, HTMLInputElement>())
const syncFileInput = useCallback((name: string, files: File[]) => {
const input = fileInputs.current.get(name)
if (!input) {return}
try {
const transfer = new DataTransfer()
for (const file of files) {transfer.items.add(file)}
input.files = transfer.files
} catch {
if (files.length === 0) {input.value = ''}
}
}, [])
/** The files picked for a File field. */
const getFiles = useCallback(
(field: BuilderField): File[] => {
const value = f.values[field.name ?? '']
return Array.isArray(value) ? (value as File[]) : []
},
[f.values],
)
const setFiles = useCallback(
(field: BuilderField, files: File[]) => {
const name = field.name ?? ''
f.setField(name, files)
syncFileInput(name, files)
// Instant feedback: too large, wrong type, too many — the server checks again, and the content too.
const problem = files.length ? fileFieldError(field, files, texts) : undefined
if (problem) {setErrors((prev) => ({ ...prev, [name]: problem }))}
},
[f, setErrors, syncFileInput, texts],
)
/** Props of the `<input type="file">` of a File field. */
const getFileProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const rules = fileFieldRules(field)
const base = getFieldProps(field)
return {
...base,
type: 'file' as const,
accept: rules.accept || undefined,
'aria-describedby': [field.help ? helpId(field) : undefined, base['aria-describedby']].filter(Boolean).join(' ') || undefined,
multiple: rules.maxFiles > 1,
onChange: (e: ChangeEvent<HTMLInputElement>) => {
const picked = Array.from(e.target.files ?? [])
// Several files: each pick adds to the list (the same file twice counts once).
const current = rules.maxFiles > 1 ? getFiles(field) : []
const known = new Set(current.map((file) => `${file.name}:${file.size}`))
setFiles(field, [...current, ...picked.filter((file) => !known.has(`${file.name}:${file.size}`))])
},
ref: (input: HTMLInputElement | null) => {
if (input) {fileInputs.current.set(name, input)}
else {fileInputs.current.delete(name)}
},
}
},
[getFieldProps, getFiles, helpId, setFiles],
)
/** Removes one picked file and puts the focus back on the field. */
const removeFile = useCallback(
(field: BuilderField, index: number) => {
setFiles(field, getFiles(field).filter((_, i) => i !== index))
fileInputs.current.get(field.name ?? '')?.focus()
},
[getFiles, setFiles],
)
/** Props of one option's input in a radio group or checkboxGroup. */
const getOptionProps = useCallback(
(field: BuilderField, option: BuilderOption, i: number) => {
@@ -279,15 +405,20 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
fieldId,
form,
getFieldProps,
getFileProps,
getFiles,
getHoneypotProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
helpId,
isFirst,
isFixed,
isLast,
next,
removeFile,
/** Message the server returned on success (Notifications → success). */
resultMessage,
step,
+25 -2
View File
@@ -6,10 +6,15 @@ import { visibleFields } from './builderLogic.js'
/** A form-builder field, trimmed to what validation needs. */
type FormField = {
/** file */
allowedTypes?: null | string[]
blockType?: string
label?: string
/** file */
maxFiles?: null | number
/** checkboxGroup limits. */
maxSelected?: null | number
maxSizeMB?: null | number
minSelected?: null | number
name?: string
/** select / radio / checkboxGroup choices defined in the panel. */
@@ -20,6 +25,8 @@ type FormField = {
}
type FormDoc = {
/** Emails tab — read by the file delivery (which e-mail may carry a file). */
emails?: { bcc?: null | string; cc?: null | string; emailTo?: null | string }[] | null
fields?: FormField[]
id: number | string
/** Per-form notification address, when the client added the field. */
@@ -39,7 +46,13 @@ export type FormValidationResult =
ok: false
reason: 'invalid'
}
| { cleaned: Record<string, unknown>; form: FormDoc; ok: true }
| {
cleaned: Record<string, unknown>
/** File fields the visitor could see — their files are checked separately (attachments/fileGate). */
fileFields: ({ name: string } & FormField)[]
form: FormDoc
ok: true
}
| { field: string; ok: false; reason: 'consent' }
| { ok: false; reason: 'not_found' }
@@ -186,12 +199,22 @@ export async function validateSubmission(
const shown = new Set(visibleFields(form.fields, data))
const cleaned: Record<string, unknown> = {}
const fileFields: ({ name: string } & FormField)[] = []
for (const field of fields) {
// Hidden by a condition: not required, not stored. The consent gate never hides —
// an editor can't switch GDPR consent off with a condition.
if (!shown.has(field) && field.name !== consentFieldName) {continue}
const value = data[field.name]
// A File field carries no text value: its files arrive separately and are
// checked by the file gate. Anything sent under its key as data is tampering.
if (field.blockType === 'file') {
if (value != null && value !== '' && !(Array.isArray(value) && value.length === 0)) {
return { field: field.name, kind: 'invalid_format', ok: false, reason: 'invalid' }
}
fileFields.push(field)
continue
}
const isBlank =
value == null ||
(typeof value === 'string' && value.trim() === '') ||
@@ -235,5 +258,5 @@ export async function validateSubmission(
return { kind: 'unknown_fields', ok: false, reason: 'invalid' }
}
return { cleaned, form, ok: true }
return { cleaned, fileFields, form, ok: true }
}
+1
View File
@@ -17,6 +17,7 @@ export function resolveLabel(label: IntegrationLabel | undefined, language: stri
/** Status codes whose message has its own text — shown in the editor's language. */
export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
'bad-response': 'statusTurnstileBadResponse',
'graph-large-files': 'statusEmailGraphLargeFiles',
'graph-unavailable': 'statusEmailGraphUnavailable',
'internal-error': 'statusTurnstileInternalError',
'invalid-input-secret': 'statusTurnstileInvalidSecret',
+14
View File
@@ -12,6 +12,13 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
back: 'Back',
consent: 'Accept the privacy policy to send the form.',
error: 'The form could not be sent. Please try again in a moment.',
fileCount: 'Too many files in "{field}". Remove some: the limit is {max}.',
fileNotSent: 'We could not send the file "{file}". Choose a smaller file or another format and try again.',
fileOptional: 'You can also send the form without the file.',
fileRefused: 'The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).',
fileRemove: 'Remove {file}',
fileTooLarge: 'The file "{file}" is too large. Choose a file of up to {max} MB.',
fileType: 'The file "{file}" is in a format we do not accept. Choose one of: {types}.',
next: 'Next',
notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.',
@@ -29,6 +36,13 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
back: 'Wstecz',
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
fileCount: 'Za dużo plików w polu „{field}”. Usuń część: limit to {max}.',
fileNotSent: 'Nie udało się wysłać pliku „{file}”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.',
fileOptional: 'Możesz też wysłać formularz bez pliku.',
fileRefused: 'Plik „{file}” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik ({types}).',
fileRemove: 'Usuń {file}',
fileTooLarge: 'Plik „{file}” jest za duży. Wybierz plik do {max} MB.',
fileType: 'Plik „{file}” ma format, którego nie przyjmujemy. Wybierz jeden z: {types}.',
next: 'Dalej',
notFound: 'Ten formularz nie jest już dostępny.',
rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.',
@@ -32,6 +32,13 @@ export async function getNotificationTexts({
back: f.back || fb.back,
consent: f.consent || fb.consent,
error: f.error || fb.error,
fileCount: f.fileCount || fb.fileCount,
fileNotSent: f.fileNotSent || fb.fileNotSent,
fileOptional: f.fileOptional || fb.fileOptional,
fileRefused: f.fileRefused || fb.fileRefused,
fileRemove: f.fileRemove || fb.fileRemove,
fileTooLarge: f.fileTooLarge || fb.fileTooLarge,
fileType: f.fileType || fb.fileType,
next: f.next || fb.next,
notFound: f.notFound || fb.notFound,
rateLimited: f.rateLimited || fb.rateLimited,
@@ -1,6 +1,21 @@
import type { SubmitFormResult } from '../forms/index.js'
import type { FormNotificationTexts } from './types.js'
/**
* The texts resolveFormMessage needs. The File-field texts are optional, so an
* object written before they existed still fits (the field or general text is used).
*/
type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit<FormNotificationTexts, FileTextKey>
/** The texts of the File field problems, by result code. */
const FILE_TEXT: Partial<Record<string, FileTextKey>> = {
file_count: 'fileCount',
file_refused: 'fileRefused',
file_too_large: 'fileTooLarge',
file_type: 'fileType',
}
/**
* Maps a submitForm result to the user-facing message, interpolating {field}
* with the field's label (its key when the form has no label) for validation
@@ -12,12 +27,17 @@ import type { FormNotificationTexts } from './types.js'
* Never surfaces raw backend/exception detail — 'error' maps to a friendly
* generic message, not the thrown error's text (which could leak internals).
*/
export function resolveFormMessage(result: SubmitFormResult, texts: FormNotificationTexts): string {
export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageTexts): string {
if (result.success) {return texts.success}
switch (result.reason) {
case 'consent':
return texts.consent
case 'delivery': {
// The file could not be e-mailed: say it is the file (at its field), never the mail server's own words.
if (!texts.fileNotSent) {return texts.error}
return withoutFile(texts.fileNotSent.replace('{file}', result.file ?? ''), result.optional, texts)
}
case 'not_found':
return texts.notFound
case 'rate_limited':
@@ -27,6 +47,16 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormNotifica
case 'validation': {
// {field} → the label the visitor sees; no single field at fault → the generic error.
const field = result.label || result.field
// A problem with a file says so: which file, why, and what to do next.
const fileText = texts[FILE_TEXT[result.kind ?? ''] ?? 'fileRemove']
if (FILE_TEXT[result.kind ?? ''] && fileText) {
const message = fileText
.replace('{file}', result.file ?? '')
.replace('{max}', result.max === undefined ? '' : String(result.max))
.replace('{types}', result.types ?? '')
.replace('{field}', field ?? '')
return withoutFile(message, result.optional, texts)
}
return field ? texts.validation.replace('{field}', field) : texts.error
}
case 'error':
@@ -34,3 +64,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormNotifica
return texts.error
}
}
/** On a field that is not required, a file message ends with "…send the form without the file". */
function withoutFile(message: string, optional: boolean | undefined, texts: FormMessageTexts): string {
return optional && texts.fileOptional ? `${message} ${texts.fileOptional}` : message
}
+17
View File
@@ -10,6 +10,23 @@ export type FormNotificationTexts = {
/** Shown when a required GDPR consent checkbox was left unchecked. */
consent: string
error: string
/** File field: too many files, with {field} and {max}. */
fileCount: string
/** File field: the e-mail with the file could not be sent — with {file}; the visitor has to send it again. */
fileNotSent: string
/** File field: added to a file message when the field is not required ("…send the form without the file"). */
fileOptional: string
/**
* File field: the format is allowed but this file is not — its content does not match, it has macros, it is
* a program or an archive. With {file} and {types}.
*/
fileRefused: string
/** File field: the button that removes a selected file, with {file}. */
fileRemove: string
/** File field: a file over the limit, with {file} and {max} (MB). */
fileTooLarge: string
/** File field: a file of a type the field does not accept, with {file} and {types}. */
fileType: string
/** Step-by-step forms: "Next" button. */
next: string
notFound: string
+87
View File
@@ -0,0 +1,87 @@
/**
* A seed run that ends early must fail loudly. `payload run` starts the CLI with `void start()` and then
* `await import(script)`: when a seed script's top-level `await getPayload()` (or a later await) is left with
* nothing that keeps Node's event loop alive, Node simply exits — code 0, no output. In Coolify's Terminal
* that looks exactly like a successful run. The guard turns it into exit 1 with the reason.
*
* Dependency-free on purpose: no Payload, no Node imports — safe to import first in any seed script.
*/
type ExitListener = () => void
/** The bits of `process` the guard uses — injectable for tests. */
export type SeedExitProcess = {
exit: (code: number) => void
exitCode?: null | number | string
off: (event: 'beforeExit', listener: ExitListener) => unknown
on: (event: 'beforeExit', listener: ExitListener) => unknown
}
export type SeedExitGuardOptions = {
/** Prefix of the message. Default '[seed]'. */
label?: string
/** Where the message goes. Default stderr. */
log?: (line: string) => void
/** Default the real `process`. */
process?: SeedExitProcess
}
export type SeedExitGuard = {
/** Stops watching (the run decides its exit code itself). */
dispose: () => void
/** The seed ended: `summary()` calls it. */
finished: () => void
/** Payload is up: `createSeeder` calls it. */
initialized: () => void
readonly state: 'finished' | 'initialized' | 'waiting'
}
let active: null | SeedExitGuard = null
/** The guard of the current run, if the script started one (`createSeeder` and `summary()` report to it). */
export function activeSeedExitGuard(): null | SeedExitGuard {
return active
}
/**
* Call it first in a seed script, before `getPayload()`. Until `summary()` runs, an exit through an empty
* event loop prints "[seed] ended before Payload initialized" (or "… before the seed finished") and exits 1.
* A normal `process.exit(code)` — after the summary, on an error, or the guard's own refusal — is untouched.
*/
export function guardSeedExit(options: SeedExitGuardOptions = {}): SeedExitGuard {
const proc: SeedExitProcess = options.process ?? process
const label = options.label ?? '[seed]'
const log = options.log ?? ((line: string) => {process.stderr.write(`${line}\n`)})
let state: SeedExitGuard['state'] = 'waiting'
const onBeforeExit = () => {
if (state === 'finished') {return}
const when = state === 'waiting' ? 'before Payload initialized' : 'before the seed finished'
log(
`${label} ended ${when} — the run stopped early and nothing after that point was written. ` +
'Exit code 1. Run it again; if it repeats, check the database connection and the seed script.',
)
proc.exitCode = 1
proc.exit(1)
}
const guard: SeedExitGuard = {
dispose: () => {
proc.off('beforeExit', onBeforeExit)
if (active === guard) {active = null}
},
finished: () => {
state = 'finished'
},
initialized: () => {
if (state === 'waiting') {state = 'initialized'}
},
get state() {
return state
},
}
active?.dispose()
proc.on('beforeExit', onBeforeExit)
active = guard
return guard
}

Some files were not shown because too many files have changed in this diff Show More