Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:51:05 +01:00
co-authored by Claude Fable 5.2
parent b6f9f34705
commit 97202ee03e
18 changed files with 335 additions and 128 deletions
+9 -4
View File
@@ -24,18 +24,23 @@ once there are more than 20.
- **E-mail:** the file goes to every e-mail of the form whose recipients are fixed addresses from the panel; an - **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 e-mail addressed with a placeholder (the confirmation to the visitor) never carries it. `{{field}}`, `{{*}}` and
`{{*:table}}` show the file name. `{{*:table}}` show the file name.
- **A failed send is visible:** the visitor sees "We could not send your file…" and can retry, staff get the - **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 notification without the file, the submission is marked **File delivery: Not sent**. A repeated request
(double click, a resend) sends nothing twice. (double click, a resend) sends nothing twice.
- Browser: `RenderForm` / `BuilderForm` render a native file input with help text, the list of picked files and - 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`, a "Remove" button; `useBuilderForm` gains `getFileProps`, `getFiles`, `removeFile`, `helpId`,
`getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`. `getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`.
- New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileCount`, `fileNotSent`, `fileRemove`), - New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
English and Polish defaults. `fileOptional`, `fileRemove`), English and Polish defaults.
- New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`, - New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`,
`mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`); `mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`);
`splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' | `splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' |
'file_type' | 'file_count'` and `reason: 'delivery'`. 'file_type' | 'file_refused' | 'file_count'` and `reason: 'delivery'`.
- **Attachments over both e-mail transports** ([email.md](./email.md) "Attachments"). SMTP passes them through. - **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 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` upload session, and the copy the mailbox keeps is deleted afterwards. That path needs the `Mail.ReadWrite`
+10 -7
View File
@@ -103,8 +103,10 @@ Never build this by hand (your own `<input type="file">`, upload route or upload
browser posts files to the plugin's endpoint `POST /api/ipal/forms/submit` — no route file, no `next.config` 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: 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)`. `f.getFileProps(field)`, `f.getFiles(field)`, `f.removeFile(field, i)`, `f.helpId(field)`.
5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileCount`, `fileNotSent`, `fileRemove`) — 5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
English and Polish defaults; fill every other language of the site. `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. 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 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 maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
@@ -112,8 +114,8 @@ Never build this by hand (your own `<input type="file">`, upload route or upload
drops to about 2.8 MB by itself. Keep Graph small on purpose: `mailAdapter({ graph: { largeAttachments: false } })`. 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` 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 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", staff get a notice without the file, and the submission shows **File delivery: Not sent**. 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/*`) ## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8): From `createPageRoute` (PROGRAMISTA §2.8):
@@ -179,8 +181,9 @@ Details the seed already covers, which you check after every manual change in th
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values; - [ ] 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, - [ ] 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; 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 a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
size message before sending; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it; 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-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking). - [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -192,7 +195,7 @@ 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`) | | `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 | | "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 | | `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") | | "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 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` | | 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 | | 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 |
+26 -10
View File
@@ -211,7 +211,7 @@ ipalKit({ forms: { attachments: true } }) // adds the File field to the form
**Verify:** submit the form with a PDF → the confirmation shows; the company e-mail has the file attached and the **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 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 → **Files** (name, type, size) and **File delivery: Handed to the mail server**. Rename a `.exe` to `.pdf` and submit →
the field shows "…is not an accepted file type", nothing is stored or sent. the File field shows "The file … was refused: …", nothing is stored or sent.
### Options (`FormAttachmentsOption`) ### Options (`FormAttachmentsOption`)
@@ -294,8 +294,9 @@ characters, the extension of the detected type (`CV Jan Kowalski.pdf`; an empty
The file is not kept, so there is nothing to retry with. Then: The file is not kept, so there is nothing to retry with. Then:
- the **visitor** sees an error — Form messages → **File not sent** ("We could not send your file. Try again, or - the **visitor** sees an error **at the File field** — Form messages → **File not sent** ("We could not send the
send it by e-mail.") — keeps their answers and the selected file, and can try again. No confirmation e-mail goes out; 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 - **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."; 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 - the **submission** is stored and marked **File delivery: Not sent**, with a note (the mail server's reason). The
@@ -308,12 +309,27 @@ refuses it) cannot be seen by the site; it arrives in the sender mailbox.
(double click, a resend by the browser or a proxy) gets the first answer and sends nothing again. The plugin sends (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. each e-mail once — there is no automatic resend.
### Result codes and messages ### What the visitor is told
`reason: 'validation'` with `kind: 'file_too_large' | 'file_type' | 'file_count'` (+ `field`, `label`, `file`, **When a submission fails because of the file, the message says it is the file, why, and what to do** — and it
`max`, `types`), `kind: 'required'` for a required File field without a file, and `reason: 'delivery'` when the shows at the File field (the result carries `field`). Everything the visitor typed stays in the form.
e-mail could not be sent. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileCount`, `fileNotSent`,
`fileRemove`), defaults in English and Polish, per language in the panel ([notifications.md](./notifications.md)). | 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 ### Your own markup
@@ -556,8 +572,8 @@ type SubmitFormResult =
| { success: true; submissionId: string | number } | { success: true; submissionId: string | number }
| { success: false; reason: 'rate_limited' } | { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' } | { success: false; reason: 'turnstile' }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_count'; file?: string; max?: number; types?: string } | { 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'; submissionId?: string | number } // the file could not be e-mailed | { 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: 'not_found' }
| { success: false; reason: 'consent'; field?: string } | { success: false; reason: 'consent'; field?: string }
| { success: false; reason: 'error' } | { success: false; reason: 'error' }
+12 -7
View File
@@ -61,17 +61,22 @@ per language.
With `forms.attachments` ([forms.md](./forms.md) "Files") the **Files** group of Form messages holds: 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 | | Key | Placeholders | English default |
|---|---|---| |---|---|---|
| `fileTooLarge` | `{file}`, `{max}` (MB) | `"{file}" is too large. The limit is {max} MB.` | | `fileTooLarge` | `{file}`, `{max}` (MB) | `The file "{file}" is too large. Choose a file of up to {max} MB.` |
| `fileType` | `{file}`, `{types}` | `"{file}" is not an accepted file type. Accepted: {types}.` | | `fileType` | `{file}`, `{types}` | `The file "{file}" is in a format we do not accept. Choose one of: {types}.` |
| `fileCount` | `{field}`, `{max}` | `Attach at most {max} files in "{field}".` | | `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}).` |
| `fileNotSent` | — | `We could not send your file. Try again, or send it by e-mail.` | | `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}` | | `fileRemove` | `{file}` | `Remove {file}` |
Polish defaults ship too; any other language is filled in the panel. `resolveFormMessage` maps Polish defaults ship too; any other language is filled in the panel (an empty field falls back to English there).
`kind: 'file_too_large' | 'file_type' | 'file_count'` and `reason: 'delivery'` to them; a texts object without these `resolveFormMessage` maps `kind: 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'` and
keys falls back to `validation` / `error`. `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 ## {field} interpolation
+12 -2
View File
@@ -99,7 +99,7 @@ test.describe('the quote form sends a file by e-mail', () => {
// a type the field does not accept: the message shows at once, by the field // 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 input.setInputFiles({ buffer: Buffer.from('MZ'), mimeType: 'application/octet-stream', name: 'plan.exe' })
await expect(form.locator('[id$="attachment-error"]')).toContainText('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 // keyboard: the Remove button is a real button — focus it and press Enter
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus() await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
@@ -110,7 +110,17 @@ test.describe('the quote form sends a file by e-mail', () => {
const token = form.locator('input[name="cf-turnstile-response"]') const token = form.locator('input[name="cf-turnstile-response"]')
await expect(token).not.toHaveValue('', { timeout: 15_000 }) await expect(token).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click() await form.locator('button[type="submit"]').click()
await expect(form.locator('[id$="attachment-error"]')).toContainText('not an accepted file type', { timeout: 15_000 }) // 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) expect(sink.messages).toHaveLength(0)
// the real file (the field takes several: remove the refused one first) // the real file (the field takes several: remove the refused one first)
+10 -1
View File
@@ -69,11 +69,20 @@ export const notificationsFields: Field[] = [
formText('fileType', { en: 'Wrong file type', pl: 'Niedozwolony typ pliku' }, { 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.' }, 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' }, { 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.' }, 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' }, { formText('fileNotSent', { en: 'File not sent', pl: 'Plik niewysłany' }, {
description: { en: 'Shown when the file could not be sent by e-mail.', pl: 'Widoczny, gdy pliku nie udało się wysłać e-mailem.' }, 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' }, { 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.' }, description: { en: 'Use {file} for the file name.', pl: 'Użyj {file}, aby wstawić nazwę pliku.' },
+9 -6
View File
@@ -145,26 +145,29 @@ export type FileRefusal =
/** /**
* Name check, before any byte of the file: the last extension must belong to * Name check, before any byte of the file: the last extension must belong to
* one of the allowed types, and NO extension of the name may be a risky one * one of the allowed types (else `type`: simply another format), and NO
* ("cv.pdf.exe", "cv.exe.pdf") unless the project allowed it. * 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( export function matchFileType(
name: string, name: string,
allowed: readonly string[], allowed: readonly string[],
types: Record<string, FormFileType>, types: Record<string, FormFileType>,
risky: ReadonlySet<string>, risky: ReadonlySet<string>,
): { key: string; type: FormFileType } | { refused: 'name' } { ): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '') const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
const last = extensions.at(-1) const last = extensions.at(-1)
if (!last || extensions.some((e) => risky.has(e))) {return { refused: 'name' }} // 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. // "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)) const known = new Set(Object.values(types).flatMap((t) => t.extensions))
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'name' }} if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'refused' }}
for (const key of allowed) { for (const key of allowed) {
const type = types[key] const type = types[key]
if (type?.extensions.includes(last)) {return { type, key }} if (type?.extensions.includes(last)) {return { type, key }}
} }
return { refused: 'name' } return { refused: 'type' }
} }
/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */ /** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */
+22 -12
View File
@@ -22,10 +22,19 @@ export type FormFileFailure = {
field: string field: string
/** The file's name as the visitor knows it (cleaned of control characters). */ /** The file's name as the visitor knows it (cleaned of control characters). */
file?: string file?: string
kind: 'file_count' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields' /**
* - `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. */ /** The limit: MB for file_too_large, a count for file_count. */
max?: number max?: number
/** "PDF, DOC, DOCX" — for file_type. */ /** 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 types?: string
} }
@@ -79,34 +88,35 @@ export function createFileGate({
const file = displayName(rawName) const file = displayName(rawName)
const count = (counts.get(fieldName) ?? 0) + 1 const count = (counts.get(fieldName) ?? 0) + 1
counts.set(fieldName, count) counts.set(fieldName, count)
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles } }} 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 types = describeFileTypes(limits.allowedTypes, options.types).labels
const typeFailure: FormFileFailure = { field: fieldName, file, kind: 'file_type', types } const refusedFailure: FormFileFailure = { field: fieldName, file, kind: 'file_refused', optional, types }
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky) const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
if ('refused' in match) {return { failure: typeFailure }} 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)) const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes) }) const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes), optional })
let checked = false let checked = false
return { return {
slot: { slot: {
checkStart: (head) => { checkStart: (head) => {
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null} if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
checked = true checked = true
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? typeFailure : null return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? refusedFailure : null
}, },
maxBytes, maxBytes,
tooLarge, tooLarge,
}, },
token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure }, token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
} }
} }
const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => { const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => {
if (data.length > token.maxBytes) {return token.tooLarge()} if (data.length > token.maxBytes) {return token.tooLarge()}
const type = options.types[token.key] const type = options.types[token.key]
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.typeFailure} if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.refusedFailure}
const file: AcceptedFormFile = { const file: AcceptedFormFile = {
name: safeFileName(token.rawName, type.extensions[0]), name: safeFileName(token.rawName, type.extensions[0]),
type: token.key, type: token.key,
@@ -118,9 +128,9 @@ export function createFileGate({
if (options.scan) { if (options.scan) {
try { try {
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size }) const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
if (!verdict?.ok) {return token.typeFailure} if (!verdict?.ok) {return token.refusedFailure}
} catch { } catch {
return token.typeFailure return token.refusedFailure
} }
} }
total += data.length total += data.length
@@ -145,8 +155,8 @@ type BeginToken = {
key: string key: string
maxBytes: number maxBytes: number
rawName: string rawName: string
refusedFailure: FormFileFailure
tooLarge: () => FormFileFailure tooLarge: () => FormFileFailure
typeFailure: FormFileFailure
} }
export type FileGate = ReturnType<typeof createFileGate> export type FileGate = ReturnType<typeof createFileGate>
@@ -132,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const source = Readable.fromWeb(req.body as never) const source = Readable.fromWeb(req.body as never)
const parser = busboy({ 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 }, headers: { 'content-type': contentType },
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 }, limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
}) })
+9 -6
View File
@@ -131,22 +131,25 @@ export function fileFieldRules(field: BuilderField): Required<BuilderFileLimits>
export function fileFieldError( export function fileFieldError(
field: BuilderField, field: BuilderField,
files: readonly BuilderFile[], files: readonly BuilderFile[],
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>, texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
): string | undefined { ): string | undefined {
const rules = fileFieldRules(field) const rules = fileFieldRules(field)
const label = field.label || field.name || '' const label = field.label || field.name || ''
const generic = texts.validation.replace('{field}', label) const generic = texts.validation.replace('{field}', label)
if (files.length > rules.maxFiles) {return (texts.fileCount ?? generic).replace('{field}', label).replace('{max}', String(rules.maxFiles))} // 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) { for (const file of files) {
if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) { if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) {
return (texts.fileType ?? generic).replace('{file}', file.name).replace('{types}', rules.typeLabels) return say(texts.fileType, (t) => t.replace('{file}', file.name).replace('{types}', rules.typeLabels))
} }
if (file.size > rules.maxSizeMB * MB || file.size === 0) { if (file.size > rules.maxSizeMB * MB || file.size === 0) {
return (texts.fileTooLarge ?? generic).replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB)) 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) { if (files.reduce((sum, f) => sum + f.size, 0) > rules.maxTotalMB * MB) {
return (texts.fileTooLarge ?? generic).replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB)) return say(texts.fileTooLarge, (t) => t.replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB)))
} }
return undefined return undefined
} }
@@ -170,7 +173,7 @@ const isBlank = isBlankValue
export function validateBuilderFields( export function validateBuilderFields(
fields: BuilderField[], fields: BuilderField[],
values: Record<string, unknown>, values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>, texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
): Record<string, string> { ): Record<string, string> {
const errors: Record<string, string> = {} const errors: Record<string, string> = {}
for (const f of inputFields(fields)) { for (const f of inputFields(fields)) {
+1
View File
@@ -84,6 +84,7 @@ export type BuilderFormTexts = {
error?: string error?: string
/** File field — see FormNotificationTexts. */ /** File field — see FormNotificationTexts. */
fileCount?: string fileCount?: string
fileOptional?: string
fileRemove?: string fileRemove?: string
fileTooLarge?: string fileTooLarge?: string
fileType?: string fileType?: string
+34 -7
View File
@@ -86,8 +86,13 @@ export type SubmitFailure =
/** /**
* The file could not be handed to the mail server (or the form has no * 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 * e-mail that may carry it). The file is gone — the visitor must send it
* again. `submissionId`: the stored attempt, marked "Not sent". * 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' reason: 'delivery'
submissionId?: number | string submissionId?: number | string
success: false success: false
@@ -95,14 +100,16 @@ export type SubmitFailure =
| { | {
/** The offending field's name, when one field is at fault. */ /** The offending field's name, when one field is at fault. */
field?: string field?: string
/** The refused file's name (file_too_large, file_type). */ /** The refused file's name (file_too_large, file_type, file_refused). */
file?: string file?: string
/** What was wrong with it. */ /** What was wrong with it. */
kind?: 'file_count' | 'file_too_large' | 'file_type' | '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. */ /** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
label?: string label?: string
/** The limit behind file_too_large (MB) or file_count (files). */ /** The limit behind file_too_large (MB) or file_count (files). */
max?: number max?: number
/** A file problem on a field that is not required — the form can be sent without the file. */
optional?: boolean
reason: 'validation' reason: 'validation'
success: false success: false
/** Accepted types, "PDF, DOCX" (file_type). */ /** Accepted types, "PDF, DOCX" (file_type). */
@@ -206,6 +213,7 @@ export async function fileFailure(payload: BasePayload, formId: string, failure:
...(failure.file ? { file: failure.file } : {}), ...(failure.file ? { file: failure.file } : {}),
...(label ? { label } : {}), ...(label ? { label } : {}),
...(failure.max !== undefined ? { max: failure.max } : {}), ...(failure.max !== undefined ? { max: failure.max } : {}),
...(failure.optional ? { optional: true } : {}),
...(failure.types ? { types: failure.types } : {}), ...(failure.types ? { types: failure.types } : {}),
} }
} }
@@ -229,9 +237,17 @@ export async function findSubmitAttempt(payload: BasePayload, attemptKey: string
limit: 1, limit: 1,
where: { attemptKey: { equals: attemptKey } }, where: { attemptKey: { equals: attemptKey } },
} as never) } as never)
const doc = found.docs[0] as { filesDelivery?: string; id: number | string } | undefined const doc = found.docs[0] as { filesDelivery?: string; id: number | string; submissionFiles?: { field?: string; name?: string }[] } | undefined
if (!doc) {return null} if (!doc) {return null}
return doc.filesDelivery === 'failed' ? { reason: 'delivery', submissionId: doc.id, success: false } : { submissionId: doc.id, success: true } 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 { } catch {
return null return null
} }
@@ -260,6 +276,7 @@ export async function storeSubmission({
} & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> { } & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> {
const attachments = getFormAttachments(payload) const attachments = getFormAttachments(payload)
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
const fileNames = files.map((f) => ({ name: f.name, field: f.field }))
const text = (value: unknown) => const text = (value: unknown) =>
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails) // 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) value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
@@ -297,7 +314,17 @@ export async function storeSubmission({
} catch (err) { } catch (err) {
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`) payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
} }
return result.state === 'sent' ? { submissionId: submission.id, success: true } : { reason: 'delivery', submissionId: submission.id, success: false } 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) { } catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { reason: 'error', success: false } return { reason: 'error', success: false }
@@ -345,7 +372,7 @@ export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult
return storeSubmission({ attemptKey, formId, locale, payload, validation }) return storeSubmission({ attemptKey, formId, locale, payload, validation })
} }
if (hasFiles && !canCarryFiles(validation.form)) {return { reason: 'delivery', success: false }} 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 gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) })
const refused = await checkBufferedFiles(gate, files ?? {}) const refused = await checkBufferedFiles(gate, files ?? {})
if (refused) {return fileFailure(payload, formId, refused, locale)} if (refused) {return fileFailure(payload, formId, refused, locale)}
+12 -8
View File
@@ -12,11 +12,13 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
back: 'Back', back: 'Back',
consent: 'Accept the privacy policy to send the form.', consent: 'Accept the privacy policy to send the form.',
error: 'The form could not be sent. Please try again in a moment.', error: 'The form could not be sent. Please try again in a moment.',
fileCount: 'Attach at most {max} files in "{field}".', fileCount: 'Too many files in "{field}". Remove some: the limit is {max}.',
fileNotSent: 'We could not send your file. Try again, or send it by e-mail.', 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}', fileRemove: 'Remove {file}',
fileTooLarge: '"{file}" is too large. The limit is {max} MB.', fileTooLarge: 'The file "{file}" is too large. Choose a file of up to {max} MB.',
fileType: '"{file}" is not an accepted file type. Accepted: {types}.', fileType: 'The file "{file}" is in a format we do not accept. Choose one of: {types}.',
next: 'Next', next: 'Next',
notFound: 'This form is no longer available.', notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.', rateLimited: 'Too many attempts. Please wait a moment and try again.',
@@ -34,11 +36,13 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
back: 'Wstecz', back: 'Wstecz',
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.', consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.', error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
fileCount: 'W polu „{field}” można dodać najwyżej {max} plików.', fileCount: 'Za dużo plików w polu „{field}”. Usuń część: limit to {max}.',
fileNotSent: 'Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem.', 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}', fileRemove: 'Usuń {file}',
fileTooLarge: 'Plik „{file}” jest za duży. Limit to {max} MB.', fileTooLarge: 'Plik „{file}” jest za duży. Wybierz plik do {max} MB.',
fileType: 'Plik „{file}” ma niedozwolony typ. Dozwolone: {types}.', fileType: 'Plik „{file}” ma format, którego nie przyjmujemy. Wybierz jeden z: {types}.',
next: 'Dalej', next: 'Dalej',
notFound: 'Ten formularz nie jest już dostępny.', notFound: 'Ten formularz nie jest już dostępny.',
rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.', rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.',
@@ -34,6 +34,8 @@ export async function getNotificationTexts({
error: f.error || fb.error, error: f.error || fb.error,
fileCount: f.fileCount || fb.fileCount, fileCount: f.fileCount || fb.fileCount,
fileNotSent: f.fileNotSent || fb.fileNotSent, fileNotSent: f.fileNotSent || fb.fileNotSent,
fileOptional: f.fileOptional || fb.fileOptional,
fileRefused: f.fileRefused || fb.fileRefused,
fileRemove: f.fileRemove || fb.fileRemove, fileRemove: f.fileRemove || fb.fileRemove,
fileTooLarge: f.fileTooLarge || fb.fileTooLarge, fileTooLarge: f.fileTooLarge || fb.fileTooLarge,
fileType: f.fileType || fb.fileType, fileType: f.fileType || fb.fileType,
+26 -11
View File
@@ -5,10 +5,16 @@ import type { FormNotificationTexts } from './types.js'
* The texts resolveFormMessage needs. The File-field texts are optional, so an * 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). * object written before they existed still fits (the field or general text is used).
*/ */
export type FormMessageTexts = { [K in 'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType']?: string } & Omit< type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
FormNotificationTexts, export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit<FormNotificationTexts, FileTextKey>
'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType'
> /** 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} * Maps a submitForm result to the user-facing message, interpolating {field}
@@ -27,8 +33,11 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
switch (result.reason) { switch (result.reason) {
case 'consent': case 'consent':
return texts.consent return texts.consent
case 'delivery': case 'delivery': {
return texts.fileNotSent ?? texts.error // 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': case 'not_found':
return texts.notFound return texts.notFound
case 'rate_limited': case 'rate_limited':
@@ -38,15 +47,16 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
case 'validation': { case 'validation': {
// {field} → the label the visitor sees; no single field at fault → the generic error. // {field} → the label the visitor sees; no single field at fault → the generic error.
const field = result.label || result.field const field = result.label || result.field
const fill = (text: string) => // A problem with a file says so: which file, why, and what to do next.
text const fileText = texts[FILE_TEXT[result.kind ?? ''] ?? 'fileRemove']
if (FILE_TEXT[result.kind ?? ''] && fileText) {
const message = fileText
.replace('{file}', result.file ?? '') .replace('{file}', result.file ?? '')
.replace('{max}', result.max === undefined ? '' : String(result.max)) .replace('{max}', result.max === undefined ? '' : String(result.max))
.replace('{types}', result.types ?? '') .replace('{types}', result.types ?? '')
.replace('{field}', field ?? '') .replace('{field}', field ?? '')
if (result.kind === 'file_too_large' && texts.fileTooLarge) {return fill(texts.fileTooLarge)} return withoutFile(message, result.optional, texts)
if (result.kind === 'file_type' && texts.fileType) {return fill(texts.fileType)} }
if (result.kind === 'file_count' && texts.fileCount) {return fill(texts.fileCount)}
return field ? texts.validation.replace('{field}', field) : texts.error return field ? texts.validation.replace('{field}', field) : texts.error
} }
case 'error': case 'error':
@@ -54,3 +64,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
return texts.error 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
}
+8 -1
View File
@@ -12,8 +12,15 @@ export type FormNotificationTexts = {
error: string error: string
/** File field: too many files, with {field} and {max}. */ /** File field: too many files, with {field} and {max}. */
fileCount: string fileCount: string
/** File field: the e-mail with the file could not be sent — the visitor has to send it again. */ /** File field: the e-mail with the file could not be sent — with {file}; the visitor has to send it again. */
fileNotSent: string 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}. */ /** File field: the button that removes a selected file, with {file}. */
fileRemove: string fileRemove: string
/** File field: a file over the limit, with {file} and {max} (MB). */ /** File field: a file over the limit, with {file} and {max} (MB). */
+92 -33
View File
@@ -294,7 +294,7 @@ describe('2 · each allowed format: one submission, the file in the staff e-mail
const attachment = staff[0].attachments![0] const attachment = staff[0].attachments![0]
expect(Buffer.compare(attachment.content, data)).toBe(0) expect(Buffer.compare(attachment.content, data)).toBe(0)
expect(attachment.contentType).toBe(mime) expect(attachment.contentType).toBe(mime)
expect(attachment.filename.endsWith(`.${type}`)).toBe(true) 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(attachment.filename) // {{attachment}} → the readable name
expect(staff[0].html).toContain('not checked for viruses') expect(staff[0].html).toContain('not checked for viruses')
const customer = mails.filter((m) => m.to === '[email protected]') const customer = mails.filter((m) => m.to === '[email protected]')
@@ -313,45 +313,62 @@ describe('2 · each allowed format: one submission, the file in the staff e-mail
}) })
describe('3 · refused files leave no submission and send no e-mail', () => { describe('3 · refused files leave no submission and send no e-mail', () => {
const refused = async (files: Upload[], expected: RegExp, extra: Post = {}) => { // 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 before = await count()
const { body, status } = await post({ files, ...extra }) const { body, status } = await post({ files, ...extra })
expect(body.success).toBe(false) expect(body.success).toBe(false)
expect(status).toBe(422) expect(status).toBe(422)
expect(body.message).toMatch(expected) expect(body.message).toBe(expected)
expect(body).toMatchObject({ field: 'attachment', reason: 'validation' })
expect(await count()).toBe(before) expect(await count()).toBe(before)
expect(mails).toEqual([]) expect(mails).toEqual([])
} }
test('oversized: stopped while reading', async () => { test('oversized: stopped while reading', async () => {
await refused([{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 200_000) }], /"big\.pdf" is too large\. The limit is 1 MB\./) 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([]) expect(scanned).toEqual([])
}) })
test('mismatched: a program named .pdf, a PDF named .docx, an empty file', async () => { test('mismatched: a program named .pdf, a PDF named .docx, an empty file', async () => {
await refused([{ name: 'cv.pdf', data: EXE }], /"cv\.pdf" is not an accepted file type\. Accepted: PDF, DOC, DOCX\./) await refused([{ name: 'cv.pdf', data: EXE }], notAcceptable('cv.pdf'))
await refused([{ name: 'cv.docx', data: PDF }], /not an accepted file type/) await refused([{ name: 'cv.docx', data: PDF }], notAcceptable('cv.docx'))
await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], /not an accepted file type|too large/) await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], notAcceptable('cv.pdf'))
}) })
test('unsupported and dangerous names: other type, program, double extension, archive, macro-enabled Office', async () => { 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]) }], /not an accepted file type/) 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: 'cv.exe', data: EXE }], /not an accepted file type/) await refused([{ name: 'notes.txt', data: Buffer.from('hello') }], wrongFormat('notes.txt'))
await refused([{ name: 'cv.pdf.exe', data: EXE }], /not an accepted file type/) await refused([{ name: 'cv', data: PDF }], wrongFormat('cv'))
await refused([{ name: 'cv.exe.pdf', data: PDF }], /not an accepted file type/) })
await refused([{ name: 'cv.pdf.docx', data: DOCX }], /not an accepted file type/)
await refused([{ name: 'cv.zip', data: ARCHIVE }], /not an accepted file type/) test('refused files: program, double extension, archive, macro-enabled Office — the message says the file was refused', async () => {
await refused([{ name: 'cv.docm', data: DOCX_MACRO }], /not an accepted file type/) 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 () => { 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 }], /not an accepted file type/) await refused([{ name: 'cv.docx', data: DOCX_MACRO }], notAcceptable('cv.docx'))
await refused([{ name: 'cv.doc', data: DOC_MACRO }], /not an accepted file type/) await refused([{ name: 'cv.doc', data: DOC_MACRO }], notAcceptable('cv.doc'))
await refused([{ name: 'cv.docx', data: ARCHIVE }], /not an accepted file type/) // a ZIP that is not a Word file 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 () => { 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 }], /Attach at most 1 files in "Attachment \(optional\)"\./) 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 before = await count()
const { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: '[email protected]' } }) const { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: '[email protected]' } })
expect(body.success).toBe(false) expect(body.success).toBe(false)
@@ -370,7 +387,7 @@ describe('3 · refused files leave no submission and send no e-mail', () => {
test('the antivirus hook can refuse a file that passed everything else', async () => { test('the antivirus hook can refuse a file that passed everything else', async () => {
scanVerdict = false scanVerdict = false
await refused([{ name: 'cv.pdf', data: PDF }], /not an accepted file type/) await refused([{ name: 'cv.pdf', data: PDF }], notAcceptable('cv.pdf'))
expect(scanned).toHaveLength(1) expect(scanned).toHaveLength(1)
}) })
@@ -501,7 +518,14 @@ describe('6 · failed send, retry, repeated request', () => {
const before = await count() const before = await count()
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] }) const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
expect(status).toBe(502) expect(status).toBe(502)
expect(body).toMatchObject({ message: 'We could not send your file. Try again, or send it by e-mail.', reason: 'delivery', success: false }) // 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)! const stored = (await submissions()).at(-1)!
expect(await count()).toBe(before + 1) expect(await count()).toBe(before + 1)
@@ -527,7 +551,8 @@ describe('6 · failed send, retry, repeated request', () => {
test('an adapter that throws is a failed send too', async () => { test('an adapter that throws is a failed send too', async () => {
mailMode = 'throw' mailMode = 'throw'
const { body } = await post({ files: [{ name: 'cv.pdf', data: PDF }] }) const { body } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
expect(body.reason).toBe('delivery') expect(body).toMatchObject({ field: 'attachment', reason: 'delivery' })
expect(body.message).not.toMatch(/ECONNREFUSED/)
expect((await submissions()).at(-1)!.filesDelivery).toBe('failed') expect((await submissions()).at(-1)!.filesDelivery).toBe('failed')
}) })
@@ -564,7 +589,8 @@ describe('6 · failed send, retry, repeated request', () => {
mails.length = 0 mails.length = 0
mailMode = 'ok' mailMode = 'ok'
const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }) const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] })
expect(again.body.reason).toBe('delivery') 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(await count()).toBe(before)
expect(mails).toEqual([]) expect(mails).toEqual([])
}) })
@@ -572,16 +598,35 @@ describe('6 · failed send, retry, repeated request', () => {
describe('7 · languages, the panel, limits', () => { describe('7 · languages, the panel, limits', () => {
test('messages follow the page language: Polish and English defaults, German and Dutch from the panel', async () => { 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: { fileTooLarge: 'Die Datei „{file}“ ist zu groß. Maximal {max} MB.' } } as never, locale: 'de' }) await payload.updateGlobal({
await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileTooLarge: 'Het bestand "{file}" is te groot. Maximaal {max} MB.' } } as never, locale: 'nl' }) 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) }] 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. Limit to 1 MB.') 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('"big.pdf" is too large. The limit is 1 MB.') 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ß. Maximal 1 MB.') 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. Maximaal 1 MB.') 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.')
// The field's label comes from the panel in the page language.
const two = [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }] // Every file message in Polish too; the field's label comes from the panel in the page language.
expect((await post({ files: two, locale: 'pl' })).body.message).toBe('W polu „Załącznik (opcjonalnie)” można dodać najwyżej 1 plików.') 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 () => { test('the form the browser gets carries the limits that really apply, and where to post', async () => {
@@ -632,6 +677,13 @@ describe('7 · languages, the panel, limits', () => {
expect(none.body).toMatchObject({ field: 'cv', reason: 'validation', success: false }) 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 submitForm({ data: {}, formId: String(required.id), maxPerMinute: 0, payload })).toMatchObject({ field: 'cv', kind: 'required' })
expect(await count()).toBe(before) 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: {} }) const ok = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
expect(ok.body.success).toBe(true) expect(ok.body.success).toBe(true)
}) })
@@ -640,7 +692,14 @@ describe('7 · languages, the panel, limits', () => {
const good = await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: PDF }] }, formId, locale: 'en', maxPerMinute: 0, payload }) 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(good.success).toBe(true)
expect(withFile()).toHaveLength(1) expect(withFile()).toHaveLength(1)
expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ kind: 'file_type' }) 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' })
}) })
}) })
+39 -13
View File
@@ -175,12 +175,15 @@ describe('the form in the browser', () => {
test('instant checks use the same messages as the server', () => { test('instant checks use the same messages as the server', () => {
const pdf = (name: string, size: number) => ({ name, size }) 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', MB)], texts)).toBeUndefined()
expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], texts)).toBe('"cv.pdf" is too large. The limit is 2 MB.') 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('"cv.png" is not an accepted file type. Accepted: PDF, DOCX.') 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('Attach at most 2 files in "Attachment (optional)".') 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('"b.pdf" is too large. The limit is 3 MB.') 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. Limit to 2 MB.') 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. // 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)".') expect(fileFieldError(field, [pdf('cv.png', 10)], { validation: 'Check the field "{field}".' })).toBe('Check the field "Attachment (optional)".')
}) })
@@ -189,7 +192,7 @@ describe('the form in the browser', () => {
expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] }) expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] })
expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({}) expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({})
expect(validateBuilderFields([{ ...field, required: true }], { attachment: [] }, texts)).toEqual({ attachment: 'Check the field "Attachment (optional)".' }) 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('not an accepted file type') 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', () => { test('markup: a native file input with a label, help text tied to it, accept and multiple', () => {
@@ -225,15 +228,38 @@ describe('messages and helpers', () => {
const texts = NOTIFICATION_FALLBACK.form const texts = NOTIFICATION_FALLBACK.form
test('every file outcome has its own text; the placeholders are filled', () => { test('every file outcome has its own text; the placeholders are filled', () => {
const fail = (extra: Record<string, unknown>) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, texts) const fail = (extra: Record<string, unknown>, t = texts) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, t)
expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 })).toBe('"a.pdf" is too large. The limit is 10 MB.') // English: which file, why, what to do
expect(fail({ file: 'a.exe', kind: 'file_type', types: 'PDF, DOCX' })).toBe('"a.exe" is not an accepted file type. Accepted: PDF, DOCX.') 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({ kind: 'file_count', max: 2 })).toBe('Attach at most 2 files in "CV".') 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: 'required' })).toBe('Check the field "CV".')
expect(resolveFormMessage({ reason: 'delivery', success: false }, texts)).toBe('We could not send your file. Try again, or send it by e-mail.') expect(fail({ kind: 'invalid_format', optional: true })).toBe('Check the field "CV".')
expect(resolveFormMessage({ reason: 'delivery', success: false }, NOTIFICATION_FALLBACK_PL.form)).toBe('Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem.') 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. // Texts written before the file keys existed fall back to the general ones.
const { fileCount: _a, fileNotSent: _b, fileRemove: _c, fileTooLarge: _d, fileType: _e, ...old } = texts 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({ 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".') expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', kind: 'file_too_large', max: 1, reason: 'validation', success: false }, old)).toBe('Check the field "cv".')
}) })