diff --git a/src/exports/client.ts b/src/exports/client.ts index d12eba2..1395dda 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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 { diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts index 10d5fa2..6702349 100644 --- a/src/globals/Notifications/fields.ts +++ b/src/globals/Notifications/fields.ts @@ -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' }, { diff --git a/src/globals/SiteIntegrations/components/TestEmailButton.tsx b/src/globals/SiteIntegrations/components/TestEmailButton.tsx index 3ab291c..89c3db3 100644 --- a/src/globals/SiteIntegrations/components/TestEmailButton.tsx +++ b/src/globals/SiteIntegrations/components/TestEmailButton.tsx @@ -17,6 +17,7 @@ export const TestEmailButton = () => { const { t } = useTranslation() const text = (key: Parameters[1], vars?: Record) => 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')} + {status.kind === 'ok' && (

✓ {status.msg} diff --git a/src/index.ts b/src/index.ts index eb4dd34..cb1cc29 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index bc693cf..cdb9ef8 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -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', }, }) diff --git a/src/modules/email/test/testEmailEndpoint.ts b/src/modules/email/test/testEmailEndpoint.ts index b2d1288..2c06668 100644 --- a/src/modules/email/test/testEmailEndpoint.ts +++ b/src/modules/email/test/testEmailEndpoint.ts @@ -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: `

${escapeHtml(text)}

`, subject, text, diff --git a/src/modules/forms/attachments/config.ts b/src/modules/forms/attachments/config.ts index d552fa8..f8d2a5a 100644 --- a/src/modules/forms/attachments/config.ts +++ b/src/modules/forms/attachments/config.ts @@ -56,14 +56,14 @@ export type FormAttachmentsOption = { * A thrown error refuses the file too. */ scan?: (file: FormFileScanInput) => FormFileScanResult | Promise + /** 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 = { diff --git a/src/modules/forms/attachments/fileChecks.ts b/src/modules/forms/attachments/fileChecks.ts index 264d02b..1c35d28 100644 --- a/src/modules/forms/attachments/fileChecks.ts +++ b/src/modules/forms/attachments/fileChecks.ts @@ -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' } } diff --git a/src/modules/forms/attachments/fileGate.ts b/src/modules/forms/attachments/fileGate.ts index 0d5efb8..bb24524 100644 --- a/src/modules/forms/attachments/fileGate.ts +++ b/src/modules/forms/attachments/fileGate.ts @@ -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) => { diff --git a/src/modules/forms/attachments/fileTypes.ts b/src/modules/forms/attachments/fileTypes.ts index e759851..c9d5b8c 100644 --- a/src/modules/forms/attachments/fileTypes.ts +++ b/src/modules/forms/attachments/fileTypes.ts @@ -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 "cvfdp.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 = FORM_FILE_TYPES) { +export function describeFileTypes(keys: null | readonly string[] | undefined, types: Record = 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 { diff --git a/src/modules/forms/attachments/formHooks.ts b/src/modules/forms/attachments/formHooks.ts index 898a6c9..8a9e6c8 100644 --- a/src/modules/forms/attachments/formHooks.ts +++ b/src/modules/forms/attachments/formHooks.ts @@ -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') : []) diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts index 20b7080..7da7054 100644 --- a/src/modules/forms/attachments/submitHandler.ts +++ b/src/modules/forms/attachments/submitHandler.ts @@ -249,11 +249,11 @@ export async function handleFormSubmit(req: PayloadRequest): Promise { 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[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 }) diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 1d4c88e..97e21cc 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -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 } }, diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index b5445a7..3c63c70 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -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. */ diff --git a/src/modules/forms/validateSubmission.ts b/src/modules/forms/validateSubmission.ts index 126602a..7852d6c 100644 --- a/src/modules/forms/validateSubmission.ts +++ b/src/modules/forms/validateSubmission.ts @@ -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. */ diff --git a/test/formFileField.test.ts b/test/formFileField.test.ts new file mode 100644 index 0000000..5990a1b --- /dev/null +++ b/test/formFileField.test.ts @@ -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('