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
@@ -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. */