Form attachments: reference smoke test with a mail sink, Turnstile reset fix, docs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
387debc88c
commit
fdb6140c09
@@ -46,6 +46,11 @@ once there are more than 20.
|
||||
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`
|
||||
|
||||
@@ -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',
|
||||
@@ -1154,6 +1159,7 @@ Rules: AGENT.md §8a.
|
||||
|---|---|
|
||||
| `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/smtp-sink.ts` | — |
|
||||
| `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)
|
||||
```
|
||||
|
||||
|
||||
+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
|
||||
|
||||
|
||||
@@ -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,38 @@ 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`).
|
||||
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`, `fileCount`, `fileNotSent`, `fileRemove`) —
|
||||
English and Polish defaults; fill every other language of the site.
|
||||
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 your
|
||||
file", 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 +177,10 @@ 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` → "…is not an accepted file type", no submission; a file over the limit → the
|
||||
size message before sending; 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 +192,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 your 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`); 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`
|
||||
|
||||
|
||||
@@ -107,18 +107,25 @@ test.describe('the quote form sends a file by e-mail', () => {
|
||||
|
||||
// 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' })
|
||||
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
|
||||
const token = form.locator('input[name="cf-turnstile-response"]')
|
||||
await expect(token).not.toHaveValue('', { timeout: 15_000 })
|
||||
await form.locator('button[type="submit"]').click()
|
||||
await expect(form.locator('[id$="attachment-error"]')).toContainText('not an accepted file type', { timeout: 15_000 })
|
||||
expect(sink.messages).toHaveLength(0)
|
||||
|
||||
// the real file
|
||||
// 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')
|
||||
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
|
||||
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST')
|
||||
await form.locator('button[type="submit"]').click()
|
||||
expect((await posted).status()).toBe(200)
|
||||
// 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)
|
||||
|
||||
Generated
+1
@@ -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,26 @@ 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;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
fileNotSent?: string | null;
|
||||
/**
|
||||
* Use {file} for the file name.
|
||||
*/
|
||||
fileRemove?: string | null;
|
||||
next?: string | null;
|
||||
back?: string | null;
|
||||
/**
|
||||
@@ -3194,6 +3296,11 @@ export interface NotificationsSelect<T extends boolean = true> {
|
||||
turnstile?: T;
|
||||
rateLimited?: T;
|
||||
notFound?: T;
|
||||
fileTooLarge?: T;
|
||||
fileType?: T;
|
||||
fileCount?: T;
|
||||
fileNotSent?: T;
|
||||
fileRemove?: T;
|
||||
next?: T;
|
||||
back?: T;
|
||||
stepOf?: T;
|
||||
|
||||
@@ -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} />
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user