WIP: form attachments — unit tests, test e-mail with attachment, lint

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:28:22 +01:00
co-authored by Claude Fable 5.2
parent 02b1e96d3d
commit 701bb420c1
16 changed files with 302 additions and 35 deletions
+1 -1
View File
@@ -29,9 +29,9 @@ export { ConstructionNotice } from '../modules/construction/ConstructionNotice.j
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { formatFileSize } from '../modules/forms/attachments/fileTypes.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { formatFileSize } from '../modules/forms/attachments/fileTypes.js'
export { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type { BuilderFile } from '../modules/forms/builderLogic.js'
export type {
+1 -1
View File
@@ -66,7 +66,7 @@ export const notificationsFields: Field[] = [
formText('fileTooLarge', { en: 'File too large', pl: 'Plik za duży' }, {
description: { en: 'Use {file} for the file name and {max} for the limit in MB.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {max} — limit w MB.' },
}),
formText('fileType', { en: 'File type not accepted', 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.' },
}),
formText('fileCount', { en: 'Too many files', pl: 'Za dużo plików' }, {
@@ -17,6 +17,7 @@ export const TestEmailButton = () => {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1], vars?: Record<string, unknown>) => ipalT(t as never, key, vars)
const [to, setTo] = useState('')
const [withFile, setWithFile] = useState(false)
const [status, setStatus] = useState<
{ kind: 'error'; msg: string } | { kind: 'idle' } | { kind: 'ok'; msg: string } | { kind: 'sending' }
>({ kind: 'idle' })
@@ -29,7 +30,7 @@ export const TestEmailButton = () => {
setStatus({ kind: 'sending' })
try {
const res = await fetch('/api/ipal/test-email', {
body: JSON.stringify({ to: to.trim() }),
body: JSON.stringify({ to: to.trim(), ...(withFile ? { attachmentMB: 10 } : {}) }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
@@ -69,6 +70,10 @@ export const TestEmailButton = () => {
{status.kind === 'sending' ? text('testEmailSending') : text('testEmailSend')}
</button>
</div>
<label htmlFor="ipal-test-email-file" style={{ alignItems: 'center', display: 'flex', fontSize: '.85rem', gap: '.4rem', marginTop: '.5rem' }}>
<input aria-label={text('testEmailWithFile')} checked={withFile} id="ipal-test-email-file" onChange={(e) => setWithFile(e.target.checked)} type="checkbox" />
{text('testEmailWithFile')}
</label>
{status.kind === 'ok' && (
<p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>
✓ {status.msg}
+2 -2
View File
@@ -172,6 +172,8 @@ export {
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
@@ -184,8 +186,6 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js'
@@ -55,6 +55,7 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Test e-mail sent to {{to}}.',
testEmailSubject: 'Test e-mail from {{site}}',
testEmailSubjectGeneric: 'Test e-mail from your website',
testEmailWithFile: 'Attach a 10 MB test file',
},
pl: {
alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.',
@@ -104,5 +105,6 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
testEmailWithFile: 'Dołącz plik testowy 10 MB',
},
})
@@ -15,6 +15,9 @@ import { serverText } from '../../integrations/texts.js'
* authenticated admin user — a test-send button must never be open to the
* public (it would be an open relay / spam vector).
*
* Body: `{ to, attachmentMB? }` — `attachmentMB` (1–25) attaches a dummy file of
* that size, to measure what the mail server really accepts.
*
* Returns the adapter's own result so the panel can show exactly what happened,
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
*/
@@ -51,12 +54,20 @@ export const testEmailEndpoint: Endpoint = {
return Response.json({ error: serverText(i18n, 'testEmailInvalidRecipient'), ok: false }, { status: 400 })
}
// Optional: a dummy attachment of N MB — proves that a form file of that size
// really gets through this mail server (form files are delivered by e-mail only).
const requested = Number(req.data?.attachmentMB)
const attachmentMB = Number.isFinite(requested) && requested > 0 ? Math.min(Math.floor(requested), 25) : 0
const site = await siteName(req)
const subject = site ? serverText(i18n, 'testEmailSubject', { site }) : serverText(i18n, 'testEmailSubjectGeneric')
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
try {
const info = await req.payload.sendEmail({
...(attachmentMB
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'ipal-kit test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
: {}),
html: `<p>${escapeHtml(text)}</p>`,
subject,
text,
+2 -2
View File
@@ -56,14 +56,14 @@ export type FormAttachmentsOption = {
* A thrown error refuses the file too.
*/
scan?: (file: FormFileScanInput) => FormFileScanResult | Promise<FormFileScanResult>
/** Refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search). Default false. */
strictPdf?: boolean
/**
* The submit endpoint's gates — the same options createSubmitAction takes,
* so both paths behave alike. `allowedOrigins`: other origins that may post
* to it (a front end on another domain); the site's own origin always may.
*/
submit?: FormSubmitEndpointOptions
/** Refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search). Default false. */
strictPdf?: boolean
}
export type FormSubmitEndpointOptions = {
+5 -5
View File
@@ -137,11 +137,11 @@ export function pdfHasActiveContent(bytes: Uint8Array): boolean {
export type FileRefusal =
/** The name: no extension the field allows, a double extension, a blocked extension. */
| 'name'
/** The bytes are not what the extension claims. */
| 'signature'
/** The right container, but with something refused inside (macros, encryption, a program). */
| 'content'
/** The bytes are not what the extension claims. */
| 'name'
/** The right container, but with something refused inside (macros, encryption, a program). */
| 'signature'
/**
* Name check, before any byte of the file: the last extension must belong to
@@ -162,7 +162,7 @@ export function matchFileType(
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'name' }}
for (const key of allowed) {
const type = types[key]
if (type?.extensions.includes(last)) {return { key, type }}
if (type?.extensions.includes(last)) {return { type, key }}
}
return { refused: 'name' }
}
+2 -3
View File
@@ -2,7 +2,7 @@ import type { FileFieldConfig, ResolvedFormAttachments } from './config.js'
import { fileFieldLimits } from './config.js'
import { checkFileContent, looksExecutable, matchFileType, SIGNATURE_BYTES, signatureMatches } from './fileChecks.js'
import { describeFileTypes, MB, safeFileName } from './fileTypes.js'
import { describeFileTypes, MB, safeFileName, UNSAFE_NAME_CHARACTERS } from './fileTypes.js'
/** A file that passed every check — in memory, ready for the e-mail. */
export type AcceptedFormFile = {
@@ -41,8 +41,7 @@ export type FileSlot = {
tooLarge: () => FormFileFailure
}
// eslint-disable-next-line no-control-regex
const displayName = (name: string) => (name.split(/[/\\]/).pop() ?? '').replace(/[\u0000-\u001F\u007F‪-‮⁦-⁩]/g, '').slice(0, 120)
const displayName = (name: string) => (name.split(/[/\\]/).pop() ?? '').replace(UNSAFE_NAME_CHARACTERS, '').slice(0, 120)
/** A limit in MB for a message: whole number, or one decimal rounded DOWN (never promise more). */
export const limitInMB = (bytes: number) => {
+4 -3
View File
@@ -72,9 +72,10 @@ export function fileExtensions(name: string): string[] {
return parts.map((p) => p.trim().toLowerCase()).filter(Boolean)
}
// Control characters and bidi overrides (a name like "cv‮fdp.exe" reads as "cvexe.pdf").
// Control characters, zero-width characters and bidi overrides (a name like "cv<RLO>fdp.exe" reads as "cvexe.pdf").
// eslint-disable-next-line no-control-regex
const UNSAFE = /[\u0000-\u001F\u007F​-‏‪-‮⁦-⁩]/g
export const UNSAFE_NAME_CHARACTERS = /[\u0000-\u001F\u007F\u200B-\u200F\u202A-\u202E\u2066-\u2069]/g
const UNSAFE = UNSAFE_NAME_CHARACTERS
/**
* The name shown to staff and used on the attachment — never the raw client
@@ -96,7 +97,7 @@ export function safeFileName(name: string, extension: string): string {
}
/** What a File field resolves to for the given type keys (unknown keys are skipped). */
export function describeFileTypes(keys: readonly string[] | null | undefined, types: Record<string, FormFileType> = FORM_FILE_TYPES) {
export function describeFileTypes(keys: null | readonly string[] | undefined, types: Record<string, FormFileType> = FORM_FILE_TYPES) {
const list = (keys ?? []).map((key) => types[key]).filter((t): t is FormFileType => Boolean(t))
const extensions = [...new Set(list.flatMap((t) => t.extensions))]
return {
+1 -1
View File
@@ -11,7 +11,7 @@ import { limitInMB } from './fileGate.js'
import { describeFileTypes } from './fileTypes.js'
type Block = { blockType?: string; resolved?: unknown } & FileFieldConfig
type FormDoc = { emails?: null | { bcc?: null | string; cc?: null | string; emailTo?: null | string }[]; fields?: Block[] | null; fileSubmitUrl?: string }
type FormDoc = { emails?: { bcc?: null | string; cc?: null | string; emailTo?: null | string }[] | null; fields?: Block[] | null; fileSubmitUrl?: string }
const fileBlocks = (doc: FormDoc | null | undefined) => (Array.isArray(doc?.fields) ? doc.fields.filter((f) => f?.blockType === 'file') : [])
@@ -249,11 +249,11 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
await pre
}
if (!outcome && gate && stored) {
const missing = (gate as FileGate).end()
const missing = (gate).end()
if (missing) {stop(await fileFailure(payload, (stored as { formId: string }).formId, missing, locale))}
}
// 15. Store the answers and the file metadata, e-mail the files, drop the buffers.
if (!outcome && gate && stored) {stop(await storeSubmission({ ...(stored as Parameters<typeof storeSubmission>[0]), files: (gate as FileGate).accepted }))}
if (!outcome && gate && stored) {stop(await storeSubmission({ ...(stored), files: (gate).accepted }))}
} catch (err) {
payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
+3 -3
View File
@@ -223,7 +223,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
? async (emails, args) => {
const noticed = fileNotice ? await fileNotice(emails, args) : emails
const laidOut = layout ? await layout(noticed, args) : noticed
const changed = forms.beforeEmail ? await forms.beforeEmail(laidOut, args) : laidOut
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
return fileDelivery ? fileDelivery(changed, args) : changed
}
: undefined
@@ -314,8 +314,8 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
if (!attachments) {return builder}
// The submit endpoint for forms with files, and the resolved option where
// submitForm and the endpoint read it (payload.config.custom.ipal.formAttachments).
return async (incoming) => {
const config = await builder(incoming)
return (incoming) => {
const config = builder(incoming)
return {
...config,
custom: { ...config.custom, ipal: { ...(config.custom?.ipal as object | undefined), formAttachments: attachments } },
+10 -10
View File
@@ -82,6 +82,16 @@ export type SubmitFormArgs = {
* - `error` — persistence failed unexpectedly
*/
export type SubmitFailure =
| {
/**
* The file could not be handed to the mail server (or the form has no
* e-mail that may carry it). The file is gone — the visitor must send it
* again. `submissionId`: the stored attempt, marked "Not sent".
*/
reason: 'delivery'
submissionId?: number | string
success: false
}
| {
/** The offending field's name, when one field is at fault. */
field?: string
@@ -98,16 +108,6 @@ export type SubmitFailure =
/** Accepted types, "PDF, DOCX" (file_type). */
types?: string
}
| {
/**
* 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".
*/
reason: 'delivery'
submissionId?: number | string
success: false
}
| {
field?: string
/** A GDPR consent field existed on the form but wasn't checked. */
+1 -1
View File
@@ -12,9 +12,9 @@ type FormField = {
label?: string
/** file */
maxFiles?: null | number
maxSizeMB?: null | number
/** checkboxGroup limits. */
maxSelected?: null | number
maxSizeMB?: null | number
minSelected?: null | number
name?: string
/** select / radio / checkboxGroup choices defined in the panel. */
+249
View File
@@ -0,0 +1,249 @@
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
import { fileFieldLimits, resolveFormAttachments } from '../src/modules/forms/attachments/config.js'
import { canCarryFiles, emailAddresses, fixedRecipients, mayCarryFiles } from '../src/modules/forms/attachments/delivery.js'
import { buildFileBlock } from '../src/modules/forms/attachments/fileBlock.js'
import { checkFileContent, matchFileType, oleHasMacros, pdfHasActiveContent, zipEntries } from '../src/modules/forms/attachments/fileChecks.js'
import { limitInMB } from '../src/modules/forms/attachments/fileGate.js'
import { describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from '../src/modules/forms/attachments/fileTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { fileFieldError, fileFieldRules, initialBuilderValues, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { splitFormFiles } from '../src/modules/forms/createSubmitAction.js'
import { publicForm } from '../src/modules/forms/RenderForm.js'
import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
vi.mock('server-only', () => ({}))
const MB = 1024 * 1024
const options = resolveFormAttachments(true)
const risky = options.risky
describe('file names', () => {
test('the attachment name is rebuilt: no path, no control or bidi characters, the detected extension', () => {
expect(safeFileName('C:\\Users\\jan\\CV Jan Kowalski.PDF', 'pdf')).toBe('CV Jan Kowalski.pdf')
expect(safeFileName('../../etc/passwd', 'pdf')).toBe('passwd.pdf')
expect(safeFileName('cv\u202Efdp.exe', 'pdf')).toBe('cvfdp.pdf')
expect(safeFileName('Życiorys (2026) — wersja #2.docx', 'docx')).toBe('Życiorys (2026) wersja 2.docx')
expect(safeFileName('<script>.pdf', 'pdf')).toBe('script.pdf')
expect(safeFileName('....', 'pdf')).toBe('attachment.pdf')
expect(safeFileName(`${'a'.repeat(300)}.pdf`, 'pdf')).toHaveLength(84)
})
test('the extension decides the type; risky and doubled extensions are refused', () => {
const allowed = ['pdf', 'doc', 'docx']
const match = (name: string, list = allowed, set: ReadonlySet<string> = risky) => {
const result = matchFileType(name, list, options.types, set)
return 'key' in result ? result.key : 'refused'
}
expect(match('cv.pdf')).toBe('pdf')
expect(match('CV.DOCX')).toBe('docx')
expect(match('my.cv.final.pdf')).toBe('pdf') // dots in a name are fine
for (const name of ['cv', 'cv.txt', 'cv.pdf.exe', 'cv.exe.pdf', 'cv.pdf.docx', 'cv.docm', 'cv.zip', 'cv.svg', 'cv.html', 'cv.js.pdf']) {
expect(match(name), name).toBe('refused')
}
expect(match('photo.png')).toBe('refused') // a known type the field does not allow
expect(match('photo.jpeg', ['jpg'])).toBe('jpg')
})
test('a project can allow a refused extension and add its own type', async () => {
const own = resolveFormAttachments({
allowRisky: ['zip'],
fileTypes: { dwg: { detect: (bytes) => bytes[0] === 0x41 && bytes[1] === 0x43, extensions: ['.DWG'], label: 'DWG', mimeType: 'image/vnd.dwg' }, rtf: false, zip: { extensions: ['zip'], label: 'ZIP', mimeType: 'application/zip' } },
})
expect(own.risky.has('zip')).toBe(false)
expect(own.risky.has('exe')).toBe(true)
expect(Object.keys(own.types)).toContain('dwg')
expect(own.types.rtf).toBeUndefined()
expect(matchFileType('plan.dwg', ['dwg'], own.types, own.risky)).toMatchObject({ key: 'dwg' })
expect(matchFileType('files.zip', ['zip'], own.types, own.risky)).toMatchObject({ key: 'zip' })
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('AC1027....'))).toBeNull()
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('not a drawing'))).toBe('signature')
// The panel offers exactly the project's types.
expect(JSON.stringify(buildFileBlock(own).fields)).toContain('"value":"dwg"')
})
test('the risky list covers programs, macro files, archives and renderable markup', () => {
for (const extension of ['exe', 'bat', 'js', 'docm', 'xlsm', 'zip', 'rar', 'html', 'svg', 'iso']) {expect(RISKY_FILE_EXTENSIONS, extension).toContain(extension)}
expect(Object.keys(FORM_FILE_TYPES).filter((key) => FORM_FILE_TYPES[key].extensions.some((e) => RISKY_FILE_EXTENSIONS.includes(e)))).toEqual([])
})
})
describe('content checks', () => {
const ole = Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(600)])
test.each([
['pdf', Buffer.from('%PDF-1.4 ....')],
['jpg', Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0])],
['png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0])],
['webp', Buffer.from('RIFF\0\0\0\0WEBPVP8 ')],
['rtf', Buffer.from('{\\rtf1\\ansi}')],
['doc', ole],
['xls', ole],
])('%s: the right bytes pass, any other bytes do not', async (key, good) => {
expect(await checkFileContent(key, FORM_FILE_TYPES[key], good)).toBeNull()
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.from('plain text, not this type'))).toBe('signature')
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.alloc(0))).toBe('signature')
})
test('programs are refused whatever they claim to be', async () => {
for (const head of [Buffer.from('MZ\x90\0'), Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.from('#!/bin/sh\n')]) {
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, Buffer.concat([head, Buffer.alloc(64)]))).toBe('signature')
}
})
test('a ZIP without a readable directory is not a document', async () => {
const truncated = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.alloc(200)])
expect(zipEntries(truncated)).toBeNull()
expect(await checkFileContent('docx', FORM_FILE_TYPES.docx, truncated)).toBe('signature')
})
test('legacy Office: a macro storage is found by its UTF-16 name (best-effort)', () => {
expect(oleHasMacros(ole)).toBe(false)
expect(oleHasMacros(Buffer.concat([ole, Buffer.from('_VBA_PROJECT_CUR', 'utf16le')]))).toBe(true)
})
test('strictPdf (optional): active content is refused only when switched on', async () => {
const pdf = Buffer.from('%PDF-1.7\n1 0 obj << /OpenAction 2 0 R /JS (app.alert(1)) >> endobj')
expect(pdfHasActiveContent(pdf)).toBe(true)
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf)).toBeNull()
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf, { strictPdf: true })).toBe('content')
})
})
describe('limits', () => {
test('the editor\'s values are capped by the option and by the e-mail transport', () => {
const field = { allowedTypes: ['pdf', 'nope'], maxFiles: 9, maxSizeMB: 50 }
expect(fileFieldLimits(field, options)).toEqual({ allowedTypes: ['pdf'], maxBytes: 10 * MB, maxFiles: 3, maxTotalBytes: 10 * MB })
expect(fileFieldLimits(field, options, 2_999_999)).toMatchObject({ maxBytes: 2_999_999, maxTotalBytes: 2_999_999 })
expect(fileFieldLimits({}, resolveFormAttachments({ maxSizeMB: 5, maxTotalMB: 12 }))).toMatchObject({ maxBytes: 5 * MB, maxFiles: 1, maxTotalBytes: 12 * MB })
expect(limitInMB(10 * MB)).toBe(10)
expect(limitInMB(2_999_999)).toBe(2.8) // rounded down — never promise more than can be sent
})
test('sizes read naturally', () => {
expect([formatFileSize(512), formatFileSize(64_000), formatFileSize(2.14 * MB), formatFileSize(10 * MB)]).toEqual(['512 B', '63 KB', '2.1 MB', '10 MB'])
})
})
describe('which e-mail may carry a file', () => {
const form = {
emails: [
{ bcc: '[email protected]', emailTo: 'HR <[email protected]>, [email protected]' },
{ emailTo: '{{email}}' },
{ cc: '{{email}}', emailTo: '[email protected]' },
{ emailTo: '' },
],
}
test('only e-mails whose recipients are all fixed addresses from the panel', () => {
expect(emailAddresses('HR <[email protected]>; [email protected]')).toEqual(['[email protected]', '[email protected]'])
expect(canCarryFiles(form)).toBe(true)
expect(canCarryFiles({ emails: [{ emailTo: '{{email}}' }] })).toBe(false)
expect(canCarryFiles({ emails: [] })).toBe(false)
const fixed = fixedRecipients(form, '[email protected]')
expect([...fixed].sort()).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]'])
expect(mayCarryFiles({ bcc: '[email protected]', cc: '', to: 'HR <[email protected]>, [email protected]' }, fixed)).toBe(true)
expect(mayCarryFiles({ bcc: '', cc: '', to: '[email protected]' }, fixed)).toBe(false) // the confirmation
expect(mayCarryFiles({ bcc: '', cc: '[email protected]', to: '[email protected]' }, fixed)).toBe(false) // a mixed one
expect(mayCarryFiles({ bcc: '', cc: '', to: '' }, fixed)).toBe(false)
})
})
describe('the form in the browser', () => {
const field: BuilderField = {
name: 'attachment',
allowedTypes: ['pdf', 'docx'],
blockType: 'file',
help: 'PDF or DOCX, up to 2 MB',
label: 'Attachment (optional)',
maxFiles: 2,
maxSizeMB: 2,
resolved: { ...describeFileTypes(['pdf', 'docx']), maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3, typeLabels: 'PDF, DOCX' },
}
const texts = { ...NOTIFICATION_FALLBACK.form }
const form: BuilderFormDoc = { id: 9, fields: [{ name: 'name', blockType: 'text', label: 'Name' }, field], fileSubmitUrl: '/api/ipal/forms/submit' }
test('rules come from what the server resolved, else from the field', () => {
expect(fileFieldRules(field)).toMatchObject({ extensions: ['pdf', 'docx'], maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3 })
expect(fileFieldRules({ name: 'a', allowedTypes: ['pdf'], blockType: 'file' })).toMatchObject({ accept: '.pdf,application/pdf', maxFiles: 1, maxSizeMB: 10, typeLabels: 'PDF' })
})
test('instant checks use the same messages as the server', () => {
const pdf = (name: string, size: number) => ({ name, size })
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.')
// Older text objects without the file keys still give a message.
expect(fileFieldError(field, [pdf('cv.png', 10)], { validation: 'Check the field "{field}".' })).toBe('Check the field "Attachment (optional)".')
})
test('values and validation: a File field starts empty; required and limits are enforced', () => {
expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] })
expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({})
expect(validateBuilderFields([{ ...field, required: true }], { attachment: [] }, texts)).toEqual({ attachment: 'Check the field "Attachment (optional)".' })
expect(validateBuilderFields([field], { attachment: [{ name: 'x.exe', size: 5 }] }, texts).attachment).toContain('not an accepted file type')
})
test('markup: a native file input with a label, help text tied to it, accept and multiple', () => {
const html = renderToStaticMarkup(createElement(BuilderForm, { action: async () => ({ success: true }), form, locale: 'en', texts }))
expect(html).toMatch(/<label for="ipal-f-9-attachment">Attachment \(optional\)<\/label><input[^>]*id="ipal-f-9-attachment"/)
const input = /<input[^>]*id="ipal-f-9-attachment"[^>]*>/.exec(html)?.[0] ?? ''
expect(input).toContain('type="file"')
expect(input).toContain('multiple=""')
expect(input).toContain('accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document"')
expect(input).toContain('aria-describedby="ipal-f-9-attachment-help"')
expect(html).toContain('<p id="ipal-f-9-attachment-help">PDF or DOCX, up to 2 MB</p>')
expect(html).toContain('<ul aria-live="polite" data-ipal="form-files"></ul>')
expect(html).toContain('data-type="file"')
expect(html).not.toMatch(/class="/)
const styled = renderToStaticMarkup(
createElement(BuilderForm, { action: async () => ({ success: true }), classNames: { file: 'f', fileList: 'l', help: 'h' }, form, texts }),
)
expect(styled).toContain('class="f"')
expect(styled).toContain('class="l"')
expect(styled).toContain('class="h"')
})
test('only the public part of the form reaches the browser, with the limits and the submit address', () => {
const doc = { ...form, emails: [{ emailTo: '[email protected]' }] } as BuilderFormDoc
const pub = publicForm(doc)
expect(JSON.stringify(pub)).not.toContain('[email protected]')
expect(pub.fileSubmitUrl).toBe('/api/ipal/forms/submit')
expect(pub.fields?.[1].resolved).toMatchObject({ maxSizeMB: 2 })
})
})
describe('messages and helpers', () => {
const texts = NOTIFICATION_FALLBACK.form
test('every file outcome has its own text; the placeholders are filled', () => {
const fail = (extra: Record<string, unknown>) => 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".')
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.')
// 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
expect(resolveFormMessage({ reason: 'delivery', success: false }, old)).toBe(texts.error)
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', kind: 'file_too_large', max: 1, reason: 'validation', success: false }, old)).toBe('Check the field "cv".')
})
test('splitFormFiles separates File values from the answers', async () => {
const file = new File([new Uint8Array([1, 2, 3])], 'cv.pdf')
const { fields, files } = await splitFormFiles({ name: 'Jan', attachment: [file], single: file, tags: ['a', 'b'] })
expect(fields).toEqual({ name: 'Jan', tags: ['a', 'b'] })
expect(files?.attachment).toEqual([{ name: 'cv.pdf', data: new Uint8Array([1, 2, 3]) }])
expect(files?.single).toHaveLength(1)
expect(await splitFormFiles({ name: 'Jan', empty: [] })).toEqual({ fields: { name: 'Jan', empty: [] } })
})
})