diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index dd8bec4..a177cf8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -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 addressed with a placeholder (the confirmation to the visitor) never carries it. `{{field}}`, `{{*}}` and
`{{*: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
(double click, a resend) sends nothing twice.
- Browser: `RenderForm` / `BuilderForm` render a native file input with help text, the list of picked files and
a "Remove" button; `useBuilderForm` gains `getFileProps`, `getFiles`, `removeFile`, `helpId`,
`getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`.
- - New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileCount`, `fileNotSent`, `fileRemove`),
- English and Polish defaults.
+ - New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
+ `fileOptional`, `fileRemove`), English and Polish defaults.
- New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`,
`mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`);
`splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' |
- 'file_type' | 'file_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.
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`
diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md
index 275755d..c25aad9 100644
--- a/docs/agent/skills/ipal-form/SKILL.md
+++ b/docs/agent/skills/ipal-form/SKILL.md
@@ -103,8 +103,10 @@ Never build this by hand (your own ``, upload route or upload
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.
+5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
+ `fileOptional`, `fileRemove`) — English and Polish defaults; fill every other language of the site. Each tells
+ the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
+ optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
@@ -112,8 +114,8 @@ Never build this by hand (your own ``, upload route or upload
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**.
+files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
+file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
@@ -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;
- [ ] 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;
+ a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
+ still there; a file over the limit → "…is too large. Choose a file of up to N MB." before sending; each
+ message in every language of the site; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -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`) |
| "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") |
+| "We could not send the file …", submission says *Not sent* | the mail server refused the message (size limit: see the note on the submission), or Graph without `Mail.ReadWrite` and no SMTP settings → Test e-mail with the 10 MB file; lower the field's maximum or fix the transport (email.md "Attachments") |
| the form with a File field cannot be saved ("Add an e-mail with a fixed recipient…") | every e-mail of the form is addressed with a placeholder → add the company notification with a fixed address |
| the File field does not appear in the builder | `forms.attachments` is off, or `forms.fields.file: false` |
| a file is refused although its type is ticked | the content does not match the extension, the name has a second extension (`cv.pdf.docx`), the document has macros, or it is password-protected |
diff --git a/docs/forms.md b/docs/forms.md
index 256d97a..91b2e58 100644
--- a/docs/forms.md
+++ b/docs/forms.md
@@ -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
line "…was not checked for viruses"; the confirmation e-mail to the visitor has no file; Form Submissions shows
**Files** (name, type, size) and **File delivery: Handed to the mail server**. Rename a `.exe` to `.pdf` and submit →
-the 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`)
@@ -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 **visitor** sees an error — Form messages → **File not sent** ("We could not send your file. Try again, or
- send it by e-mail.") — keeps their answers and the selected file, and can try again. No confirmation e-mail goes out;
+- the **visitor** sees an error **at the File field** — Form messages → **File not sent** ("We could not send the
+ file "cv.pdf". Choose a smaller file or another format and try again.") — keeps their answers and the selected
+ file, and can try again. The mail server's own words never reach the visitor. No confirmation e-mail goes out;
- **staff** get the notification once more **without** the file: "The visitor attached a file: … but it could not
be sent. Ask them to send it again.";
- the **submission** is stored and marked **File delivery: Not sent**, with a note (the mail server's reason). The
@@ -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
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`,
-`max`, `types`), `kind: 'required'` for a required File field without a file, and `reason: 'delivery'` when the
-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)).
+**When a submission fails because of the file, the message says it is the file, why, and what to do** — and it
+shows at the File field (the result carries `field`). Everything the visitor typed stays in the form.
+
+| Problem | Code | Text (Form messages → Files) | English default |
+|---|---|---|---|
+| too large | `kind: 'file_too_large'` (`file`, `max`) | `fileTooLarge` | The file "cv.pdf" is too large. Choose a file of up to 10 MB. |
+| a format the field does not take | `kind: 'file_type'` (`file`, `types`) | `fileType` | The file "cv.txt" is in a format we do not accept. Choose one of: PDF, DOC, DOCX. |
+| refused: a program, an archive, macros, a doubled extension, content that does not match the type, the scanner said no | `kind: 'file_refused'` (`file`, `types`) | `fileRefused` | The file "cv.docx" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOC, DOCX). |
+| too many files | `kind: 'file_count'` (`max`) | `fileCount` | Too many files in "Attachment". Remove some: the limit is 1. |
+| the e-mail with the file could not be sent | `reason: 'delivery'` (`field`, `file`) | `fileNotSent` | We could not send the file "cv.pdf". Choose a smaller file or another format and try again. |
+
+- On a File field that is **not required**, every one of these ends with `fileOptional` — "You can also send the
+ form without the file." (the result carries `optional: true`).
+- A required File field left empty is `kind: 'required'` → the ordinary field text ("Check the field …").
+- A failure that is **not** about the file keeps its own text: consent, a field error, the rate limit, the
+ general error.
+- The texts are in the panel like every form message: Form messages → **Files**, per language, with English and
+ Polish defaults — fill the other languages of the site ([notifications.md](./notifications.md)). The browser
+ shows the size, format and count messages before anything is sent; the server answers with the same texts.
### Your own markup
@@ -556,8 +572,8 @@ type SubmitFormResult =
| { success: true; submissionId: string | number }
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
- | { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_count'; file?: string; max?: number; types?: string }
- | { success: false; reason: 'delivery'; submissionId?: string | number } // the file could not be e-mailed
+ | { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'; file?: string; max?: number; types?: string; optional?: boolean }
+ | { success: false; reason: 'delivery'; field?: string; file?: string; optional?: boolean; submissionId?: string | number } // the file could not be e-mailed
| { success: false; reason: 'not_found' }
| { success: false; reason: 'consent'; field?: string }
| { success: false; reason: 'error' }
diff --git a/docs/notifications.md b/docs/notifications.md
index 6eaf347..e3cc599 100644
--- a/docs/notifications.md
+++ b/docs/notifications.md
@@ -61,17 +61,22 @@ per language.
With `forms.attachments` ([forms.md](./forms.md) "Files") the **Files** group of Form messages holds:
+Each one tells the visitor that the problem is the file, why, and what to do next.
+
| Key | Placeholders | English default |
|---|---|---|
-| `fileTooLarge` | `{file}`, `{max}` (MB) | `"{file}" is too large. The limit is {max} MB.` |
-| `fileType` | `{file}`, `{types}` | `"{file}" is not an accepted file type. Accepted: {types}.` |
-| `fileCount` | `{field}`, `{max}` | `Attach at most {max} files in "{field}".` |
-| `fileNotSent` | — | `We could not send your file. Try again, or send it by e-mail.` |
+| `fileTooLarge` | `{file}`, `{max}` (MB) | `The file "{file}" is too large. Choose a file of up to {max} MB.` |
+| `fileType` | `{file}`, `{types}` | `The file "{file}" is in a format we do not accept. Choose one of: {types}.` |
+| `fileRefused` | `{file}`, `{types}` | `The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).` |
+| `fileCount` | `{field}`, `{max}` | `Too many files in "{field}". Remove some: the limit is {max}.` |
+| `fileNotSent` | `{file}` | `We could not send the file "{file}". Choose a smaller file or another format and try again.` |
+| `fileOptional` | — | `You can also send the form without the file.` — added to the five above when the File field is not required |
| `fileRemove` | `{file}` | `Remove {file}` |
-Polish defaults ship too; any other language is filled in the panel. `resolveFormMessage` maps
-`kind: 'file_too_large' | 'file_type' | 'file_count'` and `reason: 'delivery'` to them; a texts object without these
-keys falls back to `validation` / `error`.
+Polish defaults ship too; any other language is filled in the panel (an empty field falls back to English there).
+`resolveFormMessage` maps `kind: 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'` and
+`reason: 'delivery'` to them and appends `fileOptional` when the result says `optional`; a texts object without
+these keys falls back to `validation` / `error`. The result carries `field`, so the message shows at the File field.
## {field} interpolation
diff --git a/reference/e2e/smoke.spec.ts b/reference/e2e/smoke.spec.ts
index ed402f0..af7b944 100644
--- a/reference/e2e/smoke.spec.ts
+++ b/reference/e2e/smoke.spec.ts
@@ -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
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
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
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"]')
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 })
+ // 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('smoke@example.com')
+ await form.locator('button[type="submit"]').click() // Next
expect(sink.messages).toHaveLength(0)
// the real file (the field takes several: remove the refused one first)
diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts
index 6702349..7993526 100644
--- a/src/globals/Notifications/fields.ts
+++ b/src/globals/Notifications/fields.ts
@@ -69,11 +69,20 @@ export const notificationsFields: Field[] = [
formText('fileType', { en: 'Wrong file type', pl: 'Niedozwolony typ pliku' }, {
description: { en: 'Use {file} for the file name and {types} for the accepted types.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {types} — dozwolone typy.' },
}),
+ formText('fileRefused', { en: 'File refused', pl: 'Plik odrzucony' }, {
+ description: {
+ en: 'For a program, an archive, macros or content that does not match; use {file} and {types}.',
+ pl: 'Dla programu, archiwum, makr lub niezgodnej zawartości; użyj {file} i {types}.',
+ },
+ }),
formText('fileCount', { en: 'Too many files', pl: 'Za dużo plików' }, {
description: { en: 'Use {field} for the field label and {max} for the limit.', pl: 'Użyj {field}, aby wstawić etykietę pola, i {max} — limit.' },
}),
formText('fileNotSent', { en: 'File not sent', pl: 'Plik niewysłany' }, {
- description: { en: 'Shown when the file could not be sent by e-mail.', 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' }, {
description: { en: 'Use {file} for the file name.', pl: 'Użyj {file}, aby wstawić nazwę pliku.' },
diff --git a/src/modules/forms/attachments/fileChecks.ts b/src/modules/forms/attachments/fileChecks.ts
index 1c35d28..d81026e 100644
--- a/src/modules/forms/attachments/fileChecks.ts
+++ b/src/modules/forms/attachments/fileChecks.ts
@@ -145,26 +145,29 @@ export type FileRefusal =
/**
* 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
- * ("cv.pdf.exe", "cv.exe.pdf") unless the project allowed it.
+ * one of the allowed types (else `type`: simply another format), and NO
+ * extension of the name may be a risky one ("cv.pdf.exe", "cv.exe.pdf") unless
+ * the project allowed it, nor a second known one ("cv.pdf.docx") — else `refused`.
*/
export function matchFileType(
name: string,
allowed: readonly string[],
types: Record,
risky: ReadonlySet,
-): { key: string; type: FormFileType } | { refused: 'name' } {
+): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
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.
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) {
const type = types[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. */
diff --git a/src/modules/forms/attachments/fileGate.ts b/src/modules/forms/attachments/fileGate.ts
index bb24524..dee2be3 100644
--- a/src/modules/forms/attachments/fileGate.ts
+++ b/src/modules/forms/attachments/fileGate.ts
@@ -22,10 +22,19 @@ export type FormFileFailure = {
field: string
/** The file's name as the visitor knows it (cleaned of control characters). */
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. */
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
}
@@ -79,34 +88,35 @@ export function createFileGate({
const file = displayName(rawName)
const count = (counts.get(fieldName) ?? 0) + 1
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 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)
- 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 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
return {
slot: {
checkStart: (head) => {
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
checked = true
- return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? typeFailure : null
+ return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? refusedFailure : null
},
maxBytes,
tooLarge,
},
- token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure },
+ token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
}
}
const finish = async (token: BeginToken, data: Uint8Array): Promise => {
if (data.length > token.maxBytes) {return token.tooLarge()}
const type = options.types[token.key]
- if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.typeFailure}
+ if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.refusedFailure}
const file: AcceptedFormFile = {
name: safeFileName(token.rawName, type.extensions[0]),
type: token.key,
@@ -118,9 +128,9 @@ export function createFileGate({
if (options.scan) {
try {
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
- if (!verdict?.ok) {return token.typeFailure}
+ if (!verdict?.ok) {return token.refusedFailure}
} catch {
- return token.typeFailure
+ return token.refusedFailure
}
}
total += data.length
@@ -145,8 +155,8 @@ type BeginToken = {
key: string
maxBytes: number
rawName: string
+ refusedFailure: FormFileFailure
tooLarge: () => FormFileFailure
- typeFailure: FormFileFailure
}
export type FileGate = ReturnType
diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts
index 7da7054..5383f36 100644
--- a/src/modules/forms/attachments/submitHandler.ts
+++ b/src/modules/forms/attachments/submitHandler.ts
@@ -132,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise {
const source = Readable.fromWeb(req.body as never)
const parser = busboy({
+ // browsers send file names as UTF-8 ("Życiorys.pdf"); the parser's default would read them as Latin-1
+ defParamCharset: 'utf8',
headers: { 'content-type': contentType },
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
})
diff --git a/src/modules/forms/builderLogic.ts b/src/modules/forms/builderLogic.ts
index d62b451..1bafadf 100644
--- a/src/modules/forms/builderLogic.ts
+++ b/src/modules/forms/builderLogic.ts
@@ -131,22 +131,25 @@ export function fileFieldRules(field: BuilderField): Required
export function fileFieldError(
field: BuilderField,
files: readonly BuilderFile[],
- texts: Pick,
+ texts: Pick,
): string | undefined {
const rules = fileFieldRules(field)
const label = field.label || field.name || ''
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) {
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) {
- 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) {
- 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
}
@@ -170,7 +173,7 @@ const isBlank = isBlankValue
export function validateBuilderFields(
fields: BuilderField[],
values: Record,
- texts: Pick,
+ texts: Pick,
): Record {
const errors: Record = {}
for (const f of inputFields(fields)) {
diff --git a/src/modules/forms/builderTypes.ts b/src/modules/forms/builderTypes.ts
index 7ec7ce4..8fded69 100644
--- a/src/modules/forms/builderTypes.ts
+++ b/src/modules/forms/builderTypes.ts
@@ -84,6 +84,7 @@ export type BuilderFormTexts = {
error?: string
/** File field — see FormNotificationTexts. */
fileCount?: string
+ fileOptional?: string
fileRemove?: string
fileTooLarge?: string
fileType?: string
diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts
index 3c63c70..bf9f5b7 100644
--- a/src/modules/forms/submitForm.ts
+++ b/src/modules/forms/submitForm.ts
@@ -86,8 +86,13 @@ export type SubmitFailure =
/**
* The file could not be handed to the mail server (or the form has no
* e-mail that may carry it). The file is gone — the visitor must send it
- * again. `submissionId`: the stored attempt, marked "Not sent".
+ * again. `submissionId`: the stored attempt, marked "Not sent". `field`
+ * and `file`: the File field and the file name(s), so the message shows
+ * at the field and names the file; `optional`: the field is not required.
*/
+ field?: string
+ file?: string
+ optional?: boolean
reason: 'delivery'
submissionId?: number | string
success: false
@@ -95,14 +100,16 @@ export type SubmitFailure =
| {
/** The offending field's name, when one field is at fault. */
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
/** 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. */
label?: string
/** The limit behind file_too_large (MB) or file_count (files). */
max?: number
+ /** A file problem on a field that is not required — the form can be sent without the file. */
+ optional?: boolean
reason: 'validation'
success: false
/** Accepted types, "PDF, DOCX" (file_type). */
@@ -206,6 +213,7 @@ export async function fileFailure(payload: BasePayload, formId: string, failure:
...(failure.file ? { file: failure.file } : {}),
...(label ? { label } : {}),
...(failure.max !== undefined ? { max: failure.max } : {}),
+ ...(failure.optional ? { optional: true } : {}),
...(failure.types ? { types: failure.types } : {}),
}
}
@@ -229,9 +237,17 @@ export async function findSubmitAttempt(payload: BasePayload, attemptKey: string
limit: 1,
where: { attemptKey: { equals: attemptKey } },
} 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}
- 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 {
return null
}
@@ -260,6 +276,7 @@ export async function storeSubmission({
} & Pick): Promise {
const attachments = getFormAttachments(payload)
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
+ const fileNames = files.map((f) => ({ name: f.name, field: f.field }))
const text = (value: unknown) =>
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
@@ -297,7 +314,17 @@ export async function storeSubmission({
} catch (err) {
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) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { reason: 'error', success: false }
@@ -345,7 +372,7 @@ export async function submitForm(args: SubmitFormArgs): Promise
+type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
+export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit
+
+/** The texts of the File field problems, by result code. */
+const FILE_TEXT: Partial> = {
+ file_count: 'fileCount',
+ file_refused: 'fileRefused',
+ file_too_large: 'fileTooLarge',
+ file_type: 'fileType',
+}
/**
* 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) {
case 'consent':
return texts.consent
- case 'delivery':
- return texts.fileNotSent ?? texts.error
+ case 'delivery': {
+ // The file could not be e-mailed: say it is the file (at its field), never the mail server's own words.
+ if (!texts.fileNotSent) {return texts.error}
+ return withoutFile(texts.fileNotSent.replace('{file}', result.file ?? ''), result.optional, texts)
+ }
case 'not_found':
return texts.notFound
case 'rate_limited':
@@ -38,15 +47,16 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
case 'validation': {
// {field} → the label the visitor sees; no single field at fault → the generic error.
const field = result.label || result.field
- const fill = (text: string) =>
- text
+ // A problem with a file says so: which file, why, and what to do next.
+ const fileText = texts[FILE_TEXT[result.kind ?? ''] ?? 'fileRemove']
+ if (FILE_TEXT[result.kind ?? ''] && fileText) {
+ const message = fileText
.replace('{file}', result.file ?? '')
.replace('{max}', result.max === undefined ? '' : String(result.max))
.replace('{types}', result.types ?? '')
.replace('{field}', field ?? '')
- if (result.kind === 'file_too_large' && texts.fileTooLarge) {return fill(texts.fileTooLarge)}
- if (result.kind === 'file_type' && texts.fileType) {return fill(texts.fileType)}
- if (result.kind === 'file_count' && texts.fileCount) {return fill(texts.fileCount)}
+ return withoutFile(message, result.optional, texts)
+ }
return field ? texts.validation.replace('{field}', field) : texts.error
}
case 'error':
@@ -54,3 +64,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
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
+}
diff --git a/src/modules/notifications/types.ts b/src/modules/notifications/types.ts
index 5d8b846..3025837 100644
--- a/src/modules/notifications/types.ts
+++ b/src/modules/notifications/types.ts
@@ -12,8 +12,15 @@ export type FormNotificationTexts = {
error: string
/** File field: too many files, with {field} and {max}. */
fileCount: string
- /** File field: the e-mail with the file could not be sent — 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
+ /** File field: added to a file message when the field is not required ("…send the form without the file"). */
+ fileOptional: string
+ /**
+ * File field: the format is allowed but this file is not — its content does not match, it has macros, it is
+ * a program or an archive. With {file} and {types}.
+ */
+ fileRefused: string
/** File field: the button that removes a selected file, with {file}. */
fileRemove: string
/** File field: a file over the limit, with {file} and {max} (MB). */
diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts
index 9463517..953fff2 100644
--- a/test/formAttachments.test.ts
+++ b/test/formAttachments.test.ts
@@ -294,7 +294,7 @@ describe('2 · each allowed format: one submission, the file in the staff e-mail
const attachment = staff[0].attachments![0]
expect(Buffer.compare(attachment.content, data)).toBe(0)
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('not checked for viruses')
const customer = mails.filter((m) => m.to === 'jan@example.com')
@@ -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', () => {
- 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 { body, status } = await post({ files, ...extra })
expect(body.success).toBe(false)
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(mails).toEqual([])
}
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([])
})
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.docx', data: PDF }], /not an accepted file type/)
- await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], /not an accepted file type|too large/)
+ await refused([{ name: 'cv.pdf', data: EXE }], notAcceptable('cv.pdf'))
+ await refused([{ name: 'cv.docx', data: PDF }], notAcceptable('cv.docx'))
+ await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], notAcceptable('cv.pdf'))
})
- test('unsupported and dangerous names: other type, program, double extension, archive, macro-enabled Office', 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: 'cv.exe', data: EXE }], /not an accepted file type/)
- await refused([{ name: 'cv.pdf.exe', data: EXE }], /not an accepted file type/)
- 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/)
- await refused([{ name: 'cv.docm', data: DOCX_MACRO }], /not an accepted file type/)
+ test('another format: the message names the formats the field takes', async () => {
+ await refused([{ name: 'photo.png', data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }], wrongFormat('photo.png'))
+ await refused([{ name: 'notes.txt', data: Buffer.from('hello') }], wrongFormat('notes.txt'))
+ await refused([{ name: 'cv', data: PDF }], wrongFormat('cv'))
+ })
+
+ test('refused files: program, double extension, archive, macro-enabled Office — the message says the file was refused', async () => {
+ await refused([{ name: 'cv.exe', data: EXE }], notAcceptable('cv.exe'))
+ await refused([{ name: 'cv.pdf.exe', data: EXE }], notAcceptable('cv.pdf.exe'))
+ await refused([{ name: 'cv.exe.pdf', data: PDF }], notAcceptable('cv.exe.pdf'))
+ await refused([{ name: 'cv.pdf.docx', data: DOCX }], notAcceptable('cv.pdf.docx'))
+ await refused([{ name: 'cv.zip', data: ARCHIVE }], notAcceptable('cv.zip'))
+ await refused([{ name: 'cv.docm', data: DOCX_MACRO }], notAcceptable('cv.docm'))
})
test('the right container with macros inside: DOCX with a macro project, DOC with a macro storage', async () => {
- await refused([{ name: 'cv.docx', data: DOCX_MACRO }], /not an accepted file type/)
- await refused([{ name: 'cv.doc', data: DOC_MACRO }], /not an accepted file type/)
- 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: DOCX_MACRO }], notAcceptable('cv.docx'))
+ await refused([{ name: 'cv.doc', data: DOC_MACRO }], notAcceptable('cv.doc'))
+ await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file
})
test('extra files: more than the field allows, a file under a key that is no File field', async () => {
- await refused([{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }], /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 { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: 'jan@example.com' } })
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 () => {
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)
})
@@ -501,7 +518,14 @@ describe('6 · failed send, retry, repeated request', () => {
const before = await count()
const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] })
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)!
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 () => {
mailMode = 'throw'
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')
})
@@ -564,7 +589,8 @@ describe('6 · failed send, retry, repeated request', () => {
mails.length = 0
mailMode = 'ok'
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(mails).toEqual([])
})
@@ -572,16 +598,35 @@ describe('6 · failed send, retry, repeated request', () => {
describe('7 · languages, the panel, limits', () => {
test('messages follow the page language: Polish and English defaults, German and Dutch from the panel', async () => {
- await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileTooLarge: 'Die Datei „{file}“ ist zu groß. Maximal {max} MB.' } } as never, locale: 'de' })
- await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileTooLarge: 'Het bestand "{file}" is te groot. Maximaal {max} MB.' } } as never, locale: 'nl' })
+ await payload.updateGlobal({
+ slug: 'notifications' as never,
+ data: { form: { fileOptional: 'Sie können das Formular auch ohne Datei senden.', fileTooLarge: 'Die Datei „{file}“ ist zu groß. Wählen Sie eine Datei bis {max} MB.' } } as never,
+ locale: 'de',
+ })
+ await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileOptional: 'U kunt het formulier ook zonder bestand versturen.', fileTooLarge: 'Het bestand "{file}" is te groot. Kies een bestand tot {max} MB.' } } as never, locale: 'nl' })
const big = [{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10) }]
- expect((await post({ files: big, locale: 'pl' })).body.message).toBe('Plik „big.pdf” jest za duży. Limit to 1 MB.')
- 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: 'de' })).body.message).toBe('Die Datei „big.pdf“ ist zu groß. Maximal 1 MB.')
- expect((await post({ files: big, locale: 'nl' })).body.message).toBe('Het bestand "big.pdf" is te groot. Maximaal 1 MB.')
- // The field's label comes from the panel in the page language.
- const two = [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }]
- expect((await post({ files: two, locale: 'pl' })).body.message).toBe('W polu „Załącznik (opcjonalnie)” można dodać najwyżej 1 plików.')
+ expect((await post({ files: big, locale: 'pl' })).body.message).toBe('Plik „big.pdf” jest za duży. Wybierz plik do 1 MB. Możesz też wysłać formularz bez pliku.')
+ expect((await post({ files: big, locale: 'en' })).body.message).toBe('The file "big.pdf" is too large. Choose a file of up to 1 MB. You can also send the form without the file.')
+ expect((await post({ files: big, locale: 'de' })).body.message).toBe('Die Datei „big.pdf“ ist zu groß. Wählen Sie eine Datei bis 1 MB. Sie können das Formular auch ohne Datei senden.')
+ expect((await post({ files: big, locale: 'nl' })).body.message).toBe('Het bestand "big.pdf" is te groot. Kies een bestand tot 1 MB. U kunt het formulier ook zonder bestand versturen.')
+
+ // Every file message in Polish too; the field's label comes from the panel in the page language.
+ const pl = async (files: Upload[]) => (await post({ files, locale: 'pl' })).body.message
+ expect(await pl([{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }])).toBe('Za dużo plików w polu „Załącznik (opcjonalnie)”. Usuń część: limit to 1. Możesz też wysłać formularz bez pliku.')
+ expect(await pl([{ name: 'zdjęcie.png', data: Buffer.alloc(32, 1) }])).toBe('Plik „zdjęcie.png” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOC, DOCX. Możesz też wysłać formularz bez pliku.')
+ expect(await pl([{ name: 'cv.pdf', data: EXE }])).toBe(
+ 'Plik „cv.pdf” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOC, DOCX). Możesz też wysłać formularz bez pliku.',
+ )
+ mailMode = 'refuse'
+ expect(await pl([{ name: 'cv.pdf', data: PDF }])).toBe('Nie udało się wysłać pliku „cv.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie. Możesz też wysłać formularz bez pliku.')
+ mailMode = 'ok'
+
+ // A failure that is not about the file keeps its own message — no file wording.
+ const consent = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { ...answers, consent: false } })).body
+ expect(consent).toMatchObject({ field: 'consent', reason: 'consent' })
+ expect(consent.message).not.toMatch(/file/i)
+ const missing = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { consent: true, email: 'jan@example.com' } })).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 () => {
@@ -632,6 +677,13 @@ describe('7 · languages, the panel, limits', () => {
expect(none.body).toMatchObject({ field: 'cv', reason: 'validation', success: false })
expect(await submitForm({ data: {}, formId: String(required.id), maxPerMinute: 0, payload })).toMatchObject({ field: 'cv', kind: 'required' })
expect(await count()).toBe(before)
+ // A required field: the same messages, without "send the form without the file".
+ const big = await post({ files: [{ name: 'cv.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10), field: 'cv' }], form: String(required.id), values: {} })
+ expect(big.body).toMatchObject({ field: 'cv', message: 'The file "cv.pdf" is too large. Choose a file of up to 1 MB.' })
+ mailMode = 'refuse'
+ const unsent = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
+ expect(unsent.body).toMatchObject({ field: 'cv', message: 'We could not send the file "cv.pdf". Choose a smaller file or another format and try again.' })
+ mailMode = 'ok'
const ok = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} })
expect(ok.body.success).toBe(true)
})
@@ -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 })
expect(good.success).toBe(true)
expect(withFile()).toHaveLength(1)
- expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ 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' })
})
})
diff --git a/test/formFileField.test.ts b/test/formFileField.test.ts
index 5990a1b..59f1923 100644
--- a/test/formFileField.test.ts
+++ b/test/formFileField.test.ts
@@ -175,12 +175,15 @@ describe('the form in the browser', () => {
test('instant checks use the same messages as the server', () => {
const pdf = (name: string, size: number) => ({ name, size })
+ const hint = ' You can also send the form without the file.'
expect(fileFieldError(field, [pdf('cv.pdf', MB)], texts)).toBeUndefined()
- expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], texts)).toBe('"cv.pdf" is too large. The limit is 2 MB.')
- expect(fileFieldError(field, [pdf('cv.png', 10)], texts)).toBe('"cv.png" is not an accepted file type. Accepted: PDF, DOCX.')
- 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.6 * MB), pdf('b.pdf', 1.6 * MB)], texts)).toBe('"b.pdf" is too large. The limit is 3 MB.')
- 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)], texts)).toBe(`The file "cv.pdf" is too large. Choose a file of up to 2 MB.${hint}`)
+ expect(fileFieldError(field, [pdf('cv.png', 10)], texts)).toBe(`The file "cv.png" is in a format we do not accept. Choose one of: PDF, DOCX.${hint}`)
+ expect(fileFieldError(field, [pdf('a.pdf', 1), pdf('b.pdf', 1), pdf('c.pdf', 1)], texts)).toBe(`Too many files in "Attachment (optional)". Remove some: the limit is 2.${hint}`)
+ expect(fileFieldError(field, [pdf('a.pdf', 1.6 * MB), pdf('b.pdf', 1.6 * MB)], texts)).toBe(`The file "b.pdf" is too large. Choose a file of up to 3 MB.${hint}`)
+ expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], NOTIFICATION_FALLBACK_PL.form)).toBe('Plik „cv.pdf” jest za duży. Wybierz plik do 2 MB. Możesz też wysłać formularz bez pliku.')
+ // A required field: no "send without the file".
+ expect(fileFieldError({ ...field, required: true }, [pdf('cv.pdf', 3 * MB)], texts)).toBe('The file "cv.pdf" is too large. Choose a file of up to 2 MB.')
// Older text objects without the file keys still give a message.
expect(fileFieldError(field, [pdf('cv.png', 10)], { validation: 'Check the field "{field}".' })).toBe('Check the field "Attachment (optional)".')
})
@@ -189,7 +192,7 @@ describe('the form in the browser', () => {
expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] })
expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({})
expect(validateBuilderFields([{ ...field, required: true }], { attachment: [] }, texts)).toEqual({ attachment: 'Check the field "Attachment (optional)".' })
- expect(validateBuilderFields([field], { attachment: [{ name: 'x.exe', size: 5 }] }, texts).attachment).toContain('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', () => {
@@ -225,15 +228,38 @@ describe('messages and helpers', () => {
const texts = NOTIFICATION_FALLBACK.form
test('every file outcome has its own text; the placeholders are filled', () => {
- const fail = (extra: Record) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, texts)
- expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 })).toBe('"a.pdf" is too large. The limit is 10 MB.')
- 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({ kind: 'file_count', max: 2 })).toBe('Attach at most 2 files in "CV".')
+ const fail = (extra: Record, t = texts) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, t)
+ // English: which file, why, what to do
+ expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 })).toBe('The file "a.pdf" is too large. Choose a file of up to 10 MB.')
+ expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' })).toBe('The file "a.txt" is in a format we do not accept. Choose one of: PDF, DOCX.')
+ expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' })).toBe(
+ 'The file "a.exe" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOCX).',
+ )
+ expect(fail({ kind: 'file_count', max: 2 })).toBe('Too many files in "CV". Remove some: the limit is 2.')
+ expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, texts)).toBe(
+ 'We could not send the file "a.pdf". Choose a smaller file or another format and try again.',
+ )
+ // an optional field: every file message adds that the form can go without the file
+ for (const extra of [{ file: 'a.pdf', kind: 'file_too_large', max: 10 }, { file: 'a.txt', kind: 'file_type', types: 'PDF' }, { file: 'a.exe', kind: 'file_refused', types: 'PDF' }, { kind: 'file_count', max: 2 }]) {
+ expect(fail({ ...extra, optional: true })).toMatch(/ You can also send the form without the file\.$/)
+ }
+ expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', optional: true, reason: 'delivery', success: false }, texts)).toMatch(/try again\. You can also send the form without the file\.$/)
+ // Polish
+ const pl = NOTIFICATION_FALLBACK_PL.form
+ expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 }, pl)).toBe('Plik „a.pdf” jest za duży. Wybierz plik do 10 MB.')
+ expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' }, pl)).toBe('Plik „a.txt” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOCX.')
+ expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' }, pl)).toBe(
+ 'Plik „a.exe” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOCX).',
+ )
+ expect(fail({ kind: 'file_count', max: 2, optional: true }, pl)).toBe('Za dużo plików w polu „CV”. Usuń część: limit to 2. Możesz też wysłać formularz bez pliku.')
+ expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, pl)).toBe('Nie udało się wysłać pliku „a.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.')
+ // Failures that are not about a file keep their own texts
expect(fail({ kind: 'required' })).toBe('Check the field "CV".')
- expect(resolveFormMessage({ reason: 'delivery', success: false }, texts)).toBe('We could not send your file. Try again, or send it by e-mail.')
- 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(fail({ kind: 'invalid_format', optional: true })).toBe('Check the field "CV".')
+ expect(resolveFormMessage({ reason: 'error', success: false }, texts)).toBe(texts.error)
+ expect(resolveFormMessage({ reason: 'rate_limited', success: false }, texts)).toBe(texts.rateLimited)
// Texts written before the file keys existed fall back to the general ones.
- const { fileCount: _a, fileNotSent: _b, 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({ field: 'cv', file: 'a.pdf', kind: 'file_too_large', max: 1, reason: 'validation', success: false }, old)).toBe('Check the field "cv".')
})