Compare commits
@@ -98,8 +98,9 @@ pnpm add @payloadcms/[email protected] # 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
|
||||
`payload` 3.90.x, Payload's own tree pins a vulnerable `undici`, `dompurify`,
|
||||
`graphql-scalars`, `mongoose` (MongoDB adapter) and `happy-dom` (the last three even in the latest Payload) — add the
|
||||
five overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md) (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).
|
||||
|
||||
@@ -8,6 +8,205 @@ 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.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
|
||||
|
||||
+29
-8
@@ -220,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` |
|
||||
@@ -504,20 +505,36 @@ 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.
|
||||
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 (the plugin's `nodemailer` 10 requires it). 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`
|
||||
the project's lockfile can fix. With `payload` 3.90.x five packages are 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",
|
||||
"mongoose@>=8 <8.24.7": "~8.24.10",
|
||||
"undici@>=7 <7.30.1": "^7.30.1"
|
||||
```
|
||||
`mongoose` (MongoDB sites — every site that uses `@payloadcms/db-mongodb`): the adapter pins 8.24.1 exactly, up
|
||||
to the latest Payload (3.93.0). 8.x below 8.24.7 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. The override stays on the
|
||||
8.24 patch line (`~8.24.10`), the line Payload itself tests; the reference site seeds, builds and passes its smoke
|
||||
tests on it. `happy-dom` comes from `@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 (`^20.9.0`); 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 3.90 never imports that entry, and Lexical 0.53 itself moved to `^21.0.4`; `withDOM` HTML parsing and
|
||||
export are checked on 21.0.4. Both overrides stop matching once Payload ships a fixed version — remove them then.
|
||||
`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
|
||||
@@ -528,7 +545,9 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`,
|
||||
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
|
||||
`pnpm why undici dompurify graphql-scalars mongoose happy-dom` → only the fixed versions (mongoose 8.24.7 or
|
||||
later, happy-dom 21.0.4 or later); `pnpm exec ipal-doctor` → no `transitive-min` finding; after the mongoose
|
||||
override run `pnpm build`, open the panel and save a document; with GraphQL in use, a query that reads a
|
||||
`createdAt` (DateTime) and filters on `email` (EmailAddress) returns data.
|
||||
|
||||
---
|
||||
@@ -1036,9 +1055,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 |
|
||||
|
||||
@@ -1107,6 +1127,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 |
|
||||
|
||||
@@ -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.3 ("Example Studio", made up) that uses
|
||||
The reference site is one complete client site on ipal-kit 1.16.2 ("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:
|
||||
@@ -911,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',
|
||||
@@ -1152,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`
|
||||
@@ -1164,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'
|
||||
@@ -1184,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: 'site@example-studio.test', 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)
|
||||
```
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 |
|
||||
@@ -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 |
|
||||
|
||||
@@ -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,13 +564,13 @@ 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`). |
|
||||
|
||||
@@ -93,10 +93,14 @@ 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.
|
||||
**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.
|
||||
**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.
|
||||
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides
|
||||
from AGENT.md §4 item 12 (`"mongoose@>=8 <8.24.7": "~8.24.10"` lifts the 8.24.1 that `@payloadcms/db-mongodb` pins —
|
||||
one critical and two high advisories; `"happy-dom@<21.0.4": "^21.0.4"` fixes two high ones). `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 +108,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).
|
||||
|
||||
|
||||
@@ -82,13 +82,23 @@ 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).
|
||||
`dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides to `pnpm.overrides`, `pnpm install`, audit
|
||||
again. MongoDB sites need the `mongoose` one now: `@payloadcms/db-mongodb` pins 8.24.1 (up to Payload 3.93.0), which has
|
||||
a critical advisory (GHSA-pcrw-h46h-c93h) and four more, all fixed in 8.24.7:
|
||||
```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 the lockfile, redeploy on Coolify (the new image ships the
|
||||
fixed packages; no data or schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical (the
|
||||
`deepmerge` low has no fix yet); `pnpm why mongoose happy-dom` → 8.24.7 or later, 21.0.4 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 +108,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`,
|
||||
@@ -236,6 +246,55 @@ and the browser tab shows the same separator.
|
||||
**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.
|
||||
|
||||
## 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):
|
||||
|
||||
@@ -400,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
|
||||
@@ -418,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)
|
||||
|
||||
@@ -666,6 +666,11 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 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 |
|
||||
|
||||
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`.
|
||||
|
||||
@@ -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.
|
||||
+2
-1
@@ -79,8 +79,9 @@ 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), `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) |
|
||||
|
||||
+80
-6
@@ -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).
|
||||
|
||||
+200
-7
@@ -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`:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+18
-2
@@ -197,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 }` |
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
+6
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.15.3",
|
||||
"version": "1.16.2",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -130,6 +130,7 @@
|
||||
"typecheck": "tsc --noEmit -p . && tsc -p test"
|
||||
},
|
||||
"dependencies": {
|
||||
"busboy": "1.6.0",
|
||||
"lucide-react": "0.400.0",
|
||||
"nodemailer": "10.3.1",
|
||||
"server-only": "0.0.1",
|
||||
@@ -160,15 +161,16 @@
|
||||
"@playwright/test": "1.64.0",
|
||||
"@swc-node/register": "1.10.9",
|
||||
"@swc/cli": "0.6.0",
|
||||
"@types/busboy": "1.5.4",
|
||||
"@types/node": "22.20.5",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"copyfiles": "2.4.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"eslint": "^9.23.0",
|
||||
"eslint-config-next": "16.4.3",
|
||||
"eslint-config-next": "16.4.6",
|
||||
"graphql": "^16.8.1",
|
||||
"next": "16.4.3",
|
||||
"next": "16.4.6",
|
||||
"open": "^10.1.0",
|
||||
"payload": "3.90.2",
|
||||
"prettier": "^3.4.2",
|
||||
@@ -202,6 +204,7 @@
|
||||
"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"
|
||||
|
||||
Generated
+92
-90
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 |
|
||||
@@ -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 |
|
||||
|
||||
@@ -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,13 +564,13 @@ 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`). |
|
||||
|
||||
@@ -93,10 +93,14 @@ 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.
|
||||
**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.
|
||||
**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.
|
||||
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides
|
||||
from AGENT.md §4 item 12 (`"mongoose@>=8 <8.24.7": "~8.24.10"` lifts the 8.24.1 that `@payloadcms/db-mongodb` pins —
|
||||
one critical and two high advisories; `"happy-dom@<21.0.4": "^21.0.4"` fixes two high ones). `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 +108,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).
|
||||
|
||||
|
||||
@@ -82,13 +82,23 @@ 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).
|
||||
`dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides to `pnpm.overrides`, `pnpm install`, audit
|
||||
again. MongoDB sites need the `mongoose` one now: `@payloadcms/db-mongodb` pins 8.24.1 (up to Payload 3.93.0), which has
|
||||
a critical advisory (GHSA-pcrw-h46h-c93h) and four more, all fixed in 8.24.7:
|
||||
```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 the lockfile, redeploy on Coolify (the new image ships the
|
||||
fixed packages; no data or schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical (the
|
||||
`deepmerge` low has no fix yet); `pnpm why mongoose happy-dom` → 8.24.7 or later, 21.0.4 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 +108,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`,
|
||||
@@ -236,6 +246,55 @@ and the browser tab shows the same separator.
|
||||
**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.
|
||||
|
||||
## 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):
|
||||
|
||||
@@ -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
@@ -47,7 +47,7 @@ Write everything in this file in English.
|
||||
<!-- /starter:decisions -->
|
||||
|
||||
<!-- ipal-kit:start -->
|
||||
## ipal-kit 1.15.3 — agent guide
|
||||
## ipal-kit 1.16.2 — 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,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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
@@ -34,7 +34,7 @@
|
||||
"@payloadcms/ui": "3.90.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"graphql": "^16.8.1",
|
||||
"next": "16.4.3",
|
||||
"next": "16.4.6",
|
||||
"payload": "3.90.2",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0",
|
||||
@@ -67,6 +67,8 @@
|
||||
"@payloadcms/ui": "3.90.2",
|
||||
"dompurify@<3.4.17": "^3.4.17",
|
||||
"graphql-scalars@<2.0.1": "^2.0.1",
|
||||
"happy-dom@<21.0.4": "^21.0.4",
|
||||
"mongoose@>=8 <8.24.7": "~8.24.10",
|
||||
"undici@>=7 <7.30.1": "^7.30.1"
|
||||
}
|
||||
},
|
||||
|
||||
Generated
+98
-95
@@ -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',
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
@@ -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',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,6 +3,32 @@ 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'; why: string }[] = [
|
||||
{
|
||||
name: 'mongoose',
|
||||
major: 8,
|
||||
min: '8.24.7',
|
||||
override: '"mongoose@>=8 <8.24.7": "~8.24.10"',
|
||||
severity: 'error',
|
||||
why: 'GHSA-pcrw-h46h-c93h (critical, sanitizeFilter not applied on countDocuments) and four more; @payloadcms/db-mongodb 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 +52,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 +80,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: `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) => {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
}
|
||||
}
|
||||
@@ -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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
|
||||
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}` }
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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(', '),
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+107
-26
@@ -172,11 +172,22 @@ const formRef = (v: object): string | undefined => {
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** True when the value holds a { $page } or { $form } reference — such fields are written once refs resolve. */
|
||||
const hasRef = (v: unknown): boolean =>
|
||||
Array.isArray(v)
|
||||
? v.some(hasRef)
|
||||
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
|
||||
const pageRef = (v: object): string | undefined => {
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** The default-locale slugs of the { $page } references a value holds. */
|
||||
const pageRefsIn = (v: unknown, out = new Set<string>()): Set<string> => {
|
||||
if (Array.isArray(v)) {v.forEach((x) => pageRefsIn(x, out))}
|
||||
else if (v && typeof v === 'object') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {out.add(ref)}
|
||||
else {Object.values(v).forEach((x) => pageRefsIn(x, out))}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder {
|
||||
// Payload is up (the caller passed it in) — the run's exit guard, if any, now waits for summary()
|
||||
@@ -229,6 +240,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
const localeKeys = codes.length ? codes : [undefined]
|
||||
const counts: Record<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, 'skip (not listed)': 0, update: 0 }
|
||||
const pageIds = new Map<string, number | string>()
|
||||
/** Forms planned for creation in a dry run, by title — a later { $form } to them is not an error. */
|
||||
const plannedForms = new Set<string>()
|
||||
|
||||
log(
|
||||
`${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'} · ${only ? `only: ${only.join(', ')}` : 'all records'}\n`,
|
||||
@@ -278,11 +291,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
if (form !== undefined) {
|
||||
const id = await findId(formsCollection, { title: form })
|
||||
if (id !== undefined) {return id}
|
||||
if (lenient || dryRun) {return `(form:${form})`}
|
||||
// A dry run reports what the real run would do: a form planned earlier in this run will exist.
|
||||
if (lenient || (dryRun && plannedForms.has(form))) {return `(form:${form})`}
|
||||
throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`)
|
||||
}
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
if (typeof ref === 'string') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
let id = pageIds.get(ref)
|
||||
if (id === undefined) {
|
||||
id = await findId(pagesCollection, { slug: ref })
|
||||
@@ -299,6 +313,34 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The first-pass value of a record being created: references to records that exist now become their ids,
|
||||
* so a required field (a layout whose block links to a page) is written complete. A { $page } to a page
|
||||
* planned in the same call and not created yet (`forward`) becomes null and is collected; pass 2 writes it.
|
||||
* Any other unknown target throws — nothing is written for that record.
|
||||
*/
|
||||
const resolveForCreate = async (v: unknown, forward: Set<string>, planned: Set<string>): Promise<unknown> => {
|
||||
if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveForCreate(x, forward, planned)))}
|
||||
if (!v || typeof v !== 'object') {return v}
|
||||
if (formRef(v) !== undefined) {return resolveRefs(v)}
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
const known = pageIds.get(ref) ?? (await findId(pagesCollection, { slug: ref }))
|
||||
if (known !== undefined) {
|
||||
pageIds.set(ref, known)
|
||||
return known
|
||||
}
|
||||
if (planned.has(ref)) {
|
||||
forward.add(ref)
|
||||
return null
|
||||
}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, x] of Object.entries(v)) {out[k] = await resolveForCreate(x, forward, planned)}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Per-locale seed values (refs resolved) — what the hash describes. */
|
||||
const perLocale = (data: unknown) => Object.fromEntries(localeKeys.map((l) => [l ?? '-', localize(data, l, undefined, codes)]))
|
||||
|
||||
@@ -325,6 +367,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
|
||||
// Plan: one status per record, decided before anything is written.
|
||||
const plan: Planned[] = []
|
||||
const plannedHere = new Set(trackPages ? items.map((i) => i.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
for (const item of items) {
|
||||
const p: Planned = { ...item }
|
||||
plan.push(p)
|
||||
@@ -332,8 +375,14 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
p.id = await findId(collection, item.key)
|
||||
const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined
|
||||
if (p.id === undefined) {
|
||||
// Every { $page } must exist already or be planned in this call — otherwise nothing is written (dry run too).
|
||||
for (const ref of pageRefsIn(item.data)) {
|
||||
if (plannedHere.has(ref) || pageIds.has(ref) || (await findId(pagesCollection, { slug: ref })) !== undefined) {continue}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
p.action = 'create'
|
||||
if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)}
|
||||
if (dryRun && collection === formsCollection && typeof item.key.title === 'string') {plannedForms.add(item.key.title)}
|
||||
continue
|
||||
}
|
||||
if (trackPages && slug) {pageIds.set(slug, p.id)}
|
||||
@@ -352,27 +401,59 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 1: create missing records without fields that reference other pages (they may not exist yet).
|
||||
// Pass 1: create missing records complete — references to existing records resolved. A forward { $page }
|
||||
// (a page created later in this call) is null for now; a record whose required field needs it is retried
|
||||
// once that page exists. Required references in a cycle, or to a page that never appears, are an error
|
||||
// and nothing is written for those records.
|
||||
if (!dryRun) {
|
||||
for (const p of plan) {
|
||||
if (p.action !== 'create') {continue}
|
||||
try {
|
||||
const first = Object.fromEntries(Object.entries(p.data).filter(([, v]) => !hasRef(v)))
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {pageIds.set(slug, p.id)}
|
||||
} catch (e) {
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
const waiting = plan.filter((p) => p.action === 'create' && !p.result)
|
||||
const planned = new Set(trackPages ? waiting.map((p) => p.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
const blocked = new Map<Planned, { error: string; forward: Set<string> }>()
|
||||
let progress = true
|
||||
while (waiting.length && progress) {
|
||||
progress = false
|
||||
for (const p of [...waiting]) {
|
||||
const forward = new Set<string>()
|
||||
try {
|
||||
const first = (await resolveForCreate(p.data, forward, planned)) as Record<string, unknown>
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {
|
||||
pageIds.set(slug, p.id)
|
||||
planned.delete(slug)
|
||||
}
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
blocked.delete(p)
|
||||
progress = true
|
||||
} catch (e) {
|
||||
if (forward.size) {
|
||||
// Valid only once the pages it links to exist — try again after the others.
|
||||
blocked.set(p, { error: (e as Error).message, forward })
|
||||
continue
|
||||
}
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const p of waiting) {
|
||||
const why = blocked.get(p)
|
||||
const targets = [...(why?.forward ?? [])].map((s) => `"${s}"`).join(', ')
|
||||
p.result = {
|
||||
label: p.label,
|
||||
note: `required references to pages not created yet (${targets}) — a cycle of required links; make one link optional or seed that page first${why ? ` (${why.error})` : ''}`,
|
||||
status: 'error',
|
||||
}
|
||||
p.action = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: full content in every locale (dry run: resolve refs to report broken ones).
|
||||
|
||||
+87
-10
@@ -25,19 +25,81 @@ export function isLocalizedValue(v: unknown, codes: string[]): v is Record<strin
|
||||
return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
|
||||
}
|
||||
|
||||
/** The schema of the value being localized: its fields, or its block types (`blocks` field rows). */
|
||||
export type SeedSchema = { blocks?: Record<string, readonly SeedField[]>; fields?: readonly SeedField[] }
|
||||
|
||||
/** The slice of a Payload field config the seed helper reads. */
|
||||
export type SeedField = {
|
||||
blocks?: readonly ({ fields: readonly SeedField[]; slug: string } | string)[]
|
||||
fields?: readonly SeedField[]
|
||||
localized?: boolean
|
||||
name?: string
|
||||
tabs?: readonly { fields: readonly SeedField[]; name?: string }[]
|
||||
type: string
|
||||
}
|
||||
|
||||
/** Named fields at one level: rows, collapsibles and unnamed tabs add no path segment. */
|
||||
function namedFields(fields: readonly SeedField[] = []): Map<string, SeedField> {
|
||||
const out = new Map<string, SeedField>()
|
||||
for (const f of fields) {
|
||||
if (f.type === 'tabs') {
|
||||
for (const tab of f.tabs ?? []) {
|
||||
if (tab.name) {out.set(tab.name, { name: tab.name, type: 'group', fields: tab.fields })}
|
||||
else {for (const [k, v] of namedFields(tab.fields)) {out.set(k, v)}}
|
||||
}
|
||||
} else if (f.name) {out.set(f.name, f)}
|
||||
else if (f.fields) {for (const [k, v] of namedFields(f.fields)) {out.set(k, v)}}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The schema below a field: a group's or array's fields, or a blocks field's block types. */
|
||||
function schemaOf(field: SeedField | undefined, blockConfigs?: (slug: string) => readonly SeedField[] | undefined): SeedSchema | undefined {
|
||||
if (!field) {return undefined}
|
||||
if (field.type === 'blocks') {
|
||||
const blocks: Record<string, readonly SeedField[]> = {}
|
||||
for (const b of field.blocks ?? []) {
|
||||
if (typeof b === 'string') {
|
||||
const fields = blockConfigs?.(b)
|
||||
if (fields) {blocks[b] = fields}
|
||||
} else {blocks[b.slug] = b.fields}
|
||||
}
|
||||
return { blocks }
|
||||
}
|
||||
return field.fields ? { fields: field.fields } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The value for one locale. Arrays (array fields, blocks) keep the ids of the
|
||||
* rows already stored at the same index — new ids would wipe the other
|
||||
* locales' texts. A block row keeps its id only when its blockType matches.
|
||||
* The value for one locale. Rows of arrays and blocks keep the ids of the rows
|
||||
* already stored at the same index — new ids would wipe the other locales' texts.
|
||||
* A block row keeps its id only when its blockType matches. A whole localized
|
||||
* value (`fields: { pl: [...], en: [...] }`) is localized again after its locale
|
||||
* is picked, so its rows keep the stored ids too.
|
||||
*
|
||||
* With `schema` (writeLocales passes the collection's or global's fields), a field
|
||||
* that is itself localized (`localized: true` array, blocks or group) gets no
|
||||
* stored ids: its rows belong to one locale and are never shared.
|
||||
* undefined = leave the field out.
|
||||
*/
|
||||
export function localize(value: unknown, locale: string | undefined, existing: unknown, codes: string[]): unknown {
|
||||
if (isLocalizedValue(value, codes)) {return locale ? value[locale] : undefined}
|
||||
export function localize(
|
||||
value: unknown,
|
||||
locale: string | undefined,
|
||||
existing: unknown,
|
||||
codes: string[],
|
||||
schema?: SeedSchema,
|
||||
blockConfigs?: (slug: string) => readonly SeedField[] | undefined,
|
||||
): unknown {
|
||||
if (isLocalizedValue(value, codes)) {
|
||||
const picked = locale ? value[locale] : undefined
|
||||
return picked === undefined ? undefined : localize(picked, locale, existing, codes, schema, blockConfigs)
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const rows = Array.isArray(existing) ? (existing as unknown[]) : []
|
||||
return value.map((item, i) => {
|
||||
const row = rows[i] as Record<string, unknown> | undefined
|
||||
const out = localize(item, locale, row, codes)
|
||||
const type = isPlainObject(item) && typeof item.blockType === 'string' ? item.blockType : undefined
|
||||
const rowSchema = schema?.blocks ? (type && schema.blocks[type] ? { fields: schema.blocks[type] } : undefined) : schema
|
||||
const out = localize(item, locale, row, codes, rowSchema, blockConfigs)
|
||||
if (!isPlainObject(out) || !row?.id) {return out ?? null}
|
||||
if (out.blockType !== undefined && row.blockType !== undefined && out.blockType !== row.blockType) {return out}
|
||||
return { ...out, id: row.id }
|
||||
@@ -45,9 +107,12 @@ export function localize(value: unknown, locale: string | undefined, existing: u
|
||||
}
|
||||
if (isPlainObject(value)) {
|
||||
const ex = isPlainObject(existing) ? existing : {}
|
||||
const fields = schema?.fields ? namedFields(schema.fields) : undefined
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
const r = localize(v, locale, ex[k], codes)
|
||||
const field = fields?.get(k)
|
||||
// A localized field's stored rows belong to another locale — never reuse their ids.
|
||||
const r = localize(v, locale, field?.localized ? undefined : ex[k], codes, schemaOf(field, blockConfigs), blockConfigs)
|
||||
if (r !== undefined) {out[k] = r}
|
||||
}
|
||||
return out
|
||||
@@ -132,6 +197,16 @@ export function editedSinceSeed({
|
||||
|
||||
export type SeedTarget = { collection: string; id: number | string } | { global: string }
|
||||
|
||||
/** The fields of a seed target (collection or global) and the config's shared blocks, for localize. */
|
||||
export function seedSchemaOf(payload: BasePayload, target: SeedTarget): { blockConfigs: (slug: string) => readonly SeedField[] | undefined; schema?: SeedSchema } {
|
||||
const config = payload.config as { blocks?: { fields: SeedField[]; slug: string }[]; collections?: { fields: SeedField[]; slug: string }[]; globals?: { fields: SeedField[]; slug: string }[] }
|
||||
const owner = 'global' in target ? config.globals?.find((g) => g.slug === target.global) : config.collections?.find((c) => c.slug === target.collection)
|
||||
return {
|
||||
blockConfigs: (slug) => config.blocks?.find((b) => b.slug === slug)?.fields,
|
||||
...(owner ? { schema: { fields: owner.fields } } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export type WriteLocalesOptions = {
|
||||
/** Passed to every write — see docs/seeding.md § Context flags. */
|
||||
context?: Record<string, unknown>
|
||||
@@ -161,20 +236,21 @@ export async function writeLocales(
|
||||
{ context = {}, draft = false }: WriteLocalesOptions = {},
|
||||
): Promise<void> {
|
||||
const { codes, defaultLocale } = localesOf(payload)
|
||||
const { blockConfigs, schema } = seedSchemaOf(payload, target)
|
||||
const local = (locale: string | undefined, rows: unknown) => localize(data, locale, rows, codes, schema, blockConfigs)
|
||||
const write = (value: unknown, locale: string | undefined) => {
|
||||
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
|
||||
return 'global' in target
|
||||
? payload.updateGlobal({ slug: target.global as never, context, data: value as never, depth: 0, ...loc })
|
||||
: payload.update({ id: target.id, collection: target.collection as never, context, data: value as never, depth: 0, ...loc })
|
||||
}
|
||||
await write(localize(data, defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft), codes), defaultLocale)
|
||||
await write(local(defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft)), defaultLocale)
|
||||
const others = codes.filter((c) => c !== defaultLocale)
|
||||
if (!others.length) {return}
|
||||
const rows = await readSeedTarget(payload, target, defaultLocale, draft)
|
||||
for (const locale of others) {await write(localize(data, locale, rows, codes), locale)}
|
||||
for (const locale of others) {await write(local(locale, rows), locale)}
|
||||
}
|
||||
|
||||
/** True when a value has content (non-empty text, a number, true, or a nested one). */
|
||||
/** Field types whose stored value is a choice, not text an editor wrote. */
|
||||
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
|
||||
|
||||
@@ -189,6 +265,7 @@ export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; t
|
||||
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
|
||||
}
|
||||
|
||||
/** True when a value has content (non-empty text, a number, true, or a nested one). */
|
||||
export function hasContent(v: unknown): boolean {
|
||||
if (typeof v === 'string') {return v.trim() !== ''}
|
||||
if (typeof v === 'number' || v === true) {return true}
|
||||
|
||||
@@ -29,6 +29,12 @@ function ensureScript(): void {
|
||||
export type TurnstileProps = {
|
||||
/** Called with the token once solved, or null on expiry/error. */
|
||||
onToken: (token: null | string) => void
|
||||
/**
|
||||
* Change this value to make the widget issue a NEW token (a token is
|
||||
* single-use: after a submission the server refused, the next one needs a
|
||||
* fresh one). useTurnstile's `reset()` does it for the provider's widget.
|
||||
*/
|
||||
resetSignal?: number
|
||||
/**
|
||||
* Public Turnstile site key. The client project reads it server-side from
|
||||
* SiteIntegrations (turnstileSiteKey) and passes it in — the widget is a pure
|
||||
@@ -54,7 +60,7 @@ export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page'
|
||||
* The script is injected directly (no next/script dependency) so the widget
|
||||
* stays framework-agnostic.
|
||||
*/
|
||||
export function Turnstile({ onToken, siteKey, theme = 'page' }: TurnstileProps) {
|
||||
export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }: TurnstileProps) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const widgetId = useRef<null | string>(null)
|
||||
const pageTheme = useTheme().theme
|
||||
@@ -95,6 +101,14 @@ export function Turnstile({ onToken, siteKey, theme = 'page' }: TurnstileProps)
|
||||
return () => clearInterval(interval)
|
||||
}, [siteKey, widgetTheme, onToken])
|
||||
|
||||
// reset(): run the challenge again — the old token was spent on the refused request.
|
||||
const lastReset = useRef(resetSignal)
|
||||
useEffect(() => {
|
||||
if (lastReset.current === resetSignal) {return}
|
||||
lastReset.current = resetSignal
|
||||
if (widgetId.current) {window.turnstile?.reset(widgetId.current)}
|
||||
}, [resetSignal])
|
||||
|
||||
if (!siteKey) {return null}
|
||||
|
||||
return <div ref={ref} />
|
||||
|
||||
@@ -7,6 +7,10 @@ import type { TurnstileTheme } from './Turnstile.js'
|
||||
import { Turnstile } from './Turnstile.js'
|
||||
|
||||
type TurnstileContextValue = {
|
||||
/** Clears the token and makes the widget issue a new one. */
|
||||
reset: () => void
|
||||
/** Bumped by `reset` — the widget re-runs its challenge when it changes. */
|
||||
resetSignal: number
|
||||
setToken: (t: null | string) => void
|
||||
/** Public site key from the provider (read server-side, passed once). */
|
||||
siteKey: null | string
|
||||
@@ -39,8 +43,13 @@ export function TurnstileProvider({
|
||||
siteKey: null | string
|
||||
}) {
|
||||
const [token, setToken] = useState<null | string>(null)
|
||||
const [resetSignal, setResetSignal] = useState(0)
|
||||
const reset = useCallback(() => {
|
||||
setToken(null)
|
||||
setResetSignal((n) => n + 1)
|
||||
}, [])
|
||||
return (
|
||||
<TurnstileContext value={{ setToken, siteKey, token }}>
|
||||
<TurnstileContext value={{ reset, resetSignal, setToken, siteKey, token }}>
|
||||
{children}
|
||||
</TurnstileContext>
|
||||
)
|
||||
@@ -53,7 +62,7 @@ export function TurnstileProvider({
|
||||
* const { token, TurnstileWidget, reset } = useTurnstile()
|
||||
* // in JSX: <TurnstileWidget />
|
||||
* // at submit: submitForm({ ..., turnstileToken: token })
|
||||
* // after submit: reset() // clear for the next submission
|
||||
* // after a refused submit: reset() // the token is spent — the widget issues a new one
|
||||
*/
|
||||
export function useTurnstile(): {
|
||||
/** True when Turnstile is configured (site key present). */
|
||||
@@ -69,7 +78,7 @@ export function useTurnstile(): {
|
||||
return useTurnstileFrom(ctx)
|
||||
}
|
||||
|
||||
const NO_PROVIDER: TurnstileContextValue = { setToken: () => {}, siteKey: null, token: null }
|
||||
const NO_PROVIDER: TurnstileContextValue = { reset: () => {}, resetSignal: 0, setToken: () => {}, siteKey: null, token: null }
|
||||
|
||||
/**
|
||||
* useTurnstile without the provider requirement: outside <TurnstileProvider>
|
||||
@@ -81,17 +90,22 @@ export function useOptionalTurnstile(): ReturnType<typeof useTurnstile> {
|
||||
}
|
||||
|
||||
function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurnstile> {
|
||||
const { setToken, siteKey, token } = ctx
|
||||
|
||||
const reset = useCallback(() => setToken(null), [setToken])
|
||||
const { reset, siteKey, token } = ctx
|
||||
|
||||
const TurnstileWidget = useCallback(
|
||||
(props?: { theme?: TurnstileTheme }) => {
|
||||
if (!siteKey) {return null}
|
||||
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
|
||||
return <ProvidedTurnstile theme={props?.theme} />
|
||||
},
|
||||
[siteKey, setToken],
|
||||
[siteKey],
|
||||
)
|
||||
|
||||
return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
|
||||
}
|
||||
|
||||
/** The provider's widget: reads the key and the reset signal from the context, so `reset()` reaches it without a remount. */
|
||||
function ProvidedTurnstile({ theme }: { theme?: TurnstileTheme }) {
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx?.siteKey) {return null}
|
||||
return <Turnstile onToken={ctx.setToken} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
|
||||
}
|
||||
|
||||
+41
-2
@@ -31,11 +31,11 @@ function project(files: Record<string, object | string>): string {
|
||||
return root
|
||||
}
|
||||
|
||||
const pkgJson = (extra: object = {}) => ({ name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '^1.14.6', next: '16.4.3', sharp: '0.35.5' }, engines: { node: '>=22 <23' }, packageManager: '[email protected]', ...extra })
|
||||
const pkgJson = (extra: object = {}) => ({ name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '^1.14.6', next: '16.4.6', sharp: '0.35.5' }, engines: { node: '>=22 <23' }, packageManager: '[email protected]', ...extra })
|
||||
const installed = (name: string, version: string) => ({ [`node_modules/${name}/package.json`]: { name, version } })
|
||||
const base = () => ({
|
||||
...installed('@intecion/ipal-kit', '1.14.6'),
|
||||
...installed('next', '16.4.3'),
|
||||
...installed('next', '16.4.6'),
|
||||
...installed('sharp', '0.35.5'),
|
||||
'.nvmrc': '22\n',
|
||||
'package.json': pkgJson(),
|
||||
@@ -120,6 +120,45 @@ describe('versions', () => {
|
||||
'pnpm-pinned:info',
|
||||
])
|
||||
})
|
||||
test('next-min: 16.4.1–16.4.4 is an error (GHSA-mfr8-8qww-v76h), 16.4.5 passes, and the rule can be silenced', async () => {
|
||||
const at = (version: string) => project({ ...base(), ...installed('next', version), ...installed('eslint-config-next', version) })
|
||||
const old = await doctor(at('16.4.3'), ['next-min'])
|
||||
expect(rules(old)).toEqual(['next-min:error'])
|
||||
expect(old.findings[0].message).toContain('GHSA-mfr8-8qww-v76h')
|
||||
expect(old.findings[0].fix).toBe('pnpm add [email protected] [email protected]')
|
||||
expect(rules(await doctor(at('16.4.4'), ['next-min']))).toEqual(['next-min:error'])
|
||||
expect((await doctor(at('16.4.0'), ['next-min'])).findings[0].message).toContain('RCE and DoS')
|
||||
expect(rules(await doctor(at('16.4.5'), ['next-min']))).toEqual([])
|
||||
expect(rules(await doctor(at('16.5.0'), ['next-min']))).toEqual([])
|
||||
const silenced = await doctor(at('16.4.3'), ['next-min'], { config: { rules: { 'next-min': { off: true, reason: 'upgrade booked' } } } })
|
||||
expect(silenced.summary).toMatchObject({ error: 0, silenced: 1 })
|
||||
})
|
||||
test('transitive-min: mongoose 8 below 8.24.7 (error) and happy-dom below 21.0.4 (warning), read from the lockfile', async () => {
|
||||
const lock = (mongoose: string, happyDom: string) =>
|
||||
`lockfileVersion: '9.0'\n\noverrides:\n [email protected]: 8.24.1\n\npackages:\n\n happy-dom@${happyDom}:\n resolution: {integrity: x}\n\n [email protected]:\n resolution: {integrity: x}\n\n mongoose@${mongoose}:\n resolution: {integrity: x}\n\nsnapshots:\n\n mongoose@${mongoose}:\n dependencies:\n mongodb: 6.20.0\n`
|
||||
const at = (mongoose: string, happyDom: string) => project({ ...base(), 'pnpm-lock.yaml': lock(mongoose, happyDom) })
|
||||
const old = await doctor(at('8.24.1', '20.14.6'), ['transitive-min'])
|
||||
expect(rules(old)).toEqual(['transitive-min:error', 'transitive-min:warning'])
|
||||
expect(old.findings[0].message).toContain('mongoose 8.24.1 < 8.24.7')
|
||||
expect(old.findings[0].message).toContain('GHSA-pcrw-h46h-c93h')
|
||||
expect(old.findings[0].fix).toContain('"mongoose@>=8 <8.24.7": "~8.24.10"')
|
||||
expect(old.findings[1].message).toContain('happy-dom 20.14.6 < 21.0.4')
|
||||
expect(old.findings[1].fix).toContain('"happy-dom@<21.0.4": "^21.0.4"')
|
||||
// 8.24.3 fixes only the critical one
|
||||
expect(rules(await doctor(at('8.24.6', '21.0.3'), ['transitive-min']))).toEqual(['transitive-min:error', 'transitive-min:warning'])
|
||||
expect(rules(await doctor(at('8.24.7', '21.0.4'), ['transitive-min']))).toEqual([])
|
||||
expect(rules(await doctor(at('8.24.10', '21.1.0'), ['transitive-min']))).toEqual([])
|
||||
// another major line (Payload 4 uses mongoose 9) is not compared with the 8.x minimum
|
||||
expect(rules(await doctor(at('9.11.4', '21.0.4'), ['transitive-min']))).toEqual([])
|
||||
// no MongoDB adapter, no lexical: nothing to report
|
||||
expect(rules(await doctor(project(base()), ['transitive-min']))).toEqual([])
|
||||
const silenced = await doctor(at('8.24.1', '20.14.6'), ['transitive-min'], { config: { rules: { 'transitive-min': { off: true, reason: 'Payload upgrade booked' } } } })
|
||||
expect(silenced.summary).toMatchObject({ error: 0, silenced: 2, warning: 0 })
|
||||
})
|
||||
test('transitive-min: without a pnpm lockfile it reads node_modules/.pnpm', async () => {
|
||||
const root = project({ ...base(), 'node_modules/.pnpm/[email protected][email protected]/node_modules/mongoose/package.json': { name: 'mongoose', version: '8.24.1' } })
|
||||
expect(rules(await doctor(root, ['transitive-min']))).toEqual(['transitive-min:error'])
|
||||
})
|
||||
test('file: / link: specs are not compared', async () => {
|
||||
expect(rules(await doctor(project({ ...base(), 'package.json': pkgJson({ dependencies: { '@intecion/ipal-kit': 'file:..' } }) }), ['plugin-installed']))).toEqual([])
|
||||
})
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
* Attachments through both e-mail paths. SMTP: the real nodemailer against a
|
||||
* small local SMTP server. Microsoft Graph: a mocked Graph (no tenant, no
|
||||
* credentials) that records every call — the inline path, the upload session,
|
||||
* and the clean-up of the mailbox copy.
|
||||
*/
|
||||
import type { BasePayload, PayloadEmailAdapter } from 'payload'
|
||||
|
||||
import { createServer, type Server } from 'node:net'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { clearGraphTokenCache, graphAdapter, graphLargeAttachmentSupport } from '../src/modules/email/graphAdapter.js'
|
||||
import { GRAPH_INLINE_MAX_BYTES } from '../src/modules/email/graphAttachments.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MB = 1024 * 1024
|
||||
const bytes = (size: number) => Buffer.from(Array.from({ length: size }, (_, i) => i % 251))
|
||||
const attachment = (size: number, filename = 'cv.pdf') => ({ content: bytes(size), contentDisposition: 'attachment' as const, contentType: 'application/pdf', filename })
|
||||
|
||||
// ---- SMTP -------------------------------------------------------------------------------------
|
||||
|
||||
type Received = { data: string; to: string[] }
|
||||
|
||||
/** `refuseOver`: answer DATA with 552 when the message is larger (a server with a size limit). */
|
||||
function startSmtp(received: Received[], limits: { refuseOver?: number } = {}): Promise<{ port: number; server: Server }> {
|
||||
const server = createServer((socket) => {
|
||||
const mail: Received = { data: '', to: [] }
|
||||
let inData = false
|
||||
let buffer = ''
|
||||
const reply = (line: string) => socket.write(`${line}\r\n`)
|
||||
reply('220 localhost ESMTP test')
|
||||
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
|
||||
if (limits.refuseOver && mail.data.length > limits.refuseOver) {
|
||||
reply('552 5.3.4 Message size exceeds fixed limit')
|
||||
} else {
|
||||
received.push(mail)
|
||||
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) => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address()
|
||||
resolve({ port: typeof address === 'object' && address ? address.port : 0, server })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const build = (adapter: PayloadEmailAdapter, payload: BasePayload) => adapter({ payload } as Parameters<PayloadEmailAdapter>[0])
|
||||
|
||||
/** The base64 body of the first attachment in a raw message, decoded. */
|
||||
function attachedBytes(raw: string): Buffer {
|
||||
const start = raw.indexOf('Content-Disposition: attachment')
|
||||
const body = raw.slice(raw.indexOf('\n\n', start) + 2)
|
||||
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
|
||||
}
|
||||
|
||||
// ---- a mocked Microsoft Graph ------------------------------------------------------------------
|
||||
|
||||
type Call = { body?: unknown; headers: Record<string, string>; method: string; url: string }
|
||||
|
||||
const jwt = (roles: string[]) => `x.${Buffer.from(JSON.stringify({ roles })).toString('base64url')}.y`
|
||||
|
||||
function mockGraph({ fail, roles = ['Mail.Send', 'Mail.ReadWrite'], sentAfterLooks = 1 }: { fail?: (call: Call) => number | undefined; roles?: string[]; sentAfterLooks?: number } = {}) {
|
||||
const calls: Call[] = []
|
||||
const uploaded: Buffer[] = []
|
||||
let looks = 0
|
||||
const fetchImpl = (async (input: string | URL, init: RequestInit = {}) => {
|
||||
const url = String(input)
|
||||
const method = init.method ?? 'GET'
|
||||
const headers = (init.headers ?? {}) as Record<string, string>
|
||||
if (url.includes('login.microsoftonline.com')) {return Response.json({ access_token: jwt(roles), expires_in: 3600 })}
|
||||
const call: Call = { body: typeof init.body === 'string' ? (JSON.parse(init.body) as unknown) : init.body, headers, method, url }
|
||||
calls.push(call)
|
||||
const failure = fail?.(call)
|
||||
if (failure) {return new Response('{"error":{"code":"Failed"}}', { status: failure })}
|
||||
if (url.endsWith('/sendMail')) {return new Response(null, { status: 202 })}
|
||||
if (method === 'POST' && url.endsWith('/messages')) {return Response.json({ id: 'draft-1' }, { status: 201 })}
|
||||
if (url.endsWith('/attachments/createUploadSession')) {return Response.json({ uploadUrl: 'https://outlook.office.com/upload/session-1' }, { status: 201 })}
|
||||
if (url.endsWith('/attachments')) {return Response.json({ id: 'att' }, { status: 201 })}
|
||||
if (method === 'PUT' && url.startsWith('https://outlook.office.com/upload/')) {
|
||||
uploaded.push(Buffer.from(init.body as Uint8Array))
|
||||
const [, end, total] = /bytes \d+-(\d+)\/(\d+)/.exec(headers['Content-Range']) ?? []
|
||||
return Response.json({}, { status: Number(end) + 1 === Number(total) ? 201 : 200 })
|
||||
}
|
||||
if (url.endsWith('/send')) {return new Response(null, { status: 202 })}
|
||||
if (method === 'GET' && url.includes('/messages/draft-1')) {return Response.json({ isDraft: ++looks < sentAfterLooks })}
|
||||
if (url.endsWith('/permanentDelete')) {return new Response(null, { status: 204 })}
|
||||
if (method === 'DELETE') {return new Response(null, { status: 204 })}
|
||||
return new Response('unexpected', { status: 500 })
|
||||
}) as unknown as typeof fetch
|
||||
const names = () => calls.map((c) => `${c.method} ${c.url.replace('https://graph.microsoft.com/v1.0/users/forms%40example.com', '').replace(/\?.*$/, '')}`)
|
||||
return { calls, fetchImpl, names, uploaded }
|
||||
}
|
||||
|
||||
const graphEnv = () => {
|
||||
vi.stubEnv('GRAPH_TENANT_ID', 'tenant')
|
||||
vi.stubEnv('GRAPH_CLIENT_ID', 'client')
|
||||
vi.stubEnv('GRAPH_CLIENT_SECRET', 'secret')
|
||||
vi.stubEnv('GRAPH_SENDER', '[email protected]')
|
||||
}
|
||||
|
||||
describe('attachments', () => {
|
||||
const received: Received[] = []
|
||||
const limited: Received[] = []
|
||||
let port = 0
|
||||
let limitedPort = 0
|
||||
let servers: Server[] = []
|
||||
|
||||
beforeAll(async () => {
|
||||
const open = await startSmtp(received)
|
||||
const small = await startSmtp(limited, { refuseOver: 200_000 })
|
||||
port = open.port
|
||||
limitedPort = small.port
|
||||
servers = [open.server, small.server]
|
||||
})
|
||||
afterAll(async () => {
|
||||
await Promise.all(servers.map((s) => new Promise((resolve) => s.close(resolve))))
|
||||
})
|
||||
afterEach(() => {
|
||||
received.length = 0
|
||||
limited.length = 0
|
||||
clearGraphTokenCache()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
const smtp = (p = port) => ({ smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'pw', smtpPort: p, smtpUser: 'mailer' })
|
||||
const message = (size: number) => ({ attachments: [attachment(size)], html: '<p>New application</p>', subject: 'Application', to: '[email protected]' })
|
||||
|
||||
describe('SMTP', () => {
|
||||
test('a 10 MB file goes out as an attachment and arrives byte for byte', async () => {
|
||||
const { payload } = fakePayload({ integrations: smtp() })
|
||||
const result = await build(panelSmtpAdapter(), payload).sendEmail(message(10 * MB))
|
||||
expect(result).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0].data).toContain('filename=cv.pdf')
|
||||
expect(received[0].data.length).toBeGreaterThan(13.3 * MB) // base64: about 13.7 MB on the wire
|
||||
expect(Buffer.compare(attachedBytes(received[0].data), bytes(10 * MB))).toBe(0)
|
||||
expect(await (build(panelSmtpAdapter(), payload) as { attachmentLimit?: unknown }).attachmentLimit).toBeUndefined()
|
||||
}, 60_000)
|
||||
|
||||
test('a server that refuses the size: reported as not sent, with the server\'s reason', async () => {
|
||||
const { payload } = fakePayload({ integrations: smtp(limitedPort) })
|
||||
const result = (await build(panelSmtpAdapter(), payload).sendEmail(message(MB))) as { detail?: string; sent: boolean }
|
||||
expect(result.sent).toBe(false)
|
||||
expect(result.detail).toContain('552')
|
||||
expect(limited).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Microsoft Graph (mocked)', () => {
|
||||
test('under 3 MB: one sendMail call with the file inline, nothing kept in the mailbox', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload()
|
||||
const result = await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(2 * MB))
|
||||
expect(result).toEqual({ sent: true })
|
||||
expect(graph.names()).toEqual(['POST /sendMail'])
|
||||
const body = graph.calls[0].body as { message: { attachments: { contentBytes: string; name: string }[] }; saveToSentItems: boolean }
|
||||
expect(body.saveToSentItems).toBe(false)
|
||||
expect(body.message.attachments[0].name).toBe('cv.pdf')
|
||||
expect(Buffer.compare(Buffer.from(body.message.attachments[0].contentBytes, 'base64'), bytes(2 * MB))).toBe(0)
|
||||
})
|
||||
|
||||
test('10 MB: draft → upload session in order → send → the mailbox copy is deleted', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ sentAfterLooks: 2 })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(10 * MB))) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
expect(await result.cleanup).toBe('deleted')
|
||||
|
||||
expect(graph.names()).toEqual([
|
||||
'POST /messages',
|
||||
'POST /messages/draft-1/attachments/createUploadSession',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'POST /messages/draft-1/send',
|
||||
'GET /messages/draft-1', // still a draft: not deleted yet (deleting now could cancel the send)
|
||||
'GET /messages/draft-1', // sent
|
||||
'POST /messages/draft-1/permanentDelete',
|
||||
])
|
||||
// The draft is addressed and labelled like any message, and asks for an id that survives the move to Sent Items.
|
||||
expect(graph.calls[0].body).toMatchObject({ subject: 'Application', toRecipients: [{ emailAddress: { address: '[email protected]' } }] })
|
||||
// every call on the draft carries the immutable-id preference (the pre-authenticated upload URL takes no headers of ours)
|
||||
const onGraph = graph.calls.filter((c) => c.url.startsWith('https://graph.microsoft.com/'))
|
||||
expect(onGraph.length).toBeGreaterThanOrEqual(6)
|
||||
expect(onGraph.every((c) => c.headers.Prefer === 'IdType="ImmutableId"')).toBe(true)
|
||||
expect((graph.calls[1].body as { AttachmentItem: unknown }).AttachmentItem).toMatchObject({ name: 'cv.pdf', attachmentType: 'file', size: 10 * MB })
|
||||
// Every byte, in order, in pieces under 4 MB, without the bearer token on the pre-authenticated URL.
|
||||
expect(Buffer.compare(Buffer.concat(graph.uploaded), bytes(10 * MB))).toBe(0)
|
||||
expect(graph.uploaded.every((part) => part.length < 4 * MB)).toBe(true)
|
||||
const puts = graph.calls.filter((c) => c.method === 'PUT')
|
||||
expect(puts.every((c) => !('Authorization' in c.headers))).toBe(true)
|
||||
expect(puts.map((c) => c.headers['Content-Range'])[0]).toBe(`bytes 0-${10 * 320 * 1024 - 1}/${10 * MB}`)
|
||||
})
|
||||
|
||||
test('several files: small ones are added directly, large ones through a session', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail({
|
||||
...message(MB),
|
||||
attachments: [attachment(MB, 'letter.pdf'), attachment(4 * MB, 'cv.pdf')],
|
||||
})) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
await result.cleanup
|
||||
expect(graph.names().slice(0, 6)).toEqual([
|
||||
'POST /messages',
|
||||
'POST /messages/draft-1/attachments',
|
||||
'POST /messages/draft-1/attachments/createUploadSession',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'PUT https://outlook.office.com/upload/session-1',
|
||||
'POST /messages/draft-1/send',
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
['the upload fails', (c: Call) => (c.method === 'PUT' ? 503 : undefined)],
|
||||
['the send fails', (c: Call) => (c.url.endsWith('/send') ? 500 : undefined)],
|
||||
['the upload session cannot be created', (c: Call) => (c.url.endsWith('createUploadSession') ? 400 : undefined)],
|
||||
])('%s: not sent, and the draft with the file is deleted from the mailbox', async (_name, fail) => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-error', sent: false })
|
||||
expect(graph.names().at(-1)).toBe('POST /messages/draft-1/permanentDelete')
|
||||
expect(graph.names()).not.toContain('GET /messages/draft-1')
|
||||
})
|
||||
|
||||
test('permanentDelete unavailable: falls back to a plain delete', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') ? 404 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise<string> }
|
||||
expect(await result.cleanup).toBe('deleted')
|
||||
expect(graph.names().slice(-2)).toEqual(['POST /messages/draft-1/permanentDelete', 'DELETE /messages/draft-1'])
|
||||
})
|
||||
|
||||
test('the sent copy cannot be removed: the send still counts, and the log says to delete it by hand', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') || c.method === 'DELETE' ? 500 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise<string>; sent: boolean }
|
||||
expect(result.sent).toBe(true)
|
||||
expect(await result.cleanup).toBe('left')
|
||||
expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('delete it by hand'))
|
||||
})
|
||||
|
||||
test('without Mail.ReadWrite: a clear refusal that names the permission, and nothing is created', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload()
|
||||
const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload)
|
||||
const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-permission', sent: false })
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('Mail.ReadWrite'))
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await graphLargeAttachmentSupport({ fetchImpl: graph.fetchImpl })).toBe('no-permission')
|
||||
expect(await (adapter as unknown as { attachmentLimit: () => Promise<null | number> }).attachmentLimit()).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
})
|
||||
|
||||
test('Graph answers 403 to the draft (a token that hides its roles): the same refusal', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ fail: (c) => (c.method === 'POST' && c.url.endsWith('/messages') ? 403 : undefined) })
|
||||
const { payload } = fakePayload()
|
||||
const result = (await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; detail?: string }
|
||||
expect(result.code).toBe('graph-permission')
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
})
|
||||
|
||||
test('largeAttachments: false — Graph keeps to small attachments', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload()
|
||||
const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl, largeAttachments: false }), payload)
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ code: 'graph-large-off', sent: false })
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('mailAdapter: Graph selected in the panel', () => {
|
||||
const limitOf = (adapter: unknown) => (adapter as { attachmentLimit: () => Promise<null | number> }).attachmentLimit()
|
||||
|
||||
test('permission present: large files go over Graph, no ceiling', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(graph.names()).toContain('POST /messages/draft-1/send')
|
||||
expect(received).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('permission missing, SMTP filled in: the large message goes over SMTP; small ones stay on Graph', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
expect(Buffer.compare(attachedBytes(received[0].data), bytes(5 * MB))).toBe(0)
|
||||
expect(graph.calls).toEqual([])
|
||||
expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true })
|
||||
expect(graph.names()).toEqual(['POST /sendMail'])
|
||||
expect(received).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('permission missing, no SMTP: the ceiling is just under 3 MB, and a larger send fails clearly', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph({ roles: ['Mail.Send'] })
|
||||
const { payload } = fakePayload({ integrations: { emailTransport: 'graph' } })
|
||||
const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload)
|
||||
expect(await limitOf(adapter)).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean }
|
||||
expect(result).toMatchObject({ code: 'graph-permission', sent: false })
|
||||
expect(result.detail).toContain('Mail.ReadWrite')
|
||||
})
|
||||
|
||||
test('switched off by the project (largeAttachments: false): SMTP carries large files when filled in', async () => {
|
||||
graphEnv()
|
||||
const graph = mockGraph()
|
||||
const withSmtp = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } }).payload)
|
||||
expect(await limitOf(withSmtp)).toBeNull()
|
||||
expect(await withSmtp.sendEmail(message(5 * MB))).toMatchObject({ sent: true })
|
||||
expect(received).toHaveLength(1)
|
||||
const without = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { emailTransport: 'graph' } }).payload)
|
||||
expect(await limitOf(without)).toBe(GRAPH_INLINE_MAX_BYTES - 1)
|
||||
})
|
||||
|
||||
test('SMTP selected: no ceiling from the plugin', async () => {
|
||||
const adapter = build(mailAdapter(), fakePayload({ integrations: smtp() }).payload)
|
||||
expect(await limitOf(adapter)).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload, PayloadEmailAdapter } from 'payload'
|
||||
import { createServer, type Server } from 'node:net'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { clearGraphTokenCache } from '../src/modules/email/graphAdapter.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js'
|
||||
import { sendEmail } from '../src/modules/email/sendEmail.js'
|
||||
@@ -90,6 +91,7 @@ describe('e-mail transports (nodemailer 10)', () => {
|
||||
|
||||
afterEach(() => {
|
||||
received.length = 0
|
||||
clearGraphTokenCache()
|
||||
vi.unstubAllEnvs()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,988 @@
|
||||
/**
|
||||
* Form files end to end through a REAL Payload (SQLite in memory): the form is
|
||||
* built in the "panel" (Local API), the browser's multipart request goes to the
|
||||
* real endpoint handler as a stream, and the e-mails land in a recording adapter.
|
||||
*
|
||||
* The groups follow the seven acceptance tests of the client request
|
||||
* (vanstevpl-web, 2026-11-13), re-read for "files are e-mailed, never stored".
|
||||
*/
|
||||
import type { Payload, PayloadEmailAdapter, PayloadRequest } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { readdirSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { FormFileScanInput } from '../src/modules/forms/attachments/config.js'
|
||||
|
||||
import { getFormAttachments } from '../src/modules/forms/attachments/config.js'
|
||||
import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MB = 1024 * 1024
|
||||
const mediaDir = path.join(os.tmpdir(), 'ipal-test-form-files-media')
|
||||
|
||||
// ---- sample files -------------------------------------------------------------------------
|
||||
|
||||
const utf16 = (text: string) => Buffer.from(text, 'utf16le')
|
||||
const pad = (head: Buffer, size: number) => Buffer.concat([head, Buffer.alloc(Math.max(0, size - head.length), 0x20)])
|
||||
|
||||
/** A stored (uncompressed) ZIP with the given entries — enough for the container checks. */
|
||||
function zip(entries: Record<string, string>): Buffer {
|
||||
const locals: Buffer[] = []
|
||||
const central: Buffer[] = []
|
||||
let offset = 0
|
||||
for (const [name, content] of Object.entries(entries)) {
|
||||
const data = Buffer.from(content)
|
||||
const file = Buffer.from(name)
|
||||
const crc = zlib.crc32(data)
|
||||
const local = Buffer.alloc(30)
|
||||
local.writeUInt32LE(0x04034b50, 0)
|
||||
local.writeUInt16LE(20, 4)
|
||||
local.writeUInt32LE(crc, 14)
|
||||
local.writeUInt32LE(data.length, 18)
|
||||
local.writeUInt32LE(data.length, 22)
|
||||
local.writeUInt16LE(file.length, 26)
|
||||
const header = Buffer.alloc(46)
|
||||
header.writeUInt32LE(0x02014b50, 0)
|
||||
header.writeUInt16LE(20, 4)
|
||||
header.writeUInt16LE(20, 6)
|
||||
header.writeUInt32LE(crc, 16)
|
||||
header.writeUInt32LE(data.length, 20)
|
||||
header.writeUInt32LE(data.length, 24)
|
||||
header.writeUInt16LE(file.length, 28)
|
||||
header.writeUInt32LE(offset, 42)
|
||||
locals.push(local, file, data)
|
||||
central.push(header, file)
|
||||
offset += 30 + file.length + data.length
|
||||
}
|
||||
const directory = Buffer.concat(central)
|
||||
const end = Buffer.alloc(22)
|
||||
end.writeUInt32LE(0x06054b50, 0)
|
||||
end.writeUInt16LE(Object.keys(entries).length, 8)
|
||||
end.writeUInt16LE(Object.keys(entries).length, 10)
|
||||
end.writeUInt32LE(directory.length, 12)
|
||||
end.writeUInt32LE(offset, 16)
|
||||
return Buffer.concat([...locals, directory, end])
|
||||
}
|
||||
|
||||
const OLE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])
|
||||
const PDF = pad(Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), 4096)
|
||||
const DOC = pad(Buffer.concat([OLE, utf16('WordDocument')]), 2048)
|
||||
const DOC_MACRO = pad(Buffer.concat([OLE, utf16('WordDocument'), utf16('Macros'), utf16('_VBA_PROJECT')]), 2048)
|
||||
const DOCX = zip({ '[Content_Types].xml': '<Types/>', 'word/document.xml': '<w:document/>' })
|
||||
const DOCX_MACRO = zip({ '[Content_Types].xml': '<Types/>', 'word/document.xml': '<w:document/>', 'word/vbaProject.bin': 'x' })
|
||||
const EXE = pad(Buffer.from('MZ\x90\x00\x03'), 1024)
|
||||
const ARCHIVE = zip({ 'readme.txt': 'hello' })
|
||||
|
||||
// ---- the site ------------------------------------------------------------------------------
|
||||
|
||||
type Mail = { attachments?: { content: Buffer; contentType: string; filename: string }[]; html: string; subject: string; to: string }
|
||||
const mails: Mail[] = []
|
||||
let mailMode: 'ok' | 'refuse' | 'throw' = 'ok'
|
||||
const recordingMail: PayloadEmailAdapter = () => ({
|
||||
name: 'test-mail',
|
||||
defaultFromAddress: '[email protected]',
|
||||
defaultFromName: 'Acme',
|
||||
sendEmail: (message) => {
|
||||
const mail = message as unknown as Mail
|
||||
mails.push(mail)
|
||||
// Only the message that carries a file is refused — like a server with a size limit.
|
||||
if (mail.attachments?.length && mailMode === 'refuse') {return Promise.resolve({ detail: '552 5.3.4 Message size exceeds fixed limit', error: 'The e-mail was not sent.', sent: false })}
|
||||
if (mail.attachments?.length && mailMode === 'throw') {return Promise.reject(new Error('connect ECONNREFUSED'))}
|
||||
return Promise.resolve({ messageId: 'ok' })
|
||||
},
|
||||
})
|
||||
|
||||
const scanned: FormFileScanInput[] = []
|
||||
let scanVerdict = true
|
||||
|
||||
const text = (value: string) => ({
|
||||
root: {
|
||||
type: 'root',
|
||||
children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }],
|
||||
direction: null,
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
},
|
||||
})
|
||||
|
||||
let payload: Payload
|
||||
let formId: string
|
||||
let ipCounter = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({
|
||||
config: buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: mediaDir } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
email: recordingMail,
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {
|
||||
attachments: {
|
||||
maxConcurrent: 0,
|
||||
maxSizeMB: 1,
|
||||
scan: (file) => {
|
||||
scanned.push(file)
|
||||
return { ok: scanVerdict }
|
||||
},
|
||||
},
|
||||
},
|
||||
i18n: {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
{ code: 'de', label: 'Deutsch' },
|
||||
{ code: 'nl', label: 'Nederlands' },
|
||||
],
|
||||
},
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'form-files-test-secret',
|
||||
telemetry: false,
|
||||
}),
|
||||
})
|
||||
|
||||
// Built in the default language first, then the English texts on the same rows.
|
||||
const base = {
|
||||
confirmationMessage: text('Thank you'),
|
||||
emails: [
|
||||
{ emailFrom: '[email protected]', emailTo: '[email protected]', message: text('New application from {{name}}: {{attachment}}'), subject: 'Application' },
|
||||
{ emailFrom: '[email protected]', emailTo: '{{email}}', message: text('We got your application, {{name}}.'), subject: 'Thank you' },
|
||||
],
|
||||
fields: [
|
||||
{ name: 'name', blockType: 'text', label: 'Name', required: true },
|
||||
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
|
||||
{ name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], blockType: 'file', help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Załącznik (opcjonalnie)', maxFiles: 1, maxSizeMB: 1 },
|
||||
{ name: 'consent', blockType: 'checkbox', label: 'Consent' },
|
||||
],
|
||||
title: 'Careers',
|
||||
}
|
||||
const form = (await payload.create({ collection: 'forms' as never, data: base as never, locale: 'pl' })) as unknown as {
|
||||
emails: Record<string, unknown>[]
|
||||
fields: Record<string, unknown>[]
|
||||
id: number | string
|
||||
}
|
||||
formId = String(form.id)
|
||||
await payload.update({
|
||||
id: formId,
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: base.confirmationMessage,
|
||||
emails: form.emails.map((email, i) => ({ ...email, message: base.emails[i].message, subject: base.emails[i].subject })),
|
||||
fields: form.fields.map(({ resolved: _resolved, ...f }) => (f.name === 'attachment' ? { ...f, help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Attachment (optional)' } : f)),
|
||||
} as never,
|
||||
locale: 'en',
|
||||
})
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
mails.length = 0
|
||||
scanned.length = 0
|
||||
mailMode = 'ok'
|
||||
scanVerdict = true
|
||||
vi.unstubAllGlobals()
|
||||
delete process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
|
||||
delete process.env.TURNSTILE_SECRET_KEY
|
||||
})
|
||||
|
||||
type Upload = { data: Buffer; field?: string; name: string }
|
||||
type Post = {
|
||||
attempt?: string
|
||||
files?: Upload[]
|
||||
form?: string
|
||||
headers?: Record<string, string>
|
||||
ip?: string
|
||||
locale?: string
|
||||
token?: string
|
||||
values?: Record<string, unknown>
|
||||
}
|
||||
|
||||
const answers = { name: 'Jan Kowalski', consent: true, email: '[email protected]' }
|
||||
|
||||
/** The browser's request: answers first, files last — to the real handler, body as a stream. */
|
||||
async function post({ attempt, files = [], form = formId, headers = {}, ip, locale = 'en', token, values = answers }: Post = {}) {
|
||||
const body = new FormData()
|
||||
body.append('_form', form)
|
||||
body.append('_locale', locale)
|
||||
if (attempt) {body.append('_attempt', attempt)}
|
||||
if (token) {body.append('_token', token)}
|
||||
body.append('_values', JSON.stringify(values))
|
||||
for (const file of files) {body.append(file.field ?? 'attachment', new File([new Uint8Array(file.data)], file.name))}
|
||||
const request = new Request(`http://localhost/api/ipal/forms/submit?locale=${locale}`, {
|
||||
body,
|
||||
headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': ip ?? `10.9.${Math.floor(++ipCounter / 250)}.${ipCounter % 250}`, ...headers },
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
return { body: (await response.json()) as { field?: string; message: string; reason?: string; success: boolean }, status: response.status }
|
||||
}
|
||||
|
||||
type Submission = {
|
||||
attemptKey?: string
|
||||
filesDelivery?: string
|
||||
filesDeliveryNote?: string
|
||||
id: number | string
|
||||
submissionData: { field: string; value: string }[]
|
||||
submissionFiles?: { field: string; name: string; size: number; type: string }[]
|
||||
}
|
||||
const submissions = async () =>
|
||||
(await payload.find({ collection: 'form-submissions' as never, depth: 0, limit: 200, sort: 'createdAt' })).docs as unknown as Submission[]
|
||||
const count = async () => (await payload.count({ collection: 'form-submissions' as never })).totalDocs
|
||||
const withFile = () => mails.filter((m) => m.attachments?.length)
|
||||
|
||||
describe('1 · a submission without the optional file works as before', () => {
|
||||
test('through the server action path: stored, both e-mails sent, no file data anywhere', async () => {
|
||||
const before = await count()
|
||||
const result = await submitForm({ data: answers, formId, ip: '10.8.0.1', locale: 'en', payload })
|
||||
expect(result.success).toBe(true)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails.map((m) => m.to).sort()).toEqual(['[email protected]', '[email protected]'])
|
||||
expect(withFile()).toEqual([])
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(stored.submissionData.map((d) => d.field)).toEqual(['name', 'email', 'consent'])
|
||||
expect(stored.filesDelivery ?? null).toBeNull()
|
||||
expect(stored.submissionFiles ?? []).toEqual([])
|
||||
})
|
||||
|
||||
test('through the endpoint without a file part: the same outcome', async () => {
|
||||
const before = await count()
|
||||
const { body, status } = await post()
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails).toHaveLength(2)
|
||||
expect(withFile()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('2 · each allowed format: one submission, the file in the staff e-mail only', () => {
|
||||
test.each([
|
||||
['CV Jan Kowalski.pdf', PDF, 'pdf', 'application/pdf'],
|
||||
['cv.DOC', DOC, 'doc', 'application/msword'],
|
||||
['Życiorys (2026).docx', DOCX, 'docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
|
||||
])('%s', async (name, data, type, mime) => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name, data }] })
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before + 1)
|
||||
|
||||
// The staff e-mail carries the file, byte for byte; the confirmation to the visitor does not.
|
||||
const staff = mails.filter((m) => m.to === '[email protected]')
|
||||
expect(staff).toHaveLength(1)
|
||||
expect(staff[0].attachments).toHaveLength(1)
|
||||
const attachment = staff[0].attachments![0]
|
||||
expect(Buffer.compare(attachment.content, data)).toBe(0)
|
||||
expect(attachment.contentType).toBe(mime)
|
||||
expect(attachment.filename).toBe(name.replace(/\.[^.]+$/, `.${type}`)) // the visitor's name (also with Polish letters), the detected extension
|
||||
expect(staff[0].html).toContain(attachment.filename) // {{attachment}} → the readable name
|
||||
expect(staff[0].html).toContain('not checked for viruses')
|
||||
const customer = mails.filter((m) => m.to === '[email protected]')
|
||||
expect(customer).toHaveLength(1)
|
||||
expect(customer[0].attachments).toBeUndefined()
|
||||
expect(customer[0].html).not.toContain('viruses')
|
||||
|
||||
// The submission keeps metadata only.
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(stored.submissionFiles).toMatchObject([{ name: attachment.filename, type, field: 'attachment', size: data.length }])
|
||||
expect(stored.filesDelivery).toBe('sent')
|
||||
expect(stored.submissionData.find((d) => d.field === 'attachment')?.value).toMatch(new RegExp(`\\.${type} \\(\\d+ (?:B|KB)\\)$`))
|
||||
expect(JSON.stringify(stored)).not.toContain(data.toString('base64').slice(0, 40))
|
||||
expect(scanned.map((s) => s.type)).toEqual([type]) // the optional scan hook saw exactly this file
|
||||
})
|
||||
})
|
||||
|
||||
describe('3 · refused files leave no submission and send no e-mail', () => {
|
||||
// Every refusal is answered AT the File field, says it is the file, why, and what to do next.
|
||||
const TYPES = 'PDF, DOC, DOCX'
|
||||
const wrongFormat = (name: string) => `The file "${name}" is in a format we do not accept. Choose one of: ${TYPES}. You can also send the form without the file.`
|
||||
const notAcceptable = (name: string) =>
|
||||
`The file "${name}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (${TYPES}). You can also send the form without the file.`
|
||||
const refused = async (files: Upload[], expected: string, extra: Post = {}) => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files, ...extra })
|
||||
expect(body.success).toBe(false)
|
||||
expect(status).toBe(422)
|
||||
expect(body.message).toBe(expected)
|
||||
expect(body).toMatchObject({ field: 'attachment', reason: 'validation' })
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
}
|
||||
|
||||
test('oversized: stopped while reading', async () => {
|
||||
await refused(
|
||||
[{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 200_000) }],
|
||||
'The file "big.pdf" is too large. Choose a file of up to 1 MB. You can also send the form without the file.',
|
||||
)
|
||||
expect(scanned).toEqual([])
|
||||
})
|
||||
|
||||
test('mismatched: a program named .pdf, a PDF named .docx, an empty file', async () => {
|
||||
await refused([{ name: 'cv.pdf', data: EXE }], notAcceptable('cv.pdf'))
|
||||
await refused([{ name: 'cv.docx', data: PDF }], notAcceptable('cv.docx'))
|
||||
await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], notAcceptable('cv.pdf'))
|
||||
})
|
||||
|
||||
test('another format: the message names the formats the field takes', async () => {
|
||||
await refused([{ name: 'photo.png', data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }], wrongFormat('photo.png'))
|
||||
await refused([{ name: 'notes.txt', data: Buffer.from('hello') }], wrongFormat('notes.txt'))
|
||||
await refused([{ name: 'cv', data: PDF }], wrongFormat('cv'))
|
||||
})
|
||||
|
||||
test('refused files: program, double extension, archive, macro-enabled Office — the message says the file was refused', async () => {
|
||||
await refused([{ name: 'cv.exe', data: EXE }], notAcceptable('cv.exe'))
|
||||
await refused([{ name: 'cv.pdf.exe', data: EXE }], notAcceptable('cv.pdf.exe'))
|
||||
await refused([{ name: 'cv.exe.pdf', data: PDF }], notAcceptable('cv.exe.pdf'))
|
||||
await refused([{ name: 'cv.pdf.docx', data: DOCX }], notAcceptable('cv.pdf.docx'))
|
||||
await refused([{ name: 'cv.zip', data: ARCHIVE }], notAcceptable('cv.zip'))
|
||||
await refused([{ name: 'cv.docm', data: DOCX_MACRO }], notAcceptable('cv.docm'))
|
||||
})
|
||||
|
||||
test('the right container with macros inside: DOCX with a macro project, DOC with a macro storage', async () => {
|
||||
await refused([{ name: 'cv.docx', data: DOCX_MACRO }], notAcceptable('cv.docx'))
|
||||
await refused([{ name: 'cv.doc', data: DOC_MACRO }], notAcceptable('cv.doc'))
|
||||
await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file
|
||||
})
|
||||
|
||||
test('extra files: more than the field allows, a file under a key that is no File field', async () => {
|
||||
await refused(
|
||||
[{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }],
|
||||
'Too many files in "Attachment (optional)". Remove some: the limit is 1. You can also send the form without the file.',
|
||||
)
|
||||
const before = await count()
|
||||
const { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: '[email protected]' } })
|
||||
expect(body.success).toBe(false)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
|
||||
test('direct calls that skip the form: text under the File key, a stringified File, a media id', async () => {
|
||||
const before = await count()
|
||||
for (const attachment of ['[object File]', '65f0c0ffee', { id: 1 }]) {
|
||||
const result = await submitForm({ data: { ...answers, attachment }, formId, ip: '10.8.0.9', maxPerMinute: 0, payload })
|
||||
expect(result).toMatchObject({ field: 'attachment', reason: 'validation', success: false })
|
||||
}
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('the antivirus hook can refuse a file that passed everything else', async () => {
|
||||
scanVerdict = false
|
||||
await refused([{ name: 'cv.pdf', data: PDF }], notAcceptable('cv.pdf'))
|
||||
expect(scanned).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('a body that declares itself too large is refused unread', async () => {
|
||||
const before = await count()
|
||||
const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', {
|
||||
body: 'x',
|
||||
headers: { 'content-length': String(50 * MB), 'content-type': 'multipart/form-data; boundary=x', 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.1.1' },
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
expect(response.status).toBe(413)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('4 · no gate can be bypassed by attaching a file', () => {
|
||||
const blocked = async (extra: Post, status: number, reason: string | undefined) => {
|
||||
const before = await count()
|
||||
const result = await post({ files: [{ name: 'cv.pdf', data: PDF }], ...extra })
|
||||
expect(result.status).toBe(status)
|
||||
expect(result.body.reason).toBe(reason)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
expect(scanned).toEqual([]) // the file was never taken in
|
||||
return result
|
||||
}
|
||||
|
||||
test('missing consent', async () => {
|
||||
const { body } = await blocked({ values: { ...answers, consent: false } }, 422, 'consent')
|
||||
expect(body.message).toMatch(/privacy policy/)
|
||||
})
|
||||
|
||||
test('a required field left empty', async () => {
|
||||
await blocked({ values: { consent: true, email: '[email protected]' } }, 422, 'validation')
|
||||
})
|
||||
|
||||
test('Turnstile configured: no token, and a token Cloudflare rejects', async () => {
|
||||
process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY = 'site-key'
|
||||
process.env.TURNSTILE_SECRET_KEY = 'secret-key'
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ 'error-codes': ['invalid-input-response'], success: false })))
|
||||
await blocked({}, 403, 'turnstile')
|
||||
await blocked({ token: 'forged' }, 403, 'turnstile')
|
||||
})
|
||||
|
||||
test('a tripped honeypot: a fake success, nothing stored, nothing sent', async () => {
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }], values: { ...answers, company_url: 'http://spam.example' } })
|
||||
expect({ status, success: body.success }).toEqual({ status: 200, success: true })
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
expect(scanned).toEqual([])
|
||||
})
|
||||
|
||||
test('rate limit: the sixth request in a minute from one address is refused before its body is read', async () => {
|
||||
const ip = '10.8.2.2'
|
||||
for (let i = 0; i < 5; i++) {await post({ ip, values: { ...answers, consent: false } })}
|
||||
await blocked({ ip }, 429, 'rate_limited')
|
||||
})
|
||||
|
||||
test('another site cannot post to the endpoint; REST cannot create a submission', async () => {
|
||||
await blocked({ headers: { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' } }, 403, 'error')
|
||||
await expect(
|
||||
payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [] } as never, overrideAccess: false }),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('a file sent before the answers is not accepted', async () => {
|
||||
const before = await count()
|
||||
const body = new FormData()
|
||||
body.append('attachment', new File([new Uint8Array(PDF)], 'cv.pdf'))
|
||||
body.append('_form', formId)
|
||||
body.append('_values', JSON.stringify(answers))
|
||||
const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', { body, headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.2.9' }, method: 'POST' })
|
||||
const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest)
|
||||
expect(response.status).toBeGreaterThanOrEqual(400)
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('5 · nothing is stored, nothing can be downloaded', () => {
|
||||
test('no upload collection, no file on disk, no route that serves a file', async () => {
|
||||
await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(withFile()).toHaveLength(1)
|
||||
|
||||
// The only upload collection is the project's own Media, and it is empty.
|
||||
const uploads = payload.config.collections.filter((c) => c.upload).map((c) => c.slug)
|
||||
expect(uploads).toEqual(['media'])
|
||||
expect((await payload.count({ collection: 'media' as never })).totalDocs).toBe(0)
|
||||
let onDisk: string[] = []
|
||||
try {
|
||||
onDisk = readdirSync(mediaDir)
|
||||
} catch {
|
||||
/* the directory was never created */
|
||||
}
|
||||
expect(onDisk).toEqual([])
|
||||
|
||||
// The submission has no upload relation — form-builder's own upload storage stays off.
|
||||
const fields = payload.collections['form-submissions' as never].config.fields.map((f) => ('name' in f ? f.name : ''))
|
||||
expect(fields).not.toContain('submissionUploads')
|
||||
// One endpoint, POST only.
|
||||
const mine = (payload.config.endpoints ?? []).filter((e) => e.path.includes('forms'))
|
||||
expect(mine.map((e) => `${e.method} ${e.path}`)).toEqual(['post /ipal/forms/submit'])
|
||||
})
|
||||
|
||||
test('the option is opt-in: without it the config has no File block, no endpoint, no extra fields', async () => {
|
||||
const plain = await buildTestConfig({
|
||||
collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })],
|
||||
secret: 'x',
|
||||
})
|
||||
const forms = plain.collections.find((c) => c.slug === 'forms')!
|
||||
const blocks = (forms.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { slug: string }[] }).blocks.map((b) => b.slug)
|
||||
expect(blocks).not.toContain('file')
|
||||
expect((plain.endpoints ?? []).some((e) => e.path.includes('forms/submit'))).toBe(false)
|
||||
const submissionFields = plain.collections.find((c) => c.slug === 'form-submissions')!.fields.map((f) => ('name' in f ? f.name : ''))
|
||||
expect(submissionFields.filter((name) => /file|attempt/i.test(name))).toEqual([])
|
||||
expect((plain.custom as { ipal?: { formAttachments?: unknown } } | undefined)?.ipal?.formAttachments).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('6 · failed send, retry, repeated request', () => {
|
||||
test('the mail server refuses the message: the visitor is told, staff get a notice, the attempt is marked', async () => {
|
||||
mailMode = 'refuse'
|
||||
const before = await count()
|
||||
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(status).toBe(502)
|
||||
// The visitor is told it is the FILE, at the File field, and what to do — never the mail server's words.
|
||||
expect(body).toEqual({
|
||||
field: 'attachment',
|
||||
message: 'We could not send the file "cv.pdf". Choose a smaller file or another format and try again. You can also send the form without the file.',
|
||||
reason: 'delivery',
|
||||
success: false,
|
||||
})
|
||||
expect(JSON.stringify(body)).not.toMatch(/552|size exceeds|smtp|ECONN/i)
|
||||
|
||||
const stored = (await submissions()).at(-1)!
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(stored.filesDelivery).toBe('failed')
|
||||
expect(stored.filesDeliveryNote).toContain('552')
|
||||
expect(stored.submissionFiles).toHaveLength(1)
|
||||
|
||||
// One attempt with the file, then the notice without it. No confirmation to the visitor.
|
||||
expect(mails.map((m) => [m.to, m.attachments?.length ?? 0])).toEqual([['[email protected]', 1], ['[email protected]', 0]])
|
||||
expect(mails[1].html).toContain('could not be sent')
|
||||
expect(mails[1].html).not.toContain('viruses')
|
||||
|
||||
// The retry is a new attempt and goes through once.
|
||||
mails.length = 0
|
||||
mailMode = 'ok'
|
||||
const retry = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(retry.body.success).toBe(true)
|
||||
expect(await count()).toBe(before + 2)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
expect(mails.filter((m) => m.to === '[email protected]')).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('an adapter that throws is a failed send too', async () => {
|
||||
mailMode = 'throw'
|
||||
const { body } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(body).toMatchObject({ field: 'attachment', reason: 'delivery' })
|
||||
expect(body.message).not.toMatch(/ECONNREFUSED/)
|
||||
expect((await submissions()).at(-1)!.filesDelivery).toBe('failed')
|
||||
})
|
||||
|
||||
test('the same attempt key again: the first answer, no second submission, no second e-mail', async () => {
|
||||
const before = await count()
|
||||
const attempt = 'attempt-0123456789abcdef'
|
||||
const first = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(first.body.success).toBe(true)
|
||||
const sent = mails.length
|
||||
const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(again.body).toEqual(first.body)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(mails).toHaveLength(sent)
|
||||
expect(scanned).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('two identical requests at the same moment: one submission, one e-mail with the file', async () => {
|
||||
const before = await count()
|
||||
const attempt = 'attempt-concurrent-000001'
|
||||
const [a, b] = await Promise.all([
|
||||
post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }),
|
||||
post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }),
|
||||
])
|
||||
expect(a.body.success && b.body.success).toBe(true)
|
||||
expect(await count()).toBe(before + 1)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('a failed attempt repeated with its key stays failed and sends nothing more', async () => {
|
||||
mailMode = 'refuse'
|
||||
const attempt = 'attempt-failed-0000000001'
|
||||
await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
const before = await count()
|
||||
mails.length = 0
|
||||
mailMode = 'ok'
|
||||
const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
|
||||
expect(again.body).toMatchObject({ field: 'attachment', reason: 'delivery' })
|
||||
expect(again.body.message).toContain('We could not send the file "cv.pdf".')
|
||||
expect(await count()).toBe(before)
|
||||
expect(mails).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('7 · languages, the panel, limits', () => {
|
||||
test('messages follow the page language: Polish and English defaults, German and Dutch from the panel', async () => {
|
||||
await payload.updateGlobal({
|
||||
slug: 'notifications' as never,
|
||||
data: { form: { fileOptional: 'Sie können das Formular auch ohne Datei senden.', fileTooLarge: 'Die Datei „{file}“ ist zu groß. Wählen Sie eine Datei bis {max} MB.' } } as never,
|
||||
locale: 'de',
|
||||
})
|
||||
await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileOptional: 'U kunt het formulier ook zonder bestand versturen.', fileTooLarge: 'Het bestand "{file}" is te groot. Kies een bestand tot {max} MB.' } } as never, locale: 'nl' })
|
||||
const big = [{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10) }]
|
||||
expect((await post({ files: big, locale: 'pl' })).body.message).toBe('Plik „big.pdf” jest za duży. Wybierz plik do 1 MB. Możesz też wysłać formularz bez pliku.')
|
||||
expect((await post({ files: big, locale: 'en' })).body.message).toBe('The file "big.pdf" is too large. Choose a file of up to 1 MB. You can also send the form without the file.')
|
||||
expect((await post({ files: big, locale: 'de' })).body.message).toBe('Die Datei „big.pdf“ ist zu groß. Wählen Sie eine Datei bis 1 MB. Sie können das Formular auch ohne Datei senden.')
|
||||
expect((await post({ files: big, locale: 'nl' })).body.message).toBe('Het bestand "big.pdf" is te groot. Kies een bestand tot 1 MB. U kunt het formulier ook zonder bestand versturen.')
|
||||
|
||||
// Every file message in Polish too; the field's label comes from the panel in the page language.
|
||||
const pl = async (files: Upload[]) => (await post({ files, locale: 'pl' })).body.message
|
||||
expect(await pl([{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }])).toBe('Za dużo plików w polu „Załącznik (opcjonalnie)”. Usuń część: limit to 1. Możesz też wysłać formularz bez pliku.')
|
||||
expect(await pl([{ name: 'zdjęcie.png', data: Buffer.alloc(32, 1) }])).toBe('Plik „zdjęcie.png” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOC, DOCX. Możesz też wysłać formularz bez pliku.')
|
||||
expect(await pl([{ name: 'cv.pdf', data: EXE }])).toBe(
|
||||
'Plik „cv.pdf” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOC, DOCX). Możesz też wysłać formularz bez pliku.',
|
||||
)
|
||||
mailMode = 'refuse'
|
||||
expect(await pl([{ name: 'cv.pdf', data: PDF }])).toBe('Nie udało się wysłać pliku „cv.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie. Możesz też wysłać formularz bez pliku.')
|
||||
mailMode = 'ok'
|
||||
|
||||
// A failure that is not about the file keeps its own message — no file wording.
|
||||
const consent = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { ...answers, consent: false } })).body
|
||||
expect(consent).toMatchObject({ field: 'consent', reason: 'consent' })
|
||||
expect(consent.message).not.toMatch(/file/i)
|
||||
const missing = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { consent: true, email: '[email protected]' } })).body
|
||||
expect(missing).toMatchObject({ field: 'name', message: 'Check the field "Name".' })
|
||||
})
|
||||
|
||||
test('the form the browser gets carries the limits that really apply, and where to post', async () => {
|
||||
const form = (await payload.findByID({ id: formId, collection: 'forms' as never, depth: 0, locale: 'en' })) as unknown as {
|
||||
fields: { blockType: string; help?: string; resolved?: Record<string, unknown> }[]
|
||||
fileSubmitUrl?: string
|
||||
}
|
||||
const field = form.fields.find((f) => f.blockType === 'file')!
|
||||
expect(field.help).toBe('PDF, DOC or DOCX, up to 1 MB')
|
||||
expect(field.resolved).toMatchObject({ extensions: ['pdf', 'doc', 'docx'], maxFiles: 1, maxSizeMB: 1, typeLabels: 'PDF, DOC, DOCX' })
|
||||
expect(String(field.resolved?.accept)).toContain('.pdf')
|
||||
expect(form.fileSubmitUrl).toBe('/api/ipal/forms/submit')
|
||||
})
|
||||
|
||||
test('the panel: the File block, its caps, and a form with a File field needs a fixed-recipient e-mail', async () => {
|
||||
const options = getFormAttachments(payload)!
|
||||
expect(options).toMatchObject({ maxFiles: 3, maxSizeMB: 1, maxTotalMB: 1 })
|
||||
const block = (payload.collections['forms' as never].config.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { fields: unknown[]; slug: string }[] }).blocks.find((b) => b.slug === 'file')!
|
||||
expect(JSON.stringify(block.fields)).toContain('Dozwolone typy plików')
|
||||
|
||||
const fields = [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV' }]
|
||||
const confirmationMessage = text('ok')
|
||||
const refusal = await payload
|
||||
.create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: '{{email}}', message: text('x'), subject: 'x' }], fields, title: 'No staff e-mail' } as never })
|
||||
.then(() => null, (err: { data?: { errors?: { message: string; path: string }[] } }) => err.data?.errors?.[0])
|
||||
expect(refusal).toMatchObject({ path: 'emails' })
|
||||
expect(refusal?.message).toMatch(/fixed recipient|stałym adresem/)
|
||||
await expect(payload.create({ collection: 'forms' as never, data: { confirmationMessage, fields, title: 'No e-mail at all' } as never })).rejects.toThrow()
|
||||
// A size over the cap is refused by the field itself.
|
||||
await expect(
|
||||
payload.create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: '[email protected]', message: text('x'), subject: 'x' }], fields: [{ ...fields[0], maxSizeMB: 50 }], title: 'Too big' } as never }),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('a required File field: the submission without a file is refused', async () => {
|
||||
const required = await payload.create({
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: text('ok'),
|
||||
emails: [{ emailFrom: '[email protected]', emailTo: '[email protected]', message: text('x'), subject: 'x' }],
|
||||
fields: [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV', required: true }],
|
||||
title: 'Required file',
|
||||
} as never,
|
||||
locale: 'en',
|
||||
})
|
||||
const before = await count()
|
||||
const none = await post({ form: String(required.id), values: {} })
|
||||
expect(none.body).toMatchObject({ field: 'cv', reason: 'validation', success: false })
|
||||
expect(await submitForm({ data: {}, formId: String(required.id), maxPerMinute: 0, payload })).toMatchObject({ field: 'cv', kind: 'required' })
|
||||
expect(await count()).toBe(before)
|
||||
// A required field: the same messages, without "send the form without the file".
|
||||
const big = await post({ files: [{ name: 'cv.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10), field: 'cv' }], form: String(required.id), values: {} })
|
||||
expect(big.body).toMatchObject({ field: 'cv', message: 'The file "cv.pdf" is too large. Choose a file of up to 1 MB.' })
|
||||
mailMode = 'refuse'
|
||||
const unsent = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
|
||||
expect(unsent.body).toMatchObject({ field: 'cv', message: 'We could not send the file "cv.pdf". Choose a smaller file or another format and try again.' })
|
||||
mailMode = 'ok'
|
||||
const ok = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
|
||||
expect(ok.body.success).toBe(true)
|
||||
})
|
||||
|
||||
test('submitForm({ files }) — a project\'s own transfer path gets the same checks and the same delivery', async () => {
|
||||
const good = await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: PDF }] }, formId, locale: 'en', maxPerMinute: 0, payload })
|
||||
expect(good.success).toBe(true)
|
||||
expect(withFile()).toHaveLength(1)
|
||||
expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({
|
||||
field: 'attachment',
|
||||
file: 'cv.pdf',
|
||||
kind: 'file_refused',
|
||||
optional: true,
|
||||
types: 'PDF, DOC, DOCX',
|
||||
})
|
||||
expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.png', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ kind: 'file_type' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('options a project can set', () => {
|
||||
let other: Payload
|
||||
let otherForm: string
|
||||
const sent: Mail[] = []
|
||||
let slowScan: null | Promise<void> = null
|
||||
|
||||
beforeAll(async () => {
|
||||
other = await getPayload({
|
||||
config: buildTestConfig({
|
||||
collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: mediaDir } }],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
email: () => ({
|
||||
name: 'test-mail-2',
|
||||
defaultFromAddress: '[email protected]',
|
||||
defaultFromName: 'Acme',
|
||||
sendEmail: (message) => {
|
||||
sent.push(message as unknown as Mail)
|
||||
return Promise.resolve({ messageId: 'ok' })
|
||||
},
|
||||
}),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {
|
||||
attachments: {
|
||||
allowRisky: ['zip'],
|
||||
fileTypes: { zip: { extensions: ['zip'], label: 'ZIP', mimeType: 'application/zip' } },
|
||||
maxConcurrent: 1,
|
||||
notice: false,
|
||||
path: '/custom/files',
|
||||
scan: async () => {
|
||||
await slowScan
|
||||
return { ok: true }
|
||||
},
|
||||
submit: { allowedOrigins: ['https://app.example'], idleTimeoutMs: 300, maxPerMinute: 0, timeoutMs: 1500 },
|
||||
},
|
||||
},
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'form-files-options-secret',
|
||||
telemetry: false,
|
||||
}),
|
||||
key: 'form-files-options',
|
||||
})
|
||||
const form = await other.create({
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationMessage: text('ok'),
|
||||
emails: [{ emailFrom: '[email protected]', emailTo: '[email protected]', message: text('Files: {{files}}'), subject: 'Files' }],
|
||||
fields: [{ name: 'files', allowedTypes: ['zip', 'pdf'], blockType: 'file', label: 'Files', maxFiles: 2 }],
|
||||
title: 'Archive',
|
||||
} as never,
|
||||
})
|
||||
otherForm = String(form.id)
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await other?.destroy()
|
||||
})
|
||||
|
||||
const send = (files: Upload[], headers: Record<string, string> = { 'sec-fetch-site': 'same-origin' }) => {
|
||||
const body = new FormData()
|
||||
body.append('_form', otherForm)
|
||||
body.append('_values', '{}')
|
||||
for (const file of files) {body.append('files', new File([new Uint8Array(file.data)], file.name))}
|
||||
const request = new Request('http://localhost/api/custom/files', { body, headers, method: 'POST' })
|
||||
return handleFormSubmit(Object.assign(request, { payload: other }) as unknown as PayloadRequest)
|
||||
}
|
||||
|
||||
test('an allowed risky type, a custom path, no virus line, an extra allowed origin', async () => {
|
||||
expect((other.config.endpoints ?? []).some((e) => e.path === '/custom/files' && e.method === 'post')).toBe(true)
|
||||
const response = await send([{ name: 'drawings.zip', data: ARCHIVE }, { name: 'cv.pdf', data: PDF }], { origin: 'https://app.example', 'sec-fetch-site': 'cross-site' })
|
||||
expect(response.status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].attachments?.map((a) => a.filename)).toEqual(['drawings.zip', 'cv.pdf'])
|
||||
expect(sent[0].html).toContain('drawings.zip (')
|
||||
expect(sent[0].html).not.toContain('viruses')
|
||||
// a program is still refused, and so is an origin that is not on the list
|
||||
expect((await send([{ name: 'setup.exe', data: EXE }])).status).toBe(422)
|
||||
expect((await send([{ name: 'cv.pdf', data: PDF }], { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' })).status).toBe(403)
|
||||
})
|
||||
|
||||
test('the concurrency guard: a second file submission waits its turn with "try again"', async () => {
|
||||
let release = () => {}
|
||||
slowScan = new Promise<void>((resolve) => (release = resolve))
|
||||
const first = send([{ name: 'cv.pdf', data: PDF }])
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
const second = await send([{ name: 'cv.pdf', data: PDF }])
|
||||
expect(second.status).toBe(429)
|
||||
expect(((await second.json()) as { message: string }).message).toMatch(/Too many attempts/)
|
||||
release()
|
||||
slowScan = null
|
||||
expect((await first).status).toBe(200)
|
||||
expect((await send([{ name: 'cv.pdf', data: PDF }])).status).toBe(200) // the slot is free again
|
||||
})
|
||||
|
||||
// ---- uploads that break off, never end, or stall (security review of 1.16.0) ----------------------------
|
||||
// The request body is built by hand, so the test decides what arrives and when — like a real connection.
|
||||
const BOUNDARY = 'ipalTestBoundary'
|
||||
const part = (name: string, value: string) => `--${BOUNDARY}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`
|
||||
const prelude = (attempt?: string) =>
|
||||
Buffer.from(
|
||||
`${part('_form', otherForm)}${attempt ? part('_attempt', attempt) : ''}${part('_values', '{}')}` +
|
||||
`--${BOUNDARY}\r\nContent-Disposition: form-data; name="files"; filename="cv.pdf"\r\nContent-Type: application/pdf\r\n\r\n`,
|
||||
)
|
||||
const closing = Buffer.from(`\r\n--${BOUNDARY}--\r\n`)
|
||||
const raw = (body: ReadableStream<Uint8Array>) => {
|
||||
const request = new Request('http://localhost/api/custom/files', {
|
||||
body,
|
||||
duplex: 'half',
|
||||
headers: { 'content-type': `multipart/form-data; boundary=${BOUNDARY}`, 'sec-fetch-site': 'same-origin' },
|
||||
method: 'POST',
|
||||
} as RequestInit)
|
||||
return handleFormSubmit(Object.assign(request, { payload: other }) as unknown as PayloadRequest)
|
||||
}
|
||||
const within = <T>(promise: Promise<T>, ms: number) =>
|
||||
Promise.race([promise, new Promise<'HUNG'>((resolve) => setTimeout(() => resolve('HUNG'), ms))])
|
||||
/** Nothing is held, and the endpoint still works: a normal upload goes through (also with the same attempt key). */
|
||||
const backToNormal = async (attempt?: string) => {
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
const whole = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Buffer.concat([prelude(attempt), PDF, closing]))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
const response = await within(raw(whole), 5000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(200)
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
}
|
||||
|
||||
test('the connection drops in the middle of a file: the request ends, nothing stays held, the retry works', async () => {
|
||||
const before = (await other.count({ collection: 'form-submissions' as never })).totalDocs
|
||||
const attempt = 'attempt-dropped-00000001'
|
||||
const dropped = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)]))
|
||||
setTimeout(() => controller.error(new Error('ECONNRESET')), 50)
|
||||
},
|
||||
})
|
||||
const response = await within(raw(dropped), 3000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(400)
|
||||
expect((await other.count({ collection: 'form-submissions' as never })).totalDocs).toBe(before)
|
||||
await backToNormal(attempt) // the browser's retry with the same attempt key is not left waiting
|
||||
})
|
||||
|
||||
// Re-review of 1.16.0: the abort can land while the gates before the first file byte are still waiting
|
||||
// (the form look-up, the attempt look-up, Turnstile). The work that resumes afterwards must not leave the
|
||||
// attempt key registered — or every retry with that key would wait on a promise nobody settles.
|
||||
test.each([
|
||||
['the form look-up (before the key is registered)', 'findByID'],
|
||||
['the attempt look-up (after the key is registered)', 'find'],
|
||||
] as const)('the connection drops while %s is still pending: the key is not left behind', async (_name, method) => {
|
||||
const attempt = `attempt-pending-${method.padEnd(8, '0')}`
|
||||
const original = other[method].bind(other) as (...args: unknown[]) => Promise<unknown>
|
||||
const slow = vi.spyOn(other, method as 'find').mockImplementation((async (...args: unknown[]) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
return original(...args)
|
||||
}) as never)
|
||||
const dropped = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)]))
|
||||
setTimeout(() => controller.error(new Error('ECONNRESET')), 30)
|
||||
},
|
||||
})
|
||||
const response = await within(raw(dropped), 3000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(400)
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
// …and it is still so once the pending look-ups have finished
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
expect(slow).toHaveBeenCalled()
|
||||
slow.mockRestore()
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
// the browser's retry with the same key is answered at once
|
||||
const started = Date.now()
|
||||
await backToNormal(attempt)
|
||||
expect(Date.now() - started).toBeLessThan(1000)
|
||||
})
|
||||
|
||||
test('two dropped uploads do not use up the concurrency slots (maxConcurrent: 1 here)', async () => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const dropped = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Buffer.concat([prelude(), PDF.subarray(0, 500)]))
|
||||
setTimeout(() => controller.error(new Error('ECONNRESET')), 20)
|
||||
},
|
||||
})
|
||||
expect(await within(raw(dropped), 3000)).not.toBe('HUNG')
|
||||
}
|
||||
await backToNormal() // 200, not "too many attempts"
|
||||
})
|
||||
|
||||
test('a chunked body with no declared length that never stops: cut off at the ceiling', async () => {
|
||||
let sent = 0
|
||||
let cancelled = false
|
||||
const megabyte = Buffer.alloc(MB, 0x20)
|
||||
const endless = new ReadableStream<Uint8Array>({
|
||||
cancel() {
|
||||
cancelled = true
|
||||
},
|
||||
pull(controller) {
|
||||
controller.enqueue(sent === 0 ? Buffer.concat([prelude('attempt-endless-00000001'), Buffer.from('%PDF-1.7\n')]) : megabyte)
|
||||
sent++
|
||||
},
|
||||
})
|
||||
const response = await within(raw(endless), 10_000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(413)
|
||||
expect(cancelled).toBe(true) // the plugin stopped reading; it did not drain an endless body
|
||||
expect(sent).toBeLessThan(20) // about 10 MB + the envelope, not more
|
||||
await backToNormal('attempt-endless-00000001')
|
||||
}, 20_000)
|
||||
|
||||
test('a stalled upload (no bytes, connection open) is given up after the idle timeout', async () => {
|
||||
const stalled = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Buffer.concat([prelude('attempt-stalled-00000001'), PDF.subarray(0, 1000)]))
|
||||
// …and then nothing: never closed, never errored
|
||||
},
|
||||
})
|
||||
const started = Date.now()
|
||||
const response = await within(raw(stalled), 5000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(408)
|
||||
expect(Date.now() - started).toBeLessThan(2000) // idleTimeoutMs: 300 in this config
|
||||
expect(((await (response as Response).json()) as { message: string }).message).toBe('The form could not be sent. Please try again in a moment.')
|
||||
await backToNormal('attempt-stalled-00000001')
|
||||
})
|
||||
|
||||
test('a slow trickle that keeps sending is not cut off by the idle timeout', async () => {
|
||||
const body = Buffer.concat([prelude(), PDF, closing])
|
||||
let offset = 0
|
||||
const trickle = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 60)) // well under the idle limit, over many chunks
|
||||
const next = body.subarray(offset, offset + Math.ceil(body.length / 10))
|
||||
offset += next.length
|
||||
if (next.length) {controller.enqueue(next)}
|
||||
else {controller.close()}
|
||||
},
|
||||
})
|
||||
const response = await within(raw(trickle), 5000)
|
||||
expect((response as Response).status).toBe(200)
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
})
|
||||
|
||||
test('the request ceiling: checks that never finish do not hold the request or its slot', async () => {
|
||||
let release = () => {}
|
||||
slowScan = new Promise<void>((resolve) => (release = resolve))
|
||||
const started = Date.now()
|
||||
const response = await within(send([{ name: 'cv.pdf', data: PDF }]), 5000)
|
||||
expect(response).not.toBe('HUNG')
|
||||
expect((response as Response).status).toBe(408)
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(1400) // timeoutMs: 1500 in this config
|
||||
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
|
||||
release()
|
||||
slowScan = null
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
await backToNormal()
|
||||
})
|
||||
})
|
||||
|
||||
describe('files without the feature', () => {
|
||||
test('submitForm({ files }) on a form without a File field is refused and logged, never dropped silently', async () => {
|
||||
const plain = await payload.create({
|
||||
collection: 'forms' as never,
|
||||
data: { confirmationMessage: text('ok'), fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'No file field' } as never,
|
||||
})
|
||||
const warn = vi.spyOn(payload.logger, 'warn')
|
||||
const before = await count()
|
||||
const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: PDF }] }, formId: String(plain.id), maxPerMinute: 0, payload })
|
||||
expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false })
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('has no File field'))
|
||||
expect(await count()).toBe(before)
|
||||
warn.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,301 @@
|
||||
import { createElement } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
|
||||
|
||||
import { fileFieldLimits, resolveFormAttachments } from '../src/modules/forms/attachments/config.js'
|
||||
import { canCarryFiles, emailAddresses, fixedRecipients, mayCarryFiles } from '../src/modules/forms/attachments/delivery.js'
|
||||
import { buildFileBlock } from '../src/modules/forms/attachments/fileBlock.js'
|
||||
import { checkFileContent, matchFileType, oleHasMacros, pdfHasActiveContent, zipEntries } from '../src/modules/forms/attachments/fileChecks.js'
|
||||
import { createFileGate, limitInMB } from '../src/modules/forms/attachments/fileGate.js'
|
||||
import { describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from '../src/modules/forms/attachments/fileTypes.js'
|
||||
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
|
||||
import { fileFieldError, fileFieldRules, initialBuilderValues, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
|
||||
import { splitFormFiles } from '../src/modules/forms/createSubmitAction.js'
|
||||
import { publicForm } from '../src/modules/forms/RenderForm.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
|
||||
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const MB = 1024 * 1024
|
||||
const options = resolveFormAttachments(true)
|
||||
const risky = options.risky
|
||||
|
||||
describe('file names', () => {
|
||||
test('the attachment name is rebuilt: no path, no control or bidi characters, the detected extension', () => {
|
||||
expect(safeFileName('C:\\Users\\jan\\CV Jan Kowalski.PDF', 'pdf')).toBe('CV Jan Kowalski.pdf')
|
||||
expect(safeFileName('../../etc/passwd', 'pdf')).toBe('passwd.pdf')
|
||||
expect(safeFileName('cv\u202Efdp.exe', 'pdf')).toBe('cvfdp.pdf')
|
||||
expect(safeFileName('Życiorys (2026) — wersja #2.docx', 'docx')).toBe('Życiorys (2026) wersja 2.docx')
|
||||
expect(safeFileName('<script>.pdf', 'pdf')).toBe('script.pdf')
|
||||
expect(safeFileName('....', 'pdf')).toBe('attachment.pdf')
|
||||
expect(safeFileName(`${'a'.repeat(300)}.pdf`, 'pdf')).toHaveLength(84)
|
||||
})
|
||||
|
||||
test('the extension decides the type; risky and doubled extensions are refused', () => {
|
||||
const allowed = ['pdf', 'doc', 'docx']
|
||||
const match = (name: string, list = allowed, set: ReadonlySet<string> = risky) => {
|
||||
const result = matchFileType(name, list, options.types, set)
|
||||
return 'key' in result ? result.key : 'refused'
|
||||
}
|
||||
expect(match('cv.pdf')).toBe('pdf')
|
||||
expect(match('CV.DOCX')).toBe('docx')
|
||||
expect(match('my.cv.final.pdf')).toBe('pdf') // dots in a name are fine
|
||||
for (const name of ['cv', 'cv.txt', 'cv.pdf.exe', 'cv.exe.pdf', 'cv.pdf.docx', 'cv.docm', 'cv.zip', 'cv.svg', 'cv.html', 'cv.js.pdf']) {
|
||||
expect(match(name), name).toBe('refused')
|
||||
}
|
||||
expect(match('photo.png')).toBe('refused') // a known type the field does not allow
|
||||
expect(match('photo.jpeg', ['jpg'])).toBe('jpg')
|
||||
})
|
||||
|
||||
test('a project can allow a refused extension and add its own type', async () => {
|
||||
const own = resolveFormAttachments({
|
||||
allowRisky: ['zip'],
|
||||
fileTypes: { dwg: { detect: (bytes) => bytes[0] === 0x41 && bytes[1] === 0x43, extensions: ['.DWG'], label: 'DWG', mimeType: 'image/vnd.dwg' }, rtf: false, zip: { extensions: ['zip'], label: 'ZIP', mimeType: 'application/zip' } },
|
||||
})
|
||||
expect(own.risky.has('zip')).toBe(false)
|
||||
expect(own.risky.has('exe')).toBe(true)
|
||||
expect(Object.keys(own.types)).toContain('dwg')
|
||||
expect(own.types.rtf).toBeUndefined()
|
||||
expect(matchFileType('plan.dwg', ['dwg'], own.types, own.risky)).toMatchObject({ key: 'dwg' })
|
||||
expect(matchFileType('files.zip', ['zip'], own.types, own.risky)).toMatchObject({ key: 'zip' })
|
||||
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('AC1027....'))).toBeNull()
|
||||
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('not a drawing'))).toBe('signature')
|
||||
// The panel offers exactly the project's types.
|
||||
expect(JSON.stringify(buildFileBlock(own).fields)).toContain('"value":"dwg"')
|
||||
})
|
||||
|
||||
test('the risky list covers programs, macro files, archives and renderable markup', () => {
|
||||
for (const extension of ['exe', 'bat', 'js', 'docm', 'xlsm', 'zip', 'rar', 'html', 'svg', 'iso']) {expect(RISKY_FILE_EXTENSIONS, extension).toContain(extension)}
|
||||
expect(Object.keys(FORM_FILE_TYPES).filter((key) => FORM_FILE_TYPES[key].extensions.some((e) => RISKY_FILE_EXTENSIONS.includes(e)))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('content checks', () => {
|
||||
const ole = Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(600)])
|
||||
|
||||
test.each([
|
||||
['pdf', Buffer.from('%PDF-1.4 ....')],
|
||||
['jpg', Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0])],
|
||||
['png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0])],
|
||||
['webp', Buffer.from('RIFF\0\0\0\0WEBPVP8 ')],
|
||||
['rtf', Buffer.from('{\\rtf1\\ansi}')],
|
||||
['doc', ole],
|
||||
['xls', ole],
|
||||
])('%s: the right bytes pass, any other bytes do not', async (key, good) => {
|
||||
expect(await checkFileContent(key, FORM_FILE_TYPES[key], good)).toBeNull()
|
||||
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.from('plain text, not this type'))).toBe('signature')
|
||||
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.alloc(0))).toBe('signature')
|
||||
})
|
||||
|
||||
test('programs are refused whatever they claim to be', async () => {
|
||||
for (const head of [Buffer.from('MZ\x90\0'), Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.from('#!/bin/sh\n')]) {
|
||||
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, Buffer.concat([head, Buffer.alloc(64)]))).toBe('signature')
|
||||
}
|
||||
})
|
||||
|
||||
test('a ZIP without a readable directory is not a document', async () => {
|
||||
const truncated = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.alloc(200)])
|
||||
expect(zipEntries(truncated)).toBeNull()
|
||||
expect(await checkFileContent('docx', FORM_FILE_TYPES.docx, truncated)).toBe('signature')
|
||||
})
|
||||
|
||||
test('legacy Office: a macro storage is found by its UTF-16 name (best-effort)', () => {
|
||||
expect(oleHasMacros(ole)).toBe(false)
|
||||
expect(oleHasMacros(Buffer.concat([ole, Buffer.from('_VBA_PROJECT_CUR', 'utf16le')]))).toBe(true)
|
||||
})
|
||||
|
||||
test('strictPdf (optional): active content is refused only when switched on', async () => {
|
||||
const pdf = Buffer.from('%PDF-1.7\n1 0 obj << /OpenAction 2 0 R /JS (app.alert(1)) >> endobj')
|
||||
expect(pdfHasActiveContent(pdf)).toBe(true)
|
||||
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf)).toBeNull()
|
||||
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf, { strictPdf: true })).toBe('content')
|
||||
})
|
||||
})
|
||||
|
||||
describe('limits', () => {
|
||||
test('the editor\'s values are capped by the option and by the e-mail transport', () => {
|
||||
const field = { allowedTypes: ['pdf', 'nope'], maxFiles: 9, maxSizeMB: 50 }
|
||||
expect(fileFieldLimits(field, options)).toEqual({ allowedTypes: ['pdf'], maxBytes: 10 * MB, maxFiles: 3, maxTotalBytes: 10 * MB })
|
||||
expect(fileFieldLimits(field, options, 2_999_999)).toMatchObject({ maxBytes: 2_999_999, maxTotalBytes: 2_999_999 })
|
||||
expect(fileFieldLimits({}, resolveFormAttachments({ maxSizeMB: 5, maxTotalMB: 12 }))).toMatchObject({ maxBytes: 5 * MB, maxFiles: 1, maxTotalBytes: 12 * MB })
|
||||
expect(limitInMB(10 * MB)).toBe(10)
|
||||
expect(limitInMB(2_999_999)).toBe(2.8) // rounded down — never promise more than can be sent
|
||||
})
|
||||
|
||||
test('when earlier files used part of the submission total, the message names what is left', async () => {
|
||||
const pdf = (size: number) => Buffer.concat([Buffer.from('%PDF-1.7\n'), Buffer.alloc(size - 9, 0x20)])
|
||||
const gate = createFileGate({ fields: [{ name: 'files', allowedTypes: ['pdf'], maxFiles: 3, maxSizeMB: 10 }], options })
|
||||
const first = gate.begin('files', 'a.pdf')
|
||||
if ('failure' in first) {throw new Error('unexpected')}
|
||||
expect(await gate.finish(first.token, pdf(6 * MB))).toBeNull()
|
||||
const second = gate.begin('files', 'b.pdf')
|
||||
if ('failure' in second) {throw new Error('unexpected')}
|
||||
expect(second.slot.maxBytes).toBe(4 * MB)
|
||||
expect(second.slot.tooLarge()).toMatchObject({ file: 'b.pdf', kind: 'file_too_large', max: 4 }) // not the per-file 10
|
||||
expect(await gate.finish(second.token, pdf(4 * MB))).toBeNull()
|
||||
const third = gate.begin('files', 'c.pdf')
|
||||
if ('failure' in third) {throw new Error('unexpected')}
|
||||
expect(third.slot.tooLarge()).toMatchObject({ max: 10 }) // nothing left: the submission's total
|
||||
})
|
||||
|
||||
test('sizes read naturally', () => {
|
||||
expect([formatFileSize(512), formatFileSize(64_000), formatFileSize(2.14 * MB), formatFileSize(10 * MB)]).toEqual(['512 B', '63 KB', '2.1 MB', '10 MB'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('which e-mail may carry a file', () => {
|
||||
const form = {
|
||||
emails: [
|
||||
{ bcc: '[email protected]', emailTo: 'HR <[email protected]>, [email protected]' },
|
||||
{ emailTo: '{{email}}' },
|
||||
{ cc: '{{email}}', emailTo: '[email protected]' },
|
||||
{ emailTo: '' },
|
||||
],
|
||||
}
|
||||
|
||||
test('only e-mails whose recipients are all fixed addresses from the panel', () => {
|
||||
expect(emailAddresses('HR <[email protected]>; [email protected]')).toEqual(['[email protected]', '[email protected]'])
|
||||
expect(canCarryFiles(form)).toBe(true)
|
||||
expect(canCarryFiles({ emails: [{ emailTo: '{{email}}' }] })).toBe(false)
|
||||
expect(canCarryFiles({ emails: [] })).toBe(false)
|
||||
const fixed = fixedRecipients(form, '[email protected]')
|
||||
expect([...fixed].sort()).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]'])
|
||||
expect(mayCarryFiles({ bcc: '[email protected]', cc: '', to: 'HR <[email protected]>, [email protected]' }, fixed)).toBe(true)
|
||||
expect(mayCarryFiles({ bcc: '', cc: '', to: '[email protected]' }, fixed)).toBe(false) // the confirmation
|
||||
expect(mayCarryFiles({ bcc: '', cc: '[email protected]', to: '[email protected]' }, fixed)).toBe(false) // a mixed one
|
||||
expect(mayCarryFiles({ bcc: '', cc: '', to: '' }, fixed)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the form in the browser', () => {
|
||||
const field: BuilderField = {
|
||||
name: 'attachment',
|
||||
allowedTypes: ['pdf', 'docx'],
|
||||
blockType: 'file',
|
||||
help: 'PDF or DOCX, up to 2 MB',
|
||||
label: 'Attachment (optional)',
|
||||
maxFiles: 2,
|
||||
maxSizeMB: 2,
|
||||
resolved: { ...describeFileTypes(['pdf', 'docx']), maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3, typeLabels: 'PDF, DOCX' },
|
||||
}
|
||||
const texts = { ...NOTIFICATION_FALLBACK.form }
|
||||
const form: BuilderFormDoc = { id: 9, fields: [{ name: 'name', blockType: 'text', label: 'Name' }, field], fileSubmitUrl: '/api/ipal/forms/submit' }
|
||||
|
||||
test('rules come from what the server resolved, else from the field', () => {
|
||||
expect(fileFieldRules(field)).toMatchObject({ extensions: ['pdf', 'docx'], maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3 })
|
||||
expect(fileFieldRules({ name: 'a', allowedTypes: ['pdf'], blockType: 'file' })).toMatchObject({ accept: '.pdf,application/pdf', maxFiles: 1, maxSizeMB: 10, typeLabels: 'PDF' })
|
||||
})
|
||||
|
||||
test('instant checks use the same messages as the server', () => {
|
||||
const pdf = (name: string, size: number) => ({ name, size })
|
||||
const hint = ' You can also send the form without the file.'
|
||||
expect(fileFieldError(field, [pdf('cv.pdf', MB)], texts)).toBeUndefined()
|
||||
expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], texts)).toBe(`The file "cv.pdf" is too large. Choose a file of up to 2 MB.${hint}`)
|
||||
expect(fileFieldError(field, [pdf('cv.png', 10)], texts)).toBe(`The file "cv.png" is in a format we do not accept. Choose one of: PDF, DOCX.${hint}`)
|
||||
expect(fileFieldError(field, [pdf('a.pdf', 1), pdf('b.pdf', 1), pdf('c.pdf', 1)], texts)).toBe(`Too many files in "Attachment (optional)". Remove some: the limit is 2.${hint}`)
|
||||
expect(fileFieldError(field, [pdf('a.pdf', 1.6 * MB), pdf('b.pdf', 1.6 * MB)], texts)).toBe(`The file "b.pdf" is too large. Choose a file of up to 3 MB.${hint}`)
|
||||
expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], NOTIFICATION_FALLBACK_PL.form)).toBe('Plik „cv.pdf” jest za duży. Wybierz plik do 2 MB. Możesz też wysłać formularz bez pliku.')
|
||||
// A required field: no "send without the file".
|
||||
expect(fileFieldError({ ...field, required: true }, [pdf('cv.pdf', 3 * MB)], texts)).toBe('The file "cv.pdf" is too large. Choose a file of up to 2 MB.')
|
||||
// Older text objects without the file keys still give a message.
|
||||
expect(fileFieldError(field, [pdf('cv.png', 10)], { validation: 'Check the field "{field}".' })).toBe('Check the field "Attachment (optional)".')
|
||||
})
|
||||
|
||||
test('values and validation: a File field starts empty; required and limits are enforced', () => {
|
||||
expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] })
|
||||
expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({})
|
||||
expect(validateBuilderFields([{ ...field, required: true }], { attachment: [] }, texts)).toEqual({ attachment: 'Check the field "Attachment (optional)".' })
|
||||
expect(validateBuilderFields([field], { attachment: [{ name: 'x.exe', size: 5 }] }, texts).attachment).toContain('is in a format we do not accept')
|
||||
})
|
||||
|
||||
test('markup: a native file input with a label, help text tied to it, accept and multiple', () => {
|
||||
const html = renderToStaticMarkup(createElement(BuilderForm, { action: async () => ({ success: true }), form, locale: 'en', texts }))
|
||||
expect(html).toMatch(/<label for="ipal-f-9-attachment">Attachment \(optional\)<\/label><input[^>]*id="ipal-f-9-attachment"/)
|
||||
const input = /<input[^>]*id="ipal-f-9-attachment"[^>]*>/.exec(html)?.[0] ?? ''
|
||||
expect(input).toContain('type="file"')
|
||||
expect(input).toContain('multiple=""')
|
||||
expect(input).toContain('accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document"')
|
||||
expect(input).toContain('aria-describedby="ipal-f-9-attachment-help"')
|
||||
expect(html).toContain('<p id="ipal-f-9-attachment-help">PDF or DOCX, up to 2 MB</p>')
|
||||
expect(html).toContain('<ul aria-live="polite" data-ipal="form-files"></ul>')
|
||||
expect(html).toContain('data-type="file"')
|
||||
expect(html).not.toMatch(/class="/)
|
||||
const styled = renderToStaticMarkup(
|
||||
createElement(BuilderForm, { action: async () => ({ success: true }), classNames: { file: 'f', fileList: 'l', help: 'h' }, form, texts }),
|
||||
)
|
||||
expect(styled).toContain('class="f"')
|
||||
expect(styled).toContain('class="l"')
|
||||
expect(styled).toContain('class="h"')
|
||||
})
|
||||
|
||||
test('only the public part of the form reaches the browser, with the limits and the submit address', () => {
|
||||
const doc = { ...form, emails: [{ emailTo: '[email protected]' }] } as BuilderFormDoc
|
||||
const pub = publicForm(doc)
|
||||
expect(JSON.stringify(pub)).not.toContain('[email protected]')
|
||||
expect(pub.fileSubmitUrl).toBe('/api/ipal/forms/submit')
|
||||
expect(pub.fields?.[1].resolved).toMatchObject({ maxSizeMB: 2 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('messages and helpers', () => {
|
||||
const texts = NOTIFICATION_FALLBACK.form
|
||||
|
||||
test('every file outcome has its own text; the placeholders are filled', () => {
|
||||
const fail = (extra: Record<string, unknown>, t = texts) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, t)
|
||||
// English: which file, why, what to do
|
||||
expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 })).toBe('The file "a.pdf" is too large. Choose a file of up to 10 MB.')
|
||||
expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' })).toBe('The file "a.txt" is in a format we do not accept. Choose one of: PDF, DOCX.')
|
||||
expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' })).toBe(
|
||||
'The file "a.exe" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOCX).',
|
||||
)
|
||||
expect(fail({ kind: 'file_count', max: 2 })).toBe('Too many files in "CV". Remove some: the limit is 2.')
|
||||
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, texts)).toBe(
|
||||
'We could not send the file "a.pdf". Choose a smaller file or another format and try again.',
|
||||
)
|
||||
// an optional field: every file message adds that the form can go without the file
|
||||
for (const extra of [{ file: 'a.pdf', kind: 'file_too_large', max: 10 }, { file: 'a.txt', kind: 'file_type', types: 'PDF' }, { file: 'a.exe', kind: 'file_refused', types: 'PDF' }, { kind: 'file_count', max: 2 }]) {
|
||||
expect(fail({ ...extra, optional: true })).toMatch(/ You can also send the form without the file\.$/)
|
||||
}
|
||||
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', optional: true, reason: 'delivery', success: false }, texts)).toMatch(/try again\. You can also send the form without the file\.$/)
|
||||
// Polish
|
||||
const pl = NOTIFICATION_FALLBACK_PL.form
|
||||
expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 }, pl)).toBe('Plik „a.pdf” jest za duży. Wybierz plik do 10 MB.')
|
||||
expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' }, pl)).toBe('Plik „a.txt” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOCX.')
|
||||
expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' }, pl)).toBe(
|
||||
'Plik „a.exe” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOCX).',
|
||||
)
|
||||
expect(fail({ kind: 'file_count', max: 2, optional: true }, pl)).toBe('Za dużo plików w polu „CV”. Usuń część: limit to 2. Możesz też wysłać formularz bez pliku.')
|
||||
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, pl)).toBe('Nie udało się wysłać pliku „a.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.')
|
||||
// Failures that are not about a file keep their own texts
|
||||
expect(fail({ kind: 'required' })).toBe('Check the field "CV".')
|
||||
expect(fail({ kind: 'invalid_format', optional: true })).toBe('Check the field "CV".')
|
||||
expect(resolveFormMessage({ reason: 'error', success: false }, texts)).toBe(texts.error)
|
||||
expect(resolveFormMessage({ reason: 'rate_limited', success: false }, texts)).toBe(texts.rateLimited)
|
||||
// Texts written before the file keys existed fall back to the general ones.
|
||||
const { fileCount: _a, fileNotSent: _b, fileOptional: _f, fileRefused: _g, fileRemove: _c, fileTooLarge: _d, fileType: _e, ...old } = texts
|
||||
expect(resolveFormMessage({ reason: 'delivery', success: false }, old)).toBe(texts.error)
|
||||
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', kind: 'file_too_large', max: 1, reason: 'validation', success: false }, old)).toBe('Check the field "cv".')
|
||||
})
|
||||
|
||||
test('splitFormFiles separates File values from the answers', async () => {
|
||||
const file = new File([new Uint8Array([1, 2, 3])], 'cv.pdf')
|
||||
const { fields, files } = await splitFormFiles({ name: 'Jan', attachment: [file], single: file, tags: ['a', 'b'] })
|
||||
expect(fields).toEqual({ name: 'Jan', tags: ['a', 'b'] })
|
||||
expect(files?.attachment).toEqual([{ name: 'cv.pdf', data: new Uint8Array([1, 2, 3]) }])
|
||||
expect(files?.single).toHaveLength(1)
|
||||
expect(await splitFormFiles({ name: 'Jan', empty: [] })).toEqual({ fields: { name: 'Jan', empty: [] } })
|
||||
})
|
||||
|
||||
test('submitForm({ files }) without forms.attachments: refused and logged, the submission is not stored', async () => {
|
||||
const { create, payload } = fakePayload({ forms: { f: { fields: [{ name: 'name', blockType: 'text' }] } } })
|
||||
const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: new Uint8Array([37, 80, 68, 70]) }] }, formId: 'f', maxPerMinute: 0, payload })
|
||||
expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false })
|
||||
expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('forms.attachments is off'))
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { Block, Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { createSeeder } from '../src/exports/seed.js'
|
||||
import { localize } from '../src/modules/seed/values.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
/**
|
||||
* Regression (vanstevpl-web, 1.15.3): a whole localized value — `fields: { pl: [...], en: [...], de: [...] }` —
|
||||
* must keep the stored row ids in every locale. Before the fix each locale write made new shared rows and only
|
||||
* the last language survived (forms, nested select options, page layouts, global arrays).
|
||||
*/
|
||||
const LOCALES = ['pl', 'en', 'de'] as const
|
||||
const confirmation = (text: string) => ({
|
||||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
|
||||
})
|
||||
|
||||
/** One form, written per locale as whole localized arrays — shared blocks with nested options. */
|
||||
const formFields = (lang: { name: string; topic: string; topics: [string, string] }) => [
|
||||
{ name: 'name', blockType: 'text', label: lang.name, required: true },
|
||||
{
|
||||
name: 'topic',
|
||||
blockType: 'select',
|
||||
label: lang.topic,
|
||||
options: [
|
||||
{ label: lang.topics[0], value: 'offer' },
|
||||
{ label: lang.topics[1], value: 'other' },
|
||||
],
|
||||
},
|
||||
]
|
||||
const FORM = {
|
||||
confirmationMessage: { de: confirmation('Danke'), en: confirmation('Thanks'), pl: confirmation('Dziękujemy') },
|
||||
confirmationType: 'message',
|
||||
fields: {
|
||||
de: formFields({ name: 'Vorname', topic: 'Thema', topics: ['Angebot', 'Sonstiges'] }),
|
||||
en: formFields({ name: 'First name', topic: 'Topic', topics: ['Offer', 'Other'] }),
|
||||
pl: formFields({ name: 'Imię', topic: 'Temat', topics: ['Oferta', 'Inne'] }),
|
||||
},
|
||||
submitButtonLabel: { de: 'Senden', en: 'Send', pl: 'Wyślij' },
|
||||
title: 'Contact form',
|
||||
}
|
||||
|
||||
const section = (heading: string, items: string[]) => ({ blockType: 'section', heading, items: items.map((text) => ({ text })) })
|
||||
|
||||
describe('createSeeder: whole localized arrays keep every language', () => {
|
||||
let payload: Payload
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv('DATABASE_URI', 'file::memory:')
|
||||
const sectionBlock: Block = {
|
||||
slug: 'section',
|
||||
fields: [
|
||||
{ name: 'heading', type: 'text', localized: true },
|
||||
{ name: 'items', type: 'array', fields: [{ name: 'text', type: 'text', localized: true }] },
|
||||
],
|
||||
}
|
||||
const config = buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||||
// Shared rows, text per locale (the block library's default).
|
||||
{ name: 'layout', type: 'blocks', blocks: [sectionBlock] },
|
||||
// Rows per locale (the block library's `localization: 'layout'`).
|
||||
{ name: 'localizedLayout', type: 'blocks', blocks: [sectionBlock], localized: true },
|
||||
],
|
||||
},
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-arrays') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
globals: [
|
||||
{
|
||||
slug: 'footer',
|
||||
fields: [{ name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }, { name: 'url', type: 'text' }] }],
|
||||
},
|
||||
],
|
||||
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
|
||||
plugins: [
|
||||
ipalKit({
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
|
||||
pages: { slug: 'pages' },
|
||||
twoFactor: false,
|
||||
} as never),
|
||||
],
|
||||
secret: 'seed-localized-arrays',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
const seeder = () => createSeeder(payload, { dryRun: false, log: () => {}, update: false })
|
||||
const readAll = (collection: string, id: number | string) =>
|
||||
payload.findByID({ id, collection: collection as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never }) as Promise<Record<string, unknown>>
|
||||
|
||||
test('a form: blocks and nested select options keep every language and one set of row ids', async () => {
|
||||
const result = await seeder().upsertBy('forms', { title: 'Contact form' }, FORM)
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = await readAll('forms', result.id!)
|
||||
const fields = all.fields as { id: string; label: Record<string, string>; options?: { id: string; label: Record<string, string> }[] }[]
|
||||
expect(fields).toHaveLength(2)
|
||||
expect(fields[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
|
||||
expect(fields[1].label).toEqual({ de: 'Thema', en: 'Topic', pl: 'Temat' })
|
||||
expect(fields[1].options?.map((o) => o.label)).toEqual([
|
||||
{ de: 'Angebot', en: 'Offer', pl: 'Oferta' },
|
||||
{ de: 'Sonstiges', en: 'Other', pl: 'Inne' },
|
||||
])
|
||||
expect(all.submitButtonLabel).toEqual({ de: 'Senden', en: 'Send', pl: 'Wyślij' })
|
||||
|
||||
// Every locale reads the same rows.
|
||||
const ids = async (locale: string) => {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: locale as never })) as unknown as { fields: { id: string; options?: { id: string }[] }[] }
|
||||
return doc.fields.flatMap((f) => [f.id, ...(f.options ?? []).map((o) => o.id)])
|
||||
}
|
||||
const pl = await ids('pl')
|
||||
expect(await ids('en')).toEqual(pl)
|
||||
expect(await ids('de')).toEqual(pl)
|
||||
|
||||
// An editor's later save in Polish validates (no missing option labels).
|
||||
const plDoc = await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: 'pl' })
|
||||
await expect(payload.update({ id: result.id!, collection: 'forms', data: { ...plDoc, submitButtonLabel: 'Wyślij teraz' } as never, locale: 'pl' })).resolves.toBeTruthy()
|
||||
const after = await readAll('forms', result.id!)
|
||||
expect((after.fields as { label: Record<string, string> }[])[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
|
||||
})
|
||||
|
||||
test('a page: a shared layout keeps one set of rows; a localized layout keeps rows per locale', async () => {
|
||||
const page = {
|
||||
slug: { de: 'ueber-uns', en: 'about', pl: 'o-nas' },
|
||||
layout: {
|
||||
de: [section('Leistungen', ['Planung', 'Bau'])],
|
||||
en: [section('Services', ['Design', 'Build'])],
|
||||
pl: [section('Usługi', ['Projekt', 'Budowa'])],
|
||||
},
|
||||
localizedLayout: {
|
||||
de: [section('Nur Deutsch', ['Eins'])],
|
||||
en: [section('English only', ['One', 'Two', 'Three'])],
|
||||
pl: [section('Tylko polski', ['Jeden', 'Dwa'])],
|
||||
},
|
||||
title: { de: 'Über uns', en: 'About', pl: 'O nas' },
|
||||
}
|
||||
const [result] = await seeder().upsertBySlug('pages', [page])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = await readAll('pages', result.id!)
|
||||
const layout = all.layout as { heading: Record<string, string>; id: string; items: { text: Record<string, string> }[] }[]
|
||||
expect(layout).toHaveLength(1)
|
||||
expect(layout[0].heading).toEqual({ de: 'Leistungen', en: 'Services', pl: 'Usługi' })
|
||||
expect(layout[0].items.map((i) => i.text)).toEqual([
|
||||
{ de: 'Planung', en: 'Design', pl: 'Projekt' },
|
||||
{ de: 'Bau', en: 'Build', pl: 'Budowa' },
|
||||
])
|
||||
|
||||
// Localized layout: each language has its own rows, with its own length.
|
||||
for (const [locale, heading, count] of [['pl', 'Tylko polski', 2], ['en', 'English only', 3], ['de', 'Nur Deutsch', 1]] as const) {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { localizedLayout: { heading: string; items: unknown[] }[] }
|
||||
expect(doc.localizedLayout[0]).toMatchObject({ heading })
|
||||
expect(doc.localizedLayout[0].items).toHaveLength(count)
|
||||
}
|
||||
})
|
||||
|
||||
test('a global array (fillGlobal) keeps every language', async () => {
|
||||
const links = (labels: [string, string]) => [
|
||||
{ label: labels[0], url: '/kontakt' },
|
||||
{ label: labels[1], url: '/blog' },
|
||||
]
|
||||
const result = await seeder().fillGlobal('footer', {
|
||||
links: { de: links(['Kontakt', 'Blog']), en: links(['Contact', 'Blog']), pl: links(['Kontakt', 'Wpisy']) },
|
||||
})
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
const all = (await payload.findGlobal({ slug: 'footer' as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as { links: { label: Record<string, string>; url: string }[] }
|
||||
expect(all.links.map((l) => l.label)).toEqual([
|
||||
{ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' },
|
||||
{ de: 'Blog', en: 'Blog', pl: 'Wpisy' },
|
||||
])
|
||||
expect(all.links.map((l) => l.url)).toEqual(['/kontakt', '/blog'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('localize', () => {
|
||||
test('a whole localized value keeps the stored row ids, nested arrays included', () => {
|
||||
const stored = [{ id: 'a', options: [{ id: 'o1', label: 'Oferta' }] }]
|
||||
const value = { en: [{ options: [{ label: 'Offer' }] }], pl: [{ options: [{ label: 'Oferta' }] }] }
|
||||
expect(localize(value, 'en', stored, ['pl', 'en'])).toEqual([{ id: 'a', options: [{ id: 'o1', label: 'Offer' }] }])
|
||||
expect(localize(value, 'de', stored, ['pl', 'en', 'de'])).toBeUndefined()
|
||||
})
|
||||
|
||||
test('with a schema, a localized field never reuses another locale’s rows', () => {
|
||||
const schema = { fields: [{ name: 'layout', type: 'array', fields: [{ name: 'text', type: 'text' }], localized: true }] }
|
||||
const stored = { layout: [{ id: 'pl-row', text: 'Polski' }] }
|
||||
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'], schema)).toEqual({ layout: [{ text: 'English' }] })
|
||||
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'])).toEqual({ layout: [{ id: 'pl-row', text: 'English' }] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { Block, Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { SeedResult } from '../src/exports/seed.js'
|
||||
|
||||
import { createSeeder } from '../src/exports/seed.js'
|
||||
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
/**
|
||||
* Regression (vanstevpl-web, 1.15.4): a page whose REQUIRED layout holds a { $page } / { $form } reference
|
||||
* could not be created — pass 1 left the whole field out and validation rejected the record, while the dry
|
||||
* run reported a create. Now pass 1 resolves references to existing records, retries records whose required
|
||||
* fields wait for pages created later in the same call, and reports cycles and unknown targets as errors
|
||||
* with nothing written. The dry run reports the same outcome.
|
||||
*/
|
||||
const LOCALES = ['pl', 'en', 'de'] as const
|
||||
|
||||
const callToAction: Block = { slug: 'callToAction', fields: [buildSectionHeaderField(), buildLinksField()] }
|
||||
const formBlock: Block = { slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms', required: true }] }
|
||||
// A block whose link to another page is required — forward references to it must wait.
|
||||
const teaser: Block = { slug: 'teaser', fields: [{ name: 'target', type: 'relationship', relationTo: 'pages', required: true }] }
|
||||
|
||||
const confirmation = {
|
||||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
|
||||
}
|
||||
|
||||
/** A page with a required layout of one block. */
|
||||
const page = (slug: string, title: string, layout: Record<string, unknown>[]) => ({
|
||||
slug: { de: `${slug}-de`, en: `${slug}-en`, pl: slug },
|
||||
layout,
|
||||
title: { de: `${title} DE`, en: `${title} EN`, pl: title },
|
||||
})
|
||||
const teaserTo = (slug: string) => ({ blockType: 'teaser', target: { $page: slug } })
|
||||
|
||||
describe('createSeeder: required fields with references', () => {
|
||||
let payload: Payload
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv('DATABASE_URI', 'file::memory:')
|
||||
const config = buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', localized: true, required: true },
|
||||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||||
{ name: 'layout', type: 'blocks', blocks: [callToAction, formBlock, teaser], required: true },
|
||||
],
|
||||
},
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-refs') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
|
||||
plugins: [
|
||||
ipalKit({
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
|
||||
pages: { slug: 'pages' },
|
||||
twoFactor: false,
|
||||
} as never),
|
||||
],
|
||||
secret: 'seed-required-refs',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
// The existing records the references point at.
|
||||
const seed = createSeeder(payload, { log: () => {} })
|
||||
await seed.upsertBySlug('pages', page('kontakt', 'Kontakt', [{ blockType: 'callToAction', header: { heading: { de: 'Hallo', en: 'Hello', pl: 'Cześć' } } }]))
|
||||
await seed.upsertBy('forms', { title: 'Contact form' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'Contact form' })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
const seeder = (dryRun = false) => createSeeder(payload, { dryRun, log: () => {}, update: false })
|
||||
const idOf = async (slug: string) => (await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: slug } } })).docs[0]?.id
|
||||
const count = async () => (await payload.count({ collection: 'pages' })).totalDocs
|
||||
|
||||
/** Runs the same seed as a dry run, then for real: both must report the same statuses. */
|
||||
const both = async (run: (seed: ReturnType<typeof seeder>) => Promise<SeedResult | SeedResult[]>) => {
|
||||
const planned = [await run(seeder(true))].flat().map((r) => r.status)
|
||||
const done = [await run(seeder())].flat()
|
||||
expect(done.map((r) => r.status)).toEqual(planned)
|
||||
return done
|
||||
}
|
||||
|
||||
test('the report’s careers page: a required layout linking to an existing page, in pl, en and de', async () => {
|
||||
const careers = {
|
||||
slug: { de: 'karriere', en: 'careers', pl: 'kariera' },
|
||||
layout: [
|
||||
{
|
||||
blockType: 'callToAction',
|
||||
header: { heading: { de: 'Kontakt', en: 'Contact', pl: 'Kontakt' } },
|
||||
links: [{ link: { type: 'internal', page: { $page: 'kontakt' } } }],
|
||||
},
|
||||
],
|
||||
title: { de: 'Karriere', en: 'Careers', pl: 'Kariera' },
|
||||
}
|
||||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', careers)])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as unknown as {
|
||||
layout: { header: { heading: Record<string, string> }; id: string; links: { link: { page: unknown } }[] }[]
|
||||
}
|
||||
expect(all.layout).toHaveLength(1)
|
||||
expect(all.layout[0].header.heading).toEqual({ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' })
|
||||
expect(all.layout[0].links[0].link.page).toBe(await idOf('kontakt'))
|
||||
// One set of rows in every locale (1.15.4).
|
||||
for (const locale of LOCALES) {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { layout: { id: string }[] }
|
||||
expect(doc.layout[0].id).toBe(all.layout[0].id)
|
||||
}
|
||||
|
||||
// Create-only: a second run changes nothing.
|
||||
expect(await seeder().upsertBySlug('pages', careers)).toMatchObject({ status: 'skip (exists)' })
|
||||
})
|
||||
|
||||
test('a required layout with a form block pointing at an existing form', async () => {
|
||||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', page('formularz', 'Formularz', [{ blockType: 'formBlock', form: { $form: 'Contact form' } }]))])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 1, locale: 'pl' })) as unknown as { layout: { form: { title: string } }[] }
|
||||
expect(doc.layout[0].form.title).toBe('Contact form')
|
||||
})
|
||||
|
||||
test('forward references in one call: an optional link is filled in pass 2, a required one waits for its page', async () => {
|
||||
const results = await both((seed) =>
|
||||
seed.upsertBySlug('pages', [
|
||||
// Optional link (CTA) to a page later in the list.
|
||||
page('o-nas', 'O nas', [{ blockType: 'callToAction', links: [{ link: { type: 'internal', page: { $page: 'oferta' } } }] }]),
|
||||
// Required link to a page later in the list: created once that page exists.
|
||||
page('start', 'Start', [teaserTo('oferta')]),
|
||||
page('oferta', 'Oferta', [{ blockType: 'callToAction', header: { heading: { de: 'Angebot', en: 'Offer', pl: 'Oferta' } } }]),
|
||||
]),
|
||||
)
|
||||
expect(results.map((r) => r.status)).toEqual(['create', 'create', 'create'])
|
||||
const oferta = await idOf('oferta')
|
||||
const about = (await payload.findByID({ id: (await idOf('o-nas')), collection: 'pages', depth: 0, locale: 'en' })) as unknown as { layout: { links: { link: { page: unknown } }[] }[] }
|
||||
expect(about.layout[0].links[0].link.page).toBe(oferta)
|
||||
const start = (await payload.findByID({ id: (await idOf('start')), collection: 'pages', depth: 0, locale: 'de' })) as unknown as { layout: { target: unknown }[] }
|
||||
expect(start.layout[0].target).toBe(oferta)
|
||||
|
||||
// Second run: everything exists, nothing written.
|
||||
const again = await seeder().upsertBySlug('pages', [page('o-nas', 'O nas', []), page('start', 'Start', []), page('oferta', 'Oferta', [])])
|
||||
expect(again.map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)', 'skip (exists)'])
|
||||
})
|
||||
|
||||
test('required references in a cycle: a clear error, nothing written', async () => {
|
||||
const before = await count()
|
||||
const results = await seeder().upsertBySlug('pages', [page('jeden', 'Jeden', [teaserTo('dwa')]), page('dwa', 'Dwa', [teaserTo('jeden')])])
|
||||
expect(results.map((r) => r.status)).toEqual(['error', 'error'])
|
||||
expect(results[0].note).toMatch(/required references to pages not created yet \("dwa"\) — a cycle of required links/)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('a reference to a page that never appears: an error in the dry run and the real run, nothing written', async () => {
|
||||
const before = await count()
|
||||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('sierota', 'Sierota', [teaserTo('nie-ma-takiej')]))])
|
||||
expect(results[0]).toMatchObject({ status: 'error' })
|
||||
expect(results[0].note).toMatch(/\$page "nie-ma-takiej" not found/)
|
||||
expect(await count()).toBe(before)
|
||||
})
|
||||
|
||||
test('a reference to a form that does not exist: an error in the dry run too', async () => {
|
||||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('bez-formularza', 'Bez', [{ blockType: 'formBlock', form: { $form: 'Missing form' } }]))])
|
||||
expect(results[0]).toMatchObject({ status: 'error' })
|
||||
expect(results[0].note).toMatch(/\$form "Missing form" not found/)
|
||||
})
|
||||
|
||||
test('dry run: a form planned earlier in the same run counts as there', async () => {
|
||||
const seed = seeder(true)
|
||||
expect(await seed.upsertBy('forms', { title: 'Newsletter' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [], title: 'Newsletter' })).toMatchObject({ status: 'create' })
|
||||
expect(await seed.upsertBySlug('pages', page('newsletter', 'Newsletter', [{ blockType: 'formBlock', form: { $form: 'Newsletter' } }]))).toMatchObject({ status: 'create' })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user