From 6003b3d7d7ab07e1b580513bc553a242c32a2778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Fri, 13 Nov 2026 16:20:02 +0100 Subject: [PATCH] =?UTF-8?q?WIP:=20form=20attachments=20(e-mail=20only)=20?= =?UTF-8?q?=E2=80=94=20core,=20endpoint,=20Graph=20large=20upload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- package.json | 2 + pnpm-lock.yaml | 6 + src/exports/client.ts | 5 +- src/exports/server.ts | 2 +- src/globals/Notifications/fields.ts | 22 ++ src/index.ts | 8 +- src/modules/admin-i18n/texts/integrations.ts | 4 + src/modules/email/attachmentLimit.ts | 17 + src/modules/email/graphAdapter.ts | 104 ++++++- src/modules/email/graphAttachments.ts | 197 ++++++++++++ src/modules/email/mailAdapter.ts | 54 +++- src/modules/forms/BuilderForm.tsx | 28 +- src/modules/forms/RenderForm.tsx | 4 + src/modules/forms/attachments/config.ts | 149 +++++++++ src/modules/forms/attachments/delivery.ts | 197 ++++++++++++ src/modules/forms/attachments/endpoint.ts | 19 ++ src/modules/forms/attachments/fileBlock.ts | 97 ++++++ src/modules/forms/attachments/fileChecks.ts | 193 ++++++++++++ src/modules/forms/attachments/fileGate.ts | 167 ++++++++++ src/modules/forms/attachments/fileTypes.ts | 109 +++++++ src/modules/forms/attachments/formHooks.ts | 124 ++++++++ .../forms/attachments/submitHandler.ts | 292 ++++++++++++++++++ src/modules/forms/builderLogic.ts | 62 +++- src/modules/forms/builderTypes.ts | 37 ++- src/modules/forms/createSubmitAction.ts | 31 +- src/modules/forms/formsPluginConfig.ts | 59 +++- src/modules/forms/index.ts | 13 +- src/modules/forms/submitForm.ts | 283 +++++++++++++---- src/modules/forms/types.ts | 13 +- src/modules/forms/useBuilderForm.ts | 123 +++++++- src/modules/forms/validateSubmission.ts | 27 +- src/modules/integrations/texts.ts | 1 + src/modules/notifications/defaults.ts | 10 + .../notifications/getNotificationTexts.ts | 5 + .../notifications/resolveFormMessage.ts | 22 +- src/modules/notifications/types.ts | 10 + 36 files changed, 2399 insertions(+), 97 deletions(-) create mode 100644 src/modules/email/attachmentLimit.ts create mode 100644 src/modules/email/graphAttachments.ts create mode 100644 src/modules/forms/attachments/config.ts create mode 100644 src/modules/forms/attachments/delivery.ts create mode 100644 src/modules/forms/attachments/endpoint.ts create mode 100644 src/modules/forms/attachments/fileBlock.ts create mode 100644 src/modules/forms/attachments/fileChecks.ts create mode 100644 src/modules/forms/attachments/fileGate.ts create mode 100644 src/modules/forms/attachments/fileTypes.ts create mode 100644 src/modules/forms/attachments/formHooks.ts create mode 100644 src/modules/forms/attachments/submitHandler.ts diff --git a/package.json b/package.json index 9571474..d48cf29 100644 --- a/package.json +++ b/package.json @@ -130,6 +130,7 @@ "typecheck": "tsc --noEmit -p . && tsc -p test" }, "dependencies": { + "busboy": "1.6.0", "lucide-react": "0.400.0", "nodemailer": "10.3.1", "server-only": "0.0.1", @@ -160,6 +161,7 @@ "@playwright/test": "1.64.0", "@swc-node/register": "1.10.9", "@swc/cli": "0.6.0", + "@types/busboy": "1.5.4", "@types/node": "22.20.5", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index db74334..0d6f4f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -25,6 +25,9 @@ importers: '@payloadcms/storage-s3': specifier: ^3.90.2 version: 3.90.2(@types/react@19.2.14)(monaco-editor@0.55.1)(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0)(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(sass@1.77.4))(payload@3.90.2(graphql@16.14.2)(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + busboy: + specifier: 1.6.0 + version: 1.6.0 lucide-react: specifier: 0.400.0 version: 0.400.0(react@19.3.0) @@ -74,6 +77,9 @@ importers: '@swc/cli': specifier: 0.6.0 version: 0.6.0(@swc/core@1.15.43(@swc/helpers@0.5.23)) + '@types/busboy': + specifier: 1.5.4 + version: 1.5.4 '@types/node': specifier: 22.20.5 version: 22.20.5 diff --git a/src/exports/client.ts b/src/exports/client.ts index 0b12af7..d12eba2 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -31,9 +31,12 @@ export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionClos export type { ConstructionMode } from '../modules/construction/types.js' export { BuilderForm } from '../modules/forms/BuilderForm.js' export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js' -export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.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 { BuilderField, + BuilderFileLimits, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, diff --git a/src/exports/server.ts b/src/exports/server.ts index 08dc3ed..6a5652a 100644 --- a/src/exports/server.ts +++ b/src/exports/server.ts @@ -1,6 +1,6 @@ export { sendEmail } from '../modules/email/index.js' export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js' -export { createSubmitAction } from '../modules/forms/createSubmitAction.js' +export { createSubmitAction, splitFormFiles } from '../modules/forms/createSubmitAction.js' export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js' export { submitForm } from '../modules/forms/index.js' export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js' diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts index 0a548e4..10d5fa2 100644 --- a/src/globals/Notifications/fields.ts +++ b/src/globals/Notifications/fields.ts @@ -59,6 +59,28 @@ export const notificationsFields: Field[] = [ formText('turnstile', { en: 'Spam check failed', pl: 'Błąd weryfikacji' }), formText('rateLimited', { en: 'Too many attempts', pl: 'Zbyt wiele prób' }), formText('notFound', { en: 'Form unavailable', pl: 'Formularz niedostępny' }), + { + type: 'collapsible', + admin: { initCollapsed: true }, + fields: [ + 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' }, { + 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' }, { + 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.' }, + }), + 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.' }, + }), + ], + label: { en: 'Files', pl: 'Pliki' }, + }, { type: 'row', fields: [ diff --git a/src/index.ts b/src/index.ts index e4e022c..eb4dd34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -184,9 +184,15 @@ 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' +export type { FormFileDetect, FormFileType } from './modules/forms/attachments/fileTypes.js' export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js' export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js' -export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js' +export type { BuilderField, BuilderFileLimits, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js' // Panel-managed form analytics (config-time field builder). export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js' export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index 9346091..bc693cf 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -26,6 +26,8 @@ export const integrationsTexts = defineTexts({ statusWorkingSince: '{{label}}: working since {{date}}.', // Status messages, by status code + statusEmailGraphLargeFiles: + 'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.', statusEmailGraphUnavailable: 'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.', statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.', @@ -74,6 +76,8 @@ export const integrationsTexts = defineTexts({ statusWorking: '{{label}}: działa.', statusWorkingSince: '{{label}}: działa od {{date}}.', + statusEmailGraphLargeFiles: + 'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.', statusEmailGraphUnavailable: 'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.', statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.', diff --git a/src/modules/email/attachmentLimit.ts b/src/modules/email/attachmentLimit.ts new file mode 100644 index 0000000..ad536de --- /dev/null +++ b/src/modules/email/attachmentLimit.ts @@ -0,0 +1,17 @@ +import type { BasePayload } from 'payload' + +/** + * The largest total attachment size (bytes) the site's e-mail adapter says it + * can carry, or null when it names no ceiling. mailAdapter and graphAdapter + * report one; any other adapter is taken to have none. Never throws. + */ +export async function mailAttachmentLimit(payload: BasePayload): Promise { + const limit = (payload.email as { attachmentLimit?: () => null | number | Promise } | undefined)?.attachmentLimit + if (typeof limit !== 'function') {return null} + try { + const value = await limit() + return typeof value === 'number' && value >= 0 ? value : null + } catch { + return null + } +} diff --git a/src/modules/email/graphAdapter.ts b/src/modules/email/graphAdapter.ts index b76d858..7e032af 100644 --- a/src/modules/email/graphAdapter.ts +++ b/src/modules/email/graphAdapter.ts @@ -1,6 +1,15 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { getSiteIntegrations } from '../payload/index.js' +import { + attachmentBytes, + GRAPH_INLINE_MAX_BYTES, + GRAPH_LARGE_PERMISSION, + inlineGraphAttachments, + sendLargeGraphMail, + toGraphAttachments, + tokenRoles, +} from './graphAttachments.js' /** * From/To settings the adapter reads from SiteIntegrations (panel). The Graph @@ -19,8 +28,42 @@ type GraphIntegrations = { } export type GraphAdapterArgs = { + /** Waits before the sent copy of a large-attachment message is deleted from the mailbox (ms). Default 2 s, 5 s, 15 s, 60 s. */ + cleanupDelaysMs?: number[] fallbackFromAddress?: string fallbackFromName?: string + /** For tests: the `fetch` to call Microsoft with. */ + fetchImpl?: typeof fetch + /** + * Attachments of 3 MB and more (in total): the message goes through a draft + * in the sender mailbox and an upload session, and the mailbox copy is deleted + * afterwards. Needs the `Mail.ReadWrite` application permission. Default true; + * `false` keeps Graph to small attachments (larger ones go over SMTP when the + * panel has SMTP settings — see mailAdapter). + */ + largeAttachments?: boolean +} + +/** + * Can this Graph setup send attachments of 3 MB and more? + * - 'ok' — yes + * - 'off' — `largeAttachments: false` + * - 'no-permission' — the app's token lacks Mail.ReadWrite + * - 'unavailable' — Graph is not configured, or no token could be fetched + */ +export type GraphLargeSupport = 'no-permission' | 'off' | 'ok' | 'unavailable' + +export async function graphLargeAttachmentSupport(args: Pick = {}): Promise { + if (args.largeAttachments === false) {return 'off'} + const env = readGraphEnv() + if (!env) {return 'unavailable'} + try { + const roles = tokenRoles(await getAccessToken(env, args.fetchImpl)) + // A token we cannot read says nothing — let the send try and report. + return !roles || roles.includes(GRAPH_LARGE_PERMISSION) ? 'ok' : 'no-permission' + } catch { + return 'unavailable' + } } type GraphEnv = { @@ -43,11 +86,15 @@ function readGraphEnv(): GraphEnv | null { /** * Fetches an app-only access token via the OAuth2 client-credentials flow. * Scope MUST be '.../.default' — passing 'Mail.Send' directly is rejected - * (AADSTS1002012). Tokens last ~1h; we fetch per send for simplicity and to - * avoid holding state in a possibly multi-instance deployment. If you send at - * high volume, cache by expiry. + * (AADSTS1002012). Tokens last ~1h and are cached per process until a minute + * before they expire. */ -async function getAccessToken(env: GraphEnv): Promise { +const tokenCache = new Map() + +async function getAccessToken(env: GraphEnv, fetchImpl: typeof fetch = fetch): Promise { + const cacheKey = `${env.tenantId}:${env.clientId}` + const cached = tokenCache.get(cacheKey) + if (cached && cached.expiresAt > Date.now()) {return cached.token} const url = `https://login.microsoftonline.com/${env.tenantId}/oauth2/v2.0/token` const body = new URLSearchParams({ client_id: env.clientId, @@ -56,7 +103,7 @@ async function getAccessToken(env: GraphEnv): Promise { scope: 'https://graph.microsoft.com/.default', }) - const res = await fetch(url, { + const res = await fetchImpl(url, { body, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'POST', @@ -65,8 +112,10 @@ async function getAccessToken(env: GraphEnv): Promise { const detail = await res.text() throw new Error(`Graph token request failed (${res.status}): ${detail}`) } - const data = (await res.json()) as { access_token?: string } + const data = (await res.json()) as { access_token?: string; expires_in?: number } if (!data.access_token) {throw new Error('Graph token response had no access_token')} + // Kept until a minute before it expires (tokens last about an hour). + tokenCache.set(cacheKey, { expiresAt: Date.now() + Math.max(0, (data.expires_in ?? 0) - 60) * 1000, token: data.access_token }) return data.access_token } @@ -103,6 +152,11 @@ export const graphAdapter = (args: GraphAdapterArgs = {}): PayloadEmailAdapter => ({ payload }) => ({ name: 'ipal-graph', + /** Total attachment bytes this adapter can carry; null = no ceiling of its own (see mailAdapter). */ + attachmentLimit: async (): Promise => { + const support = await graphLargeAttachmentSupport(args) + return support === 'ok' || support === 'unavailable' ? null : GRAPH_INLINE_MAX_BYTES - 1 + }, defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost', defaultFromName: args.fallbackFromName ?? 'Website', @@ -166,10 +220,44 @@ export const graphAdapter = ...(replyTo.length > 0 ? { replyTo } : {}), } + // Attachments: small ones ride in the same call; larger ones need a draft and an upload session. + const attachments = toGraphAttachments(message) + if (!attachments) { + payload.logger.error('[ipal] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.') + return { detail: 'Attachment content must be a Buffer or a string.', error: 'The e-mail was not sent.', sent: false } + } + const fetchImpl = args.fetchImpl ?? fetch + try { - const token = await getAccessToken(env) + const token = await getAccessToken(env, fetchImpl) + if (attachments.length > 0 && attachmentBytes(attachments) >= GRAPH_INLINE_MAX_BYTES) { + if (args.largeAttachments === false) { + return { + code: 'graph-large-off', + detail: 'Attachments of 3 MB and more are switched off for Microsoft Graph (largeAttachments: false).', + error: 'The e-mail was not sent.', + sent: false, + } + } + const roles = tokenRoles(token) + if (roles && !roles.includes(GRAPH_LARGE_PERMISSION)) { + const detail = `The Microsoft Graph app lacks the ${GRAPH_LARGE_PERMISSION} application permission, so it cannot send attachments of 3 MB and more.` + payload.logger.error(`[ipal] ${detail}`) + return { code: 'graph-permission', detail, error: 'The e-mail was not sent.', sent: false } + } + const large = await sendLargeGraphMail(attachments, { + cleanupDelaysMs: args.cleanupDelaysMs, + fetchImpl, + log: payload.logger, + message: graphMessage, + sender: env.sender, + token, + }) + return large.sent ? large : { ...large, error: 'The e-mail was not sent.' } + } + if (attachments.length > 0) {graphMessage.attachments = inlineGraphAttachments(attachments)} // App-only: MUST target /users/{sender}, never /me. - const res = await fetch( + const res = await fetchImpl( `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(env.sender)}/sendMail`, { body: JSON.stringify({ message: graphMessage, saveToSentItems: false }), diff --git a/src/modules/email/graphAttachments.ts b/src/modules/email/graphAttachments.ts new file mode 100644 index 0000000..f20ff27 --- /dev/null +++ b/src/modules/email/graphAttachments.ts @@ -0,0 +1,197 @@ +import type { SendEmailOptions } from 'payload' + +/** + * Attachments over Microsoft Graph. + * + * - Small (all attachments together under GRAPH_INLINE_MAX_BYTES): inside the + * one `sendMail` call. Needs only `Mail.Send`; nothing is left in the mailbox. + * - Large: Graph has no single call for it. The message is created as a DRAFT + * in the sender mailbox, each file is added (an upload session for files of + * 3 MiB and more), the draft is sent, and the copy the mailbox keeps in Sent + * Items is deleted afterwards. Needs the `Mail.ReadWrite` application + * permission — limit it to the sender mailbox with an application access + * policy (docs/email.md). + */ + +/** + * Microsoft documents inline attachments "under 3 MB"; the request also has to + * fit base64 (+33 %) and the message body, so the plugin switches at 3,000,000 bytes. + */ +export const GRAPH_INLINE_MAX_BYTES = 3_000_000 + +/** Files of this size and more need an upload session; smaller ones are refused by it. */ +const UPLOAD_SESSION_MIN_BYTES = 3 * 1024 * 1024 +/** Bytes per PUT — Microsoft: keep it under 4 MB. A multiple of 320 KiB. */ +const CHUNK_BYTES = 10 * 320 * 1024 + +export const GRAPH_LARGE_PERMISSION = 'Mail.ReadWrite' + +export type GraphAttachment = { content: Buffer; contentType: string; name: string } + +/** nodemailer-style attachments → buffers. `null` when one cannot be read into memory (a path or a stream). */ +export function toGraphAttachments(message: SendEmailOptions): GraphAttachment[] | null { + const list = (message as { attachments?: unknown }).attachments + if (!Array.isArray(list) || list.length === 0) {return []} + const out: GraphAttachment[] = [] + for (const raw of list as { content?: unknown; contentType?: unknown; filename?: unknown }[]) { + const content = + Buffer.isBuffer(raw.content) ? raw.content + : raw.content instanceof Uint8Array ? Buffer.from(raw.content.buffer, raw.content.byteOffset, raw.content.byteLength) + : typeof raw.content === 'string' ? Buffer.from(raw.content, 'utf8') + : null + if (!content) {return null} + out.push({ + name: typeof raw.filename === 'string' && raw.filename ? raw.filename : 'attachment', + content, + contentType: typeof raw.contentType === 'string' && raw.contentType ? raw.contentType : 'application/octet-stream', + }) + } + return out +} + +export const attachmentBytes = (attachments: GraphAttachment[]) => attachments.reduce((sum, a) => sum + a.content.length, 0) + +/** The attachments as `fileAttachment` objects for an inline `sendMail`. */ +export const inlineGraphAttachments = (attachments: GraphAttachment[]) => + attachments.map((a) => ({ + name: a.name, + '@odata.type': '#microsoft.graph.fileAttachment', + contentBytes: a.content.toString('base64'), + contentType: a.contentType, + })) + +/** Application permissions (`roles`) of an app-only access token; `null` when the token is not a readable JWT. */ +export function tokenRoles(token: string): null | string[] { + try { + const payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8')) as { roles?: unknown } + return Array.isArray(payload.roles) ? payload.roles.filter((r): r is string => typeof r === 'string') : null + } catch { + return null + } +} + +export type GraphLargeResult = + | { cleanup: Promise; sent: true } + | { code: 'graph-error' | 'graph-permission'; detail: string; sent: false } + +/** What happened to the copy in the sender mailbox. */ +export type GraphCleanup = 'deleted' | 'left' + +type LargeArgs = { + /** Waits between looks at the sent message before deleting it. Default 2 s, 5 s, 15 s, 60 s. */ + cleanupDelaysMs?: number[] + fetchImpl: typeof fetch + log: { error: (msg: string) => void; warn: (msg: string) => void } + message: Record + sender: string + token: string +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +const permissionDetail = + `Microsoft Graph refused to create the message: the app needs the ${GRAPH_LARGE_PERMISSION} application permission ` + + 'for the sender mailbox to send attachments of 3 MB and more.' + +/** + * Sends a message with large attachments: draft → attachments → send → delete + * the mailbox copy. Any failure before the send deletes the draft, so no file + * is left in the mailbox. Never throws. + */ +export async function sendLargeGraphMail(attachments: GraphAttachment[], { cleanupDelaysMs = [2000, 5000, 15_000, 60_000], fetchImpl, log, message, sender, token }: LargeArgs): Promise { + const base = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(sender)}` + const auth = { Authorization: `Bearer ${token}` } + const json = { ...auth, 'Content-Type': 'application/json' } + const describe = async (res: Response) => `${res.status} ${(await res.text().catch(() => '')).slice(0, 300)}` + + /** Removes a message from the mailbox for good; falls back to a plain delete. */ + const remove = async (id: string): Promise => { + try { + const purge = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}/permanentDelete`, { headers: auth, method: 'POST' }) + if (purge.status === 204 || purge.status === 200) {return true} + const res = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}`, { headers: auth, method: 'DELETE' }) + return res.status === 204 || res.status === 200 || res.status === 404 + } catch { + return false + } + } + + let draftId: string | undefined + try { + // An immutable id stays the same when the draft moves to Sent Items — that is how the copy is found again. + const created = await fetchImpl(`${base}/messages`, { + body: JSON.stringify(message), + headers: { ...json, Prefer: 'IdType="ImmutableId"' }, + method: 'POST', + }) + if (created.status === 401 || created.status === 403) { + log.error(`[ipal] ${permissionDetail} (${await describe(created)})`) + return { code: 'graph-permission', detail: permissionDetail, sent: false } + } + if (created.status !== 201 && created.status !== 200) { + throw new Error(`create draft failed (${await describe(created)})`) + } + draftId = ((await created.json()) as { id?: string }).id + if (!draftId) {throw new Error('create draft returned no id')} + const item = `${base}/messages/${encodeURIComponent(draftId)}` + + for (const attachment of attachments) { + if (attachment.content.length < UPLOAD_SESSION_MIN_BYTES) { + const added = await fetchImpl(`${item}/attachments`, { body: JSON.stringify(inlineGraphAttachments([attachment])[0]), headers: json, method: 'POST' }) + if (added.status !== 201 && added.status !== 200) {throw new Error(`add attachment failed (${await describe(added)})`)} + continue + } + const session = await fetchImpl(`${item}/attachments/createUploadSession`, { + body: JSON.stringify({ AttachmentItem: { name: attachment.name, attachmentType: 'file', contentType: attachment.contentType, size: attachment.content.length } }), + headers: json, + method: 'POST', + }) + if (session.status !== 201 && session.status !== 200) {throw new Error(`create upload session failed (${await describe(session)})`)} + const { uploadUrl } = (await session.json()) as { uploadUrl?: string } + if (!uploadUrl) {throw new Error('upload session returned no uploadUrl')} + const total = attachment.content.length + for (let start = 0; start < total; start += CHUNK_BYTES) { + const end = Math.min(start + CHUNK_BYTES, total) + // The upload URL is pre-authenticated: no Authorization header (Microsoft's rule). + const put = await fetchImpl(uploadUrl, { + body: new Uint8Array(attachment.content.buffer, attachment.content.byteOffset + start, end - start) as unknown as BodyInit, + headers: { 'Content-Length': String(end - start), 'Content-Range': `bytes ${start}-${end - 1}/${total}`, 'Content-Type': 'application/octet-stream' }, + method: 'PUT', + }) + if (put.status !== 200 && put.status !== 201) {throw new Error(`upload failed at byte ${start} (${await describe(put)})`)} + } + } + + const sent = await fetchImpl(`${item}/send`, { headers: { ...auth, 'Content-Length': '0' }, method: 'POST' }) + if (sent.status !== 202) {throw new Error(`send failed (${await describe(sent)})`)} + } catch (err) { + const detail = err instanceof Error ? err.message : String(err) + log.error(`[ipal] Graph send with a large attachment failed: ${detail}`) + // Nothing went out: take the draft (and the file in it) out of the mailbox. + if (draftId && !(await remove(draftId))) { + log.error(`[ipal] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`) + } + return { code: 'graph-error', detail, sent: false } + } + + // Sent. Exchange keeps a copy in Sent Items; delete it once the message has left Drafts. + const sentId = draftId + const cleanup = (async (): Promise => { + for (const delay of cleanupDelaysMs) { + await sleep(delay) + try { + const look = await fetchImpl(`${base}/messages/${encodeURIComponent(sentId)}?$select=isDraft`, { headers: { ...auth, Prefer: 'IdType="ImmutableId"' } }) + if (look.status === 404) {return 'deleted'} + if (look.ok && ((await look.json()) as { isDraft?: boolean }).isDraft === false) { + if (await remove(sentId)) {return 'deleted'} + } + } catch { + /* try again after the next delay */ + } + } + log.warn(`[ipal] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`) + return 'left' + })() + cleanup.catch(() => undefined) + return { cleanup, sent: true } +} diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index a27a0bb..18dc01c 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -2,15 +2,24 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { getSiteIntegrations } from '../payload/index.js' -import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js' +import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' +import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js' type TransportIntegrations = { emailStatus?: IntegrationStatus | null /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */ emailTransport?: 'graph' | 'smtp' | null + smtpHost?: null | string + smtpPassword?: null | string + smtpUser?: null | string } +const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword) + +/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */ +const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission']) + const STATUS_FIELD = 'emailStatus' /** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */ const describe = (err: unknown) => @@ -68,8 +77,24 @@ export const mailAdapter = const { payload } = deps + /** + * The largest total attachment size (bytes) the current transport can + * carry, or null when the plugin knows no ceiling (the mail server's own + * limit still applies). Read by the forms module, so a File field never + * promises more than can be sent: on Graph without the large-file path and + * without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES. + */ + const attachmentLimit = async (): Promise => { + const settings = await getSiteIntegrations(payload) + if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null} + const support = await graphLargeAttachmentSupport(args.graph) + if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null} + return GRAPH_INLINE_MAX_BYTES - 1 + } + return { name: 'ipal-mail-dispatcher', + attachmentLimit, defaultFromAddress: smtp.defaultFromAddress, defaultFromName: smtp.defaultFromName, @@ -88,11 +113,24 @@ export const mailAdapter = ) } - const transport = useGraph ? 'Microsoft Graph' : 'SMTP' - const code = useGraph ? 'graph-error' : 'smtp-error' + // A large attachment Graph cannot carry (switched off, or the app lacks + // Mail.ReadWrite) goes over SMTP when the panel has SMTP settings. + const attachments = useGraph ? toGraphAttachments(message) : [] + const large = Boolean(attachments?.length) && attachmentBytes(attachments ?? []) >= GRAPH_INLINE_MAX_BYTES + const support = large ? await graphLargeAttachmentSupport(args.graph) : 'ok' + const largeOverSmtp = large && support !== 'ok' && support !== 'unavailable' && smtpConfigured(settings) + const viaGraph = useGraph && !largeOverSmtp + + const transport = viaGraph ? 'Microsoft Graph' : 'SMTP' + const code = viaGraph ? 'graph-error' : 'smtp-error' let result: unknown try { - result = await (useGraph ? graph : smtp).sendEmail(message) + result = await (viaGraph ? graph : smtp).sendEmail(message) + // Graph found out only while sending (a token it could not read): one try over SMTP. Graph sent nothing. + const refused = result as { code?: string; sent?: boolean } | null + if (viaGraph && refused?.sent === false && GRAPH_TOO_LARGE.has(refused.code ?? '') && smtpConfigured(settings)) { + result = await smtp.sendEmail(message) + } } catch (err) { await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, @@ -104,10 +142,10 @@ export const mailAdapter = // The delegates report failure as { sent: false, error, detail? } instead // of throwing (a broken mailbox must not crash a form submission). - const failed = result as { detail?: string; error?: string; sent?: boolean } | null + const failed = result as { code?: string; detail?: string; error?: string; sent?: boolean } | null if (failed && typeof failed === 'object' && failed.sent === false) { await recordIntegrationStatus(payload, STATUS_FIELD, previous, { - code, + code: GRAPH_TOO_LARGE.has(failed.code ?? '') ? 'graph-large-files' : code, message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`, state: 'degraded', }) @@ -119,7 +157,9 @@ export const mailAdapter = payload, STATUS_FIELD, previous, - graphFallback + large && support === 'no-permission' + ? { code: 'graph-large-files', state: 'degraded' } + : graphFallback ? { code: 'graph-unavailable', message: diff --git a/src/modules/forms/BuilderForm.tsx b/src/modules/forms/BuilderForm.tsx index 8b69c33..1b25eb3 100644 --- a/src/modules/forms/BuilderForm.tsx +++ b/src/modules/forms/BuilderForm.tsx @@ -8,6 +8,7 @@ import type { TurnstileTheme } from '../turnstile/Turnstile.js' import type { BuilderField } from './builderTypes.js' import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js' +import { formatFileSize } from './attachments/fileTypes.js' import { honeypotInputProps } from './honeypot.js' import { useBuilderForm } from './useBuilderForm.js' @@ -19,7 +20,8 @@ import { useBuilderForm } from './useBuilderForm.js' export type BuilderFormClassNames = Partial< Record< | 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices' - | 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label' + | 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'file' | 'fileItem' | 'fileList' | 'fileRemove' | 'fixed' + | 'form' | 'formError' | 'help' | 'input' | 'label' | 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription' | 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile', string @@ -161,6 +163,30 @@ export function BuilderForm({ {errorOf(field)} ) + case 'file': { + // A native file input: keyboard, touch and screen readers work as everywhere else. + const props = f.getFileProps(field) + const files = f.getFiles(field) + const remove = options.texts.fileRemove ?? 'Remove {file}' + return ( + <> + + + {field.help ?

{field.help}

: null} +
    + {files.map((file, i) => ( +
  • + {file.name} ({formatFileSize(file.size)}){' '} + +
  • + ))} +
+ {errorOf(field)} + + ) + } case 'select': { const props = f.getSelectProps(field) return ( diff --git a/src/modules/forms/RenderForm.tsx b/src/modules/forms/RenderForm.tsx index e24e208..5f0810b 100644 --- a/src/modules/forms/RenderForm.tsx +++ b/src/modules/forms/RenderForm.tsx @@ -52,6 +52,7 @@ export function publicForm(form: BuilderFormDoc): BuilderFormDoc { analytics: form.analytics, confirmationType: form.confirmationType, fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field), + fileSubmitUrl: form.fileSubmitUrl, redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null, submitButtonLabel: form.submitButtonLabel, title: form.title, @@ -68,6 +69,8 @@ export type PreparedBuilderForm = { action: (values: Record, turnstileToken?: string) => Promise confirmation: ReactNode form: BuilderFormDoc + /** The page language — sent with a submission that carries files. */ + locale: string messages: Record redirectHref: null | string } @@ -116,6 +119,7 @@ export function prepareBuilderForm({ action: action.bind(null, String(form.id), locale), confirmation: rich(form.confirmationMessage), form: publicForm(form), + locale, messages, redirectHref, } diff --git a/src/modules/forms/attachments/config.ts b/src/modules/forms/attachments/config.ts new file mode 100644 index 0000000..d552fa8 --- /dev/null +++ b/src/modules/forms/attachments/config.ts @@ -0,0 +1,149 @@ +import type { BasePayload } from 'payload' + +import type { ClientIpOptions } from '../../shared/rateLimit.js' +import type { FormFileType } from './fileTypes.js' + +import { FORM_FILE_TYPES, MB, RISKY_FILE_EXTENSIONS } from './fileTypes.js' + +/** A file handed to `attachments.scan` — in memory, after every other check passed. */ +export type FormFileScanInput = { + data: Uint8Array + /** The field key of the File field it came from. */ + field: string + /** The cleaned name the attachment will carry. */ + name: string + size: number + /** Type key, e.g. 'pdf'. */ + type: string +} + +export type FormFileScanResult = { ok: boolean; reason?: string } + +/** + * `ipalKit({ forms: { attachments } })` — files on panel forms. They are + * NEVER stored: a file is checked, attached to the company e-mail, and dropped. + */ +export type FormAttachmentsOption = { + /** + * Extensions from the refused list (RISKY_FILE_EXTENSIONS: programs, macro-enabled + * Office files, archives, HTML/SVG…) this project accepts after all, e.g. `['zip']`. + * The extension still has to belong to a file type of the field (`fileTypes`). + */ + allowRisky?: string[] + /** + * Add a file type (`{ dwg: { label, extensions, mimeType, detect } }`), replace + * a built-in one, or remove one with `false`. + */ + fileTypes?: Record + /** File submissions handled at the same time, per instance. More get "try again". Default 2; 0 = no guard. */ + maxConcurrent?: number + /** Ceiling for a field's "Maximum files". Default 3. */ + maxFiles?: number + /** Ceiling for a field's "Maximum size (MB)". Default 10. */ + maxSizeMB?: number + /** Ceiling for all files of one submission, in MB. Default 10. */ + maxTotalMB?: number + /** + * The line added to the e-mail that carries a file ("…was not checked for + * viruses"). `false` leaves it out; a string or a function replaces it. + */ + notice?: ((locale: string | undefined) => string) | false | string + /** Path of the submit endpoint under the API route. Default '/ipal/forms/submit'. */ + path?: string + /** + * Antivirus hook. The plugin has NO malware scanner; plug one in here + * (ClamAV, a scanning API). Return `{ ok: false }` to refuse the file. + * A thrown error refuses the file too. + */ + scan?: (file: FormFileScanInput) => FormFileScanResult | Promise + /** + * 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 = { + allowedOrigins?: string[] + clientIp?: ClientIpOptions + /** Honeypot field name. Default HONEYPOT_FIELD. */ + honeypotField?: string + /** Max submissions per IP per minute. Default 5; 0 turns it off. */ + maxPerMinute?: number + turnstileHostnames?: string[] + turnstileOnConfigError?: 'allow' | 'reject' +} + +export type ResolvedFormAttachments = { + maxConcurrent: number + maxFiles: number + maxSizeMB: number + maxTotalMB: number + notice: FormAttachmentsOption['notice'] + path: string + risky: ReadonlySet + scan?: FormAttachmentsOption['scan'] + strictPdf: boolean + submit: FormSubmitEndpointOptions + types: Record +} + +export const FORM_SUBMIT_PATH = '/ipal/forms/submit' + +const positive = (value: number | undefined, fallback: number) => (typeof value === 'number' && value > 0 ? value : fallback) + +/** Defaults applied; `true` = everything default. */ +export function resolveFormAttachments(option: FormAttachmentsOption | true): ResolvedFormAttachments { + const o = option === true ? {} : option + const types: Record = { ...FORM_FILE_TYPES } + for (const [key, type] of Object.entries(o.fileTypes ?? {})) { + if (type === false) {delete types[key]} + else {types[key] = { ...type, extensions: type.extensions.map((e) => e.replace(/^\./, '').toLowerCase()) }} + } + const allowed = new Set((o.allowRisky ?? []).map((e) => e.replace(/^\./, '').toLowerCase())) + return { + maxConcurrent: typeof o.maxConcurrent === 'number' && o.maxConcurrent >= 0 ? o.maxConcurrent : 2, + maxFiles: Math.floor(positive(o.maxFiles, 3)), + maxSizeMB: positive(o.maxSizeMB, 10), + maxTotalMB: positive(o.maxTotalMB, positive(o.maxSizeMB, 10)), + notice: o.notice, + path: o.path ? `/${o.path.replace(/^\/+/, '')}` : FORM_SUBMIT_PATH, + risky: new Set(RISKY_FILE_EXTENSIONS.filter((e) => !allowed.has(e))), + scan: o.scan, + strictPdf: o.strictPdf === true, + submit: o.submit ?? {}, + types, + } +} + +/** The resolved option of this Payload instance, or null when `forms.attachments` is off. */ +export function getFormAttachments(payload: BasePayload): null | ResolvedFormAttachments { + const value = (payload.config?.custom as { ipal?: { formAttachments?: ResolvedFormAttachments } } | undefined)?.ipal?.formAttachments + return value ?? null +} + +/** A File field as the panel stores it. */ +export type FileFieldConfig = { + allowedTypes?: null | string[] + maxFiles?: null | number + maxSizeMB?: null | number + name?: null | string +} + +/** + * The limits that really apply to a File field: the editor's values, capped by + * the plugin option and by what the e-mail transport can carry (`transportMaxBytes`). + */ +export function fileFieldLimits(field: FileFieldConfig, options: ResolvedFormAttachments, transportMaxBytes?: null | number) { + const sizeMB = Math.min(positive(field.maxSizeMB ?? undefined, options.maxSizeMB), options.maxSizeMB) + const cap = typeof transportMaxBytes === 'number' ? transportMaxBytes : Infinity + return { + allowedTypes: (field.allowedTypes ?? []).filter((key) => options.types[key]), + maxBytes: Math.floor(Math.min(sizeMB * MB, cap)), + maxFiles: Math.max(1, Math.min(Math.floor(positive(field.maxFiles ?? undefined, 1)), options.maxFiles)), + maxTotalBytes: Math.floor(Math.min(options.maxTotalMB * MB, cap)), + } +} diff --git a/src/modules/forms/attachments/delivery.ts b/src/modules/forms/attachments/delivery.ts new file mode 100644 index 0000000..2fd2f58 --- /dev/null +++ b/src/modules/forms/attachments/delivery.ts @@ -0,0 +1,197 @@ +import type { BeforeEmail, FormattedEmail } from '@payloadcms/plugin-form-builder/types' +import type { BasePayload } from 'payload' + +import type { FormAttachmentsOption } from './config.js' +import type { AcceptedFormFile } from './fileGate.js' + +import { formatFileSize } from './fileTypes.js' + +/** + * Form files are delivered by e-mail and nowhere else. The files of one + * submission travel in the request context (memory only) from submitForm to + * form-builder's `beforeEmail`; these hooks attach them to the e-mails that go + * to the company, send those themselves — to see whether the mail server took + * them — and record the outcome on the same context object for submitForm. + */ +export const FORM_FILES_CONTEXT = 'ipalFormFiles' + +export type FormFileDelivery = { + files: AcceptedFormFile[] + /** Set by the delivery hook; absent = no e-mail was attempted. */ + result?: { note?: string; state: 'failed' | 'sent' } +} + +type EmailRow = { bcc?: null | string; cc?: null | string; emailTo?: null | string } +type FormWithEmails = { emails?: EmailRow[] | null } + +/** Addresses in a To/CC/BCC value ("Anna , b@y.pl"), lowercase. */ +export function emailAddresses(value: unknown): string[] { + const text = Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? v : ((v as { address?: string })?.address ?? ''))).join(',') : typeof value === 'string' ? value : '' + return text + .split(/[,;]/) + .map((part) => (part.match(/<([^>]+)>/)?.[1] ?? part).trim().toLowerCase()) + .filter((address) => address.includes('@')) +} + +const isFixedRow = (row: EmailRow) => ![row.emailTo, row.cc, row.bcc].some((v) => typeof v === 'string' && v.includes('{{')) + +/** + * True when the form has an e-mail whose To, CC and BCC are written in the + * panel as fixed addresses (no `{{field}}` placeholder). Only such e-mails may + * carry a file; without one a file could not be delivered at all. + */ +export function canCarryFiles(form: FormWithEmails | null | undefined): boolean { + return (form?.emails ?? []).some(isFixedRow) +} + +/** + * Every address the panel names as a fixed recipient. An e-mail with an empty + * "To" goes to the site's default address (form-builder's rule), so that one counts. + */ +export function fixedRecipients(form: FormWithEmails | null | undefined, defaultAddress?: string): Set { + const fixed = new Set() + for (const row of (form?.emails ?? []).filter(isFixedRow)) { + const to = emailAddresses(row.emailTo) + for (const address of [...(to.length ? to : emailAddresses(defaultAddress)), ...emailAddresses(row.cc), ...emailAddresses(row.bcc)]) {fixed.add(address)} + } + return fixed +} + +/** + * May this (already formatted) e-mail carry the file? Only when EVERY recipient + * is a fixed address from the panel. The confirmation to the visitor is + * addressed with a placeholder, so it never qualifies — whatever its template says. + */ +export function mayCarryFiles(email: Pick, fixed: ReadonlySet): boolean { + const recipients = [...emailAddresses(email.to), ...emailAddresses(email.cc), ...emailAddresses(email.bcc)] + return recipients.length > 0 && recipients.every((address) => fixed.has(address)) +} + +const isPolish = (locale: unknown) => typeof locale === 'string' && locale.toLowerCase().startsWith('pl') + +const escapeHtml = (text: string) => + text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + +const NOTICE_OPEN = '

' +const NOTICE = /

]*>[\s\S]*?<\/p>/ + +/** Default line under an e-mail that carries a form file. */ +export const fileNoticeText = (locale?: string) => + isPolish(locale) + ? 'Plik pochodzi z publicznego formularza i nie został sprawdzony pod kątem wirusów.' + : 'This file came from a public form and was not checked for viruses.' + +const fileList = (files: AcceptedFormFile[]) => files.map((f) => `${f.name} (${formatFileSize(f.size)})`).join(', ') + +const failureText = (files: AcceptedFormFile[], locale?: string) => + isPolish(locale) + ? `Odwiedzający dołączył plik: ${fileList(files)}, ale nie udało się go wysłać. Poproś o ponowne przesłanie.` + : `The visitor attached a file: ${fileList(files)}, but it could not be sent. Ask them to send it again.` + +type HookArgs = Parameters[1] + +const contextOf = (args: HookArgs): FormFileDelivery | undefined => { + const value = (args.req.context as Record | undefined)?.[FORM_FILES_CONTEXT] as FormFileDelivery | undefined + return value?.files?.length ? value : undefined +} + +async function loadFixed(args: HookArgs, formsSlug: string): Promise> { + const formRef = (args.data as { form?: unknown } | undefined)?.form + const id = formRef && typeof formRef === 'object' ? (formRef as { id: number | string }).id : (formRef as number | string) + const form = (await args.req.payload.findByID({ id, collection: formsSlug as never, depth: 0, req: args.req })) as FormWithEmails + return fixedRecipients(form, args.req.payload.email?.defaultFromAddress) +} + +/** + * First hook (before the e-mail layout): adds the "not checked for viruses" + * line to the e-mails that will carry the file, so the layout wraps it. + */ +export function buildFileNoticeHook({ formsSlug = 'forms', notice }: { formsSlug?: string; notice?: FormAttachmentsOption['notice'] } = {}): BeforeEmail { + return async (emails, args) => { + const delivery = contextOf(args) + if (!delivery || notice === false) {return emails} + try { + const fixed = await loadFixed(args, formsSlug) + const locale = typeof args.req.locale === 'string' ? args.req.locale : undefined + const text = typeof notice === 'function' ? notice(locale) : typeof notice === 'string' ? notice : fileNoticeText(locale) + return emails.map((email) => (mayCarryFiles(email, fixed) ? { ...email, html: `${email.html ?? ''}${NOTICE_OPEN}${escapeHtml(text)}

` } : email)) + } catch { + return emails // the delivery hook reports the real problem + } + } +} + +type SendOutcome = { detail?: string; ok: boolean } + +/** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */ +async function send(payload: BasePayload, message: { attachments?: unknown } & FormattedEmail): Promise { + try { + const result = (await payload.sendEmail(message as never)) as { detail?: string; error?: string; sent?: boolean } | null | undefined + if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false }} + return { ok: true } + } catch (err) { + return { detail: err instanceof Error ? err.message : String(err), ok: false } + } +} + +const firstLine = (text: string | undefined) => (text ?? '').split('\n')[0].slice(0, 200) + +/** + * Last hook (after the layout and the project's own beforeEmail): takes the + * e-mails that may carry the file, sends them WITH the attachments and records + * the outcome. The other e-mails (the confirmation to the visitor) are handed + * back to form-builder only when the file was handed to the mail server — a + * failed attempt confirms nothing to the visitor. + * + * On failure the staff e-mail goes out once more WITHOUT the file, saying that + * a file was attached and could not be sent. Each e-mail is sent once; there + * is no automatic retry (the file is not kept). + */ +export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}): BeforeEmail { + return async (emails, args) => { + const delivery = contextOf(args) + if (!delivery) {return emails} + const { payload } = args.req + const locale = typeof args.req.locale === 'string' ? args.req.locale : undefined + try { + const fixed = await loadFixed(args, formsSlug) + const carriers = emails.filter((email) => mayCarryFiles(email, fixed)) + if (carriers.length === 0) { + delivery.result = { note: 'No e-mail of this form has a fixed recipient, so the file had nowhere to go.', state: 'failed' } + return [] + } + const attachments = delivery.files.map((file) => ({ + content: Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength), + contentDisposition: 'attachment' as const, + contentType: file.mimeType, + filename: file.name, + })) + const outcomes: SendOutcome[] = [] + for (const email of carriers) {outcomes.push(await send(payload, { ...email, attachments }))} + + if (outcomes.some((o) => o.ok)) { + delivery.result = { state: 'sent' } + // A recipient whose copy failed still learns about the submission, without the file. + await Promise.all(carriers.filter((_, i) => !outcomes[i].ok).map((email) => send(payload, withFailureNotice(email, delivery.files, locale)))) + return emails.filter((email) => !carriers.includes(email)) + } + + const detail = firstLine(outcomes.find((o) => o.detail)?.detail) + delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' } + payload.logger.error(`[ipal] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`) + await Promise.all(carriers.map((email) => send(payload, withFailureNotice(email, delivery.files, locale)))) + return [] + } catch (err) { + delivery.result = { note: firstLine(err instanceof Error ? err.message : String(err)), state: 'failed' } + payload.logger.error(`[ipal] Form file delivery failed: ${(err as Error).message}`) + return [] + } + } +} + +/** The staff e-mail without the file: the virus line gives way to "could not be sent — ask again". */ +function withFailureNotice(email: FormattedEmail, files: AcceptedFormFile[], locale?: string): FormattedEmail { + const notice = `

${escapeHtml(failureText(files, locale))}

` + const html = email.html ?? '' + return { ...email, html: NOTICE.test(html) ? html.replace(NOTICE, notice) : `${html}${notice}` } +} diff --git a/src/modules/forms/attachments/endpoint.ts b/src/modules/forms/attachments/endpoint.ts new file mode 100644 index 0000000..dc6a8fe --- /dev/null +++ b/src/modules/forms/attachments/endpoint.ts @@ -0,0 +1,19 @@ +import type { Endpoint } from 'payload' + +import type { ResolvedFormAttachments } from './config.js' + +/** + * POST /api/ipal/forms/submit — where a panel form with a file posts + * (multipart/form-data: the answers first, the files last). Registered by the + * plugin when `forms.attachments` is on; a project wires nothing. + * + * The handler is loaded on the first request: it pulls in the submit pipeline + * (server-only) and the multipart parser, which a config load must not. + */ +export function buildFormSubmitEndpoint(options: ResolvedFormAttachments): Endpoint { + return { + handler: async (req) => (await import('./submitHandler.js')).handleFormSubmit(req), + method: 'post', + path: options.path, + } +} diff --git a/src/modules/forms/attachments/fileBlock.ts b/src/modules/forms/attachments/fileBlock.ts new file mode 100644 index 0000000..b3f317f --- /dev/null +++ b/src/modules/forms/attachments/fileBlock.ts @@ -0,0 +1,97 @@ +import type { Block, Field } from 'payload' + +import type { FormAttachmentsOption, ResolvedFormAttachments } from './config.js' + +import { withShowWhen } from '../builderBlocks.js' +import { resolveFormAttachments } from './config.js' +import { DEFAULT_FORM_FILE_TYPES } from './fileTypes.js' + +/** + * The "File" field of the form builder. The file a visitor attaches is never + * stored: it is checked and sent with the company e-mail (docs/forms.md). + * + * forms: { attachments: true } // adds the block + * forms: { attachments: true, fields: { file: buildFileBlock({ maxSizeMB: 5 }) } } // your own variant + */ +export function buildFileBlock(option: FormAttachmentsOption | ResolvedFormAttachments | true = true): Block { + const o = option !== true && 'types' in option ? option : resolveFormAttachments(option) + const half = { width: '50%' } + const fields: Field[] = [ + { + type: 'row', + fields: [ + { + name: 'name', + type: 'text', + admin: { ...half, description: { en: 'No spaces, e.g. attachment.', pl: 'Bez spacji, np. zalacznik.' } }, + label: { en: 'Field key', pl: 'Klucz pola' }, + required: true, + }, + { name: 'label', type: 'text', admin: half, label: { en: 'Label', pl: 'Etykieta' }, localized: true }, + ], + }, + { + name: 'help', + type: 'text', + admin: { + description: { en: 'Shown under the field.', pl: 'Widoczny pod polem.' }, + placeholder: { en: 'e.g. PDF or DOCX, up to 10 MB', pl: 'np. PDF lub DOCX, do 10 MB' }, + }, + label: { en: 'Help text', pl: 'Tekst pomocy' }, + localized: true, + }, + { + type: 'row', + fields: [ + { name: 'width', type: 'number', admin: half, label: { en: 'Width (%)', pl: 'Szerokość (%)' } }, + { name: 'required', type: 'checkbox', admin: half, label: { en: 'Required', pl: 'Wymagane' } }, + ], + }, + { + name: 'allowedTypes', + type: 'select', + admin: { + description: { + en: 'The file is sent by e-mail and is not kept on the site.', + pl: 'Plik jest wysyłany e-mailem i nie jest przechowywany w witrynie.', + }, + }, + defaultValue: DEFAULT_FORM_FILE_TYPES.filter((key) => o.types[key]), + hasMany: true, + label: { en: 'Allowed file types', pl: 'Dozwolone typy plików' }, + options: Object.entries(o.types).map(([value, type]) => ({ label: type.label, value })), + required: true, + }, + { + type: 'row', + fields: [ + { + name: 'maxSizeMB', + type: 'number', + admin: half, + defaultValue: o.maxSizeMB, + label: { en: 'Maximum size (MB)', pl: 'Maksymalny rozmiar (MB)' }, + max: o.maxSizeMB, + min: 1, + }, + { + name: 'maxFiles', + type: 'number', + admin: half, + defaultValue: 1, + label: { en: 'Maximum files', pl: 'Maksymalna liczba plików' }, + max: o.maxFiles, + min: 1, + }, + ], + }, + ] + return withShowWhen({ + slug: 'file', + fields, + labels: { plural: { en: 'File fields', pl: 'Pola pliku' }, singular: { en: 'File', pl: 'Plik' } }, + }) +} + +/** The File block with default limits — `forms.fields.file: fileBlock`, or build your own with buildFileBlock. */ +export const fileBlock: Block = buildFileBlock(true) diff --git a/src/modules/forms/attachments/fileChecks.ts b/src/modules/forms/attachments/fileChecks.ts new file mode 100644 index 0000000..264d02b --- /dev/null +++ b/src/modules/forms/attachments/fileChecks.ts @@ -0,0 +1,193 @@ +import type { FormFileType } from './fileTypes.js' + +import { fileExtensions } from './fileTypes.js' + +/** + * Content checks for form files — by the bytes, never by the name or the + * browser's MIME type alone. They stop the wrong KIND of file. They are not an + * antivirus: a well-formed PDF or DOC can still be malicious (attachments.scan). + */ + +const startsWith = (bytes: Uint8Array, signature: readonly number[], offset = 0) => + bytes.length >= offset + signature.length && signature.every((b, i) => bytes[offset + i] === b) + +const ascii = (text: string) => [...text].map((c) => c.charCodeAt(0)) + +const OLE = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1] +const ZIP = [0x50, 0x4b, 0x03, 0x04] + +/** How many leading bytes `signatureMatches` needs. */ +export const SIGNATURE_BYTES = 16 + +/** Programs, whatever they are named: Windows (MZ), Linux (ELF), macOS (Mach-O), scripts (#!). */ +export function looksExecutable(bytes: Uint8Array): boolean { + return ( + startsWith(bytes, [0x4d, 0x5a]) || + startsWith(bytes, [0x7f, 0x45, 0x4c, 0x46]) || + startsWith(bytes, [0xfe, 0xed, 0xfa, 0xce]) || + startsWith(bytes, [0xfe, 0xed, 0xfa, 0xcf]) || + startsWith(bytes, [0xce, 0xfa, 0xed, 0xfe]) || + startsWith(bytes, [0xcf, 0xfa, 0xed, 0xfe]) || + startsWith(bytes, [0xca, 0xfe, 0xba, 0xbe]) || + startsWith(bytes, ascii('#!')) + ) +} + +/** + * First-bytes check for a built-in type key; `undefined` for a key without one + * (a project's own type — its `detect` runs on the whole file instead). + */ +export function signatureMatches(key: string, head: Uint8Array): boolean | undefined { + switch (key) { + case 'doc': + case 'xls': + return startsWith(head, OLE) + case 'docx': + case 'odt': + case 'xlsx': + return startsWith(head, ZIP) + case 'jpg': + return startsWith(head, [0xff, 0xd8, 0xff]) + case 'pdf': + return startsWith(head, ascii('%PDF-')) + case 'png': + return startsWith(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + case 'rtf': + return startsWith(head, ascii('{\\rtf')) + case 'webp': + return startsWith(head, ascii('RIFF')) && startsWith(head, ascii('WEBP'), 8) + default: + return undefined + } +} + +type ZipEntry = { encrypted: boolean; name: string } + +const u16 = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8) +const u32 = (b: Uint8Array, o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0 + +/** + * Entry names from a ZIP's central directory — read WITHOUT unpacking anything, + * so a zip bomb costs nothing. `null` when the archive has no readable directory. + */ +export function zipEntries(bytes: Uint8Array, maxEntries = 5000): null | ZipEntry[] { + // End-of-central-directory record: in the last 22 bytes + up to 64 KB of comment. + const min = Math.max(0, bytes.length - 22 - 0xffff) + let eocd = -1 + for (let i = bytes.length - 22; i >= min; i--) { + if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) { + eocd = i + break + } + } + if (eocd < 0) {return null} + const count = u16(bytes, eocd + 10) + let offset = u32(bytes, eocd + 16) + if (count > maxEntries) {return null} + const entries: ZipEntry[] = [] + const decoder = new TextDecoder() + for (let i = 0; i < count; i++) { + if (offset + 46 > bytes.length || u32(bytes, offset) !== 0x02014b50) {return null} + const flags = u16(bytes, offset + 8) + const nameLength = u16(bytes, offset + 28) + const extraLength = u16(bytes, offset + 30) + const commentLength = u16(bytes, offset + 32) + if (offset + 46 + nameLength > bytes.length) {return null} + entries.push({ name: decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)), encrypted: (flags & 1) === 1 }) + offset += 46 + nameLength + extraLength + commentLength + } + return entries +} + +/** Entries a container of this type must have. */ +const REQUIRED_ENTRIES: Record = { + docx: ['[Content_Types].xml', 'word/document.xml'], + odt: ['mimetype', 'content.xml'], + xlsx: ['[Content_Types].xml', 'xl/workbook.xml'], +} + +const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)$/i + +const indexOfBytes = (bytes: Uint8Array, needle: readonly number[]) => { + outer: for (let i = 0; i <= bytes.length - needle.length; i++) { + for (let j = 0; j < needle.length; j++) { + if (bytes[i + j] !== needle[j]) {continue outer} + } + return i + } + return -1 +} + +const utf16 = (text: string) => [...text].flatMap((c) => [c.charCodeAt(0), 0]) + +/** + * VBA macros in a legacy Office file: the macro storage holds a stream named + * `_VBA_PROJECT` (Word: Macros/VBA/_VBA_PROJECT, Excel: _VBA_PROJECT_CUR), and + * the compound file's directory stores names as UTF-16. BEST-EFFORT — it finds + * ordinary macro-enabled documents, not one built to hide. + */ +export function oleHasMacros(bytes: Uint8Array): boolean { + return indexOfBytes(bytes, utf16('_VBA_PROJECT')) >= 0 +} + +/** PDF features that run code or carry other files — a plain byte search (attachments.strictPdf). */ +export function pdfHasActiveContent(bytes: Uint8Array): boolean { + return ['/JavaScript', '/JS ', '/JS(', '/Launch', '/EmbeddedFile', '/OpenAction'].some((token) => indexOfBytes(bytes, ascii(token)) >= 0) +} + +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' + +/** + * 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. + */ +export function matchFileType( + name: string, + allowed: readonly string[], + types: Record, + risky: ReadonlySet, +): { key: string; type: FormFileType } | { refused: 'name' } { + const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '') + const last = extensions.at(-1) + if (!last || extensions.some((e) => risky.has(e))) {return { refused: 'name' }} + // "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' }} + for (const key of allowed) { + const type = types[key] + if (type?.extensions.includes(last)) {return { key, type }} + } + return { refused: 'name' } +} + +/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */ +export async function checkFileContent( + key: string, + type: FormFileType, + bytes: Uint8Array, + { strictPdf = false }: { strictPdf?: boolean } = {}, +): Promise { + if (bytes.length === 0 || looksExecutable(bytes)) {return 'signature'} + const signature = signatureMatches(key, bytes.subarray(0, SIGNATURE_BYTES)) + if (signature === false) {return 'signature'} + if (type.detect && !(await type.detect(bytes))) {return 'signature'} + + const required = REQUIRED_ENTRIES[key] + if (required) { + const entries = zipEntries(bytes) + if (!entries) {return 'signature'} + const names = new Set(entries.map((e) => e.name)) + if (required.some((name) => !names.has(name))) {return 'signature'} + if (entries.some((e) => e.encrypted || /vbaProject\.bin$/i.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'} + } + if ((key === 'doc' || key === 'xls') && oleHasMacros(bytes)) {return 'content'} + if (key === 'pdf' && strictPdf && pdfHasActiveContent(bytes)) {return 'content'} + return null +} diff --git a/src/modules/forms/attachments/fileGate.ts b/src/modules/forms/attachments/fileGate.ts new file mode 100644 index 0000000..0d5efb8 --- /dev/null +++ b/src/modules/forms/attachments/fileGate.ts @@ -0,0 +1,167 @@ +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' + +/** A file that passed every check — in memory, ready for the e-mail. */ +export type AcceptedFormFile = { + data: Uint8Array + /** Field key of the File field. */ + field: string + mimeType: string + /** Cleaned name with the extension of the detected type. */ + name: string + size: number + /** Type key, e.g. 'pdf'. */ + type: string +} + +/** Why a file was refused — a code for resolveFormMessage, never text. */ +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' + /** The limit: MB for file_too_large, a count for file_count. */ + max?: number + /** "PDF, DOC, DOCX" — for file_type. */ + types?: string +} + +type FileField = { name: string; required?: boolean | null } & FileFieldConfig + +/** One file being received. */ +export type FileSlot = { + /** Feed the first bytes as they arrive (any chunking). Returns a failure as soon as the signature is wrong. */ + checkStart: (head: Uint8Array) => FormFileFailure | null + /** Bytes this file may have; reading must stop past it. */ + maxBytes: number + /** Call when a read went past `maxBytes`. */ + tooLarge: () => FormFileFailure +} + +// eslint-disable-next-line no-control-regex +const displayName = (name: string) => (name.split(/[/\\]/).pop() ?? '').replace(/[\u0000-\u001F\u007F‪-‮⁦-⁩]/g, '').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) => { + const mb = bytes / MB + return Number.isInteger(mb) ? mb : Math.floor(mb * 10) / 10 +} + +/** + * The file checks of one submission, in the order the wall needs them: + * `begin` (field, count, name — before any byte), the slot (size while reading, + * signature on the first bytes), `finish` (whole-file checks, scan), `end` + * (required fields). Used by the streaming endpoint and, with whole buffers, + * by submitForm({ files }). + */ +export function createFileGate({ + fields, + options, + transportMaxBytes, +}: { + /** The form's File fields the visitor could see. */ + fields: FileField[] + options: ResolvedFormAttachments + /** What the e-mail transport can carry, when it has a ceiling. */ + transportMaxBytes?: null | number +}) { + const byName = new Map(fields.map((f) => [f.name, f])) + const counts = new Map() + const accepted: AcceptedFormFile[] = [] + let total = 0 + + const begin = (fieldName: string, rawName: string): { failure: FormFileFailure } | { slot: FileSlot; token: BeginToken } => { + const field = byName.get(fieldName) + if (!field) {return { failure: { field: fieldName, kind: 'unknown_fields' } }} + const limits = fileFieldLimits(field, options, transportMaxBytes) + 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 types = describeFileTypes(limits.allowedTypes, options.types).labels + const typeFailure: FormFileFailure = { field: fieldName, file, kind: 'file_type', types } + const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky) + if ('refused' in match) {return { failure: typeFailure }} + + 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) }) + 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 + }, + maxBytes, + tooLarge, + }, + token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure }, + } + } + + 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} + const file: AcceptedFormFile = { + name: safeFileName(token.rawName, type.extensions[0]), + type: token.key, + data, + field: token.field, + mimeType: type.mimeType, + size: data.length, + } + 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} + } catch { + return token.typeFailure + } + } + total += data.length + accepted.push(file) + return null + } + + /** After the last file: a required File field without a file. */ + const end = (): FormFileFailure | null => { + for (const field of fields) { + if (field.required && !accepted.some((f) => f.field === field.name)) {return { field: field.name, kind: 'required' }} + } + return null + } + + return { accepted, begin, end, finish } +} + +type BeginToken = { + field: string + file: string + key: string + maxBytes: number + rawName: string + tooLarge: () => FormFileFailure + typeFailure: FormFileFailure +} + +export type FileGate = ReturnType + +/** Whole buffers through the same checks, in order. */ +export async function checkBufferedFiles(gate: FileGate, files: Record): Promise { + for (const [field, list] of Object.entries(files)) { + for (const file of list) { + const started = gate.begin(field, file.name) + if ('failure' in started) {return started.failure} + if (file.data.length > started.slot.maxBytes) {return started.slot.tooLarge()} + const failure = started.slot.checkStart(file.data.subarray(0, 64)) ?? (await gate.finish(started.token, file.data)) + if (failure) {return failure} + } + } + return gate.end() +} diff --git a/src/modules/forms/attachments/fileTypes.ts b/src/modules/forms/attachments/fileTypes.ts new file mode 100644 index 0000000..e759851 --- /dev/null +++ b/src/modules/forms/attachments/fileTypes.ts @@ -0,0 +1,109 @@ +/** + * File types a form's File field can accept — pure data and helpers, shared by + * the panel block, the browser (accept, instant checks) and the server (the + * real checks, fileChecks.ts). No Node APIs here. + */ + +/** What a custom `detect` receives: the whole file. */ +export type FormFileDetect = (bytes: Uint8Array) => boolean | Promise + +export type FormFileType = { + /** + * Content check for a project's own type: true when the bytes really are this + * type. Built-in types have their own checks (fileChecks.ts). A type without + * `detect` and without a built-in check is accepted by extension only. + */ + detect?: FormFileDetect + /** Lowercase, without the dot. The first one names the attachment. */ + extensions: string[] + /** Shown to the editor (panel option) and the visitor ("Accepted: PDF, DOCX"). */ + label: string + mimeType: string +} + +/** Built-in types. Keys are what the File field stores in `allowedTypes`. */ +export const FORM_FILE_TYPES: Record = { + doc: { extensions: ['doc'], label: 'DOC', mimeType: 'application/msword' }, + docx: { extensions: ['docx'], label: 'DOCX', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }, + jpg: { extensions: ['jpg', 'jpeg'], label: 'JPG', mimeType: 'image/jpeg' }, + odt: { extensions: ['odt'], label: 'ODT', mimeType: 'application/vnd.oasis.opendocument.text' }, + pdf: { extensions: ['pdf'], label: 'PDF', mimeType: 'application/pdf' }, + png: { extensions: ['png'], label: 'PNG', mimeType: 'image/png' }, + rtf: { extensions: ['rtf'], label: 'RTF', mimeType: 'application/rtf' }, + webp: { extensions: ['webp'], label: 'WebP', mimeType: 'image/webp' }, + xls: { extensions: ['xls'], label: 'XLS', mimeType: 'application/vnd.ms-excel' }, + xlsx: { extensions: ['xlsx'], label: 'XLSX', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }, +} + +/** Ticked on a new File field. */ +export const DEFAULT_FORM_FILE_TYPES = ['pdf', 'doc', 'docx'] + +/** + * Extensions refused whatever a field allows: programs and scripts, macro-enabled + * Office files, archives, disk images, and files a browser or mail client may run. + * A project lifts single ones with `attachments.allowRisky`. + */ +export const RISKY_FILE_EXTENSIONS = [ + // programs and scripts + 'apk', 'app', 'bat', 'bin', 'cmd', 'com', 'cpl', 'dll', 'exe', 'gadget', 'hta', 'jar', 'js', 'jse', 'lnk', 'mjs', 'msc', + 'msi', 'msp', 'pif', 'ps1', 'psm1', 'py', 'reg', 'scr', 'sh', 'vb', 'vbe', 'vbs', 'ws', 'wsf', 'wsh', + // macro-enabled Office + 'docm', 'dotm', 'potm', 'ppam', 'ppsm', 'pptm', 'xlam', 'xlsm', 'xltm', + // archives and disk images + '7z', 'bz2', 'cab', 'dmg', 'gz', 'img', 'iso', 'rar', 'tar', 'tgz', 'xz', 'zip', + // markup a browser or mail client renders + 'htm', 'html', 'mht', 'mhtml', 'shtml', 'svg', 'xhtml', 'xml', +] + +export const MB = 1024 * 1024 + +/** "2.1 MB", "640 KB" — for the file list, the answers row and e-mails. */ +export function formatFileSize(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) {return ''} + if (bytes < 1024) {return `${bytes} B`} + if (bytes < MB) {return `${Math.round(bytes / 1024)} KB`} + const mb = bytes / MB + return `${mb >= 10 ? Math.round(mb) : Math.round(mb * 10) / 10} MB` +} + +/** Every extension of a name, lowercase: "CV.final.PDF" → ['final', 'pdf']. */ +export function fileExtensions(name: string): string[] { + const parts = name.split('.').slice(1) + return parts.map((p) => p.trim().toLowerCase()).filter(Boolean) +} + +// Control characters and bidi overrides (a name like "cv‮fdp.exe" reads as "cvexe.pdf"). +// eslint-disable-next-line no-control-regex +const UNSAFE = /[\u0000-\u001F\u007F​-‏‪-‮⁦-⁩]/g + +/** + * The name shown to staff and used on the attachment — never the raw client + * string: no path, no control or bidi characters, only letters, digits, space + * and `.-_()` in the stem, at most 80 characters, and the extension of the + * DETECTED type. An empty stem becomes "attachment". + */ +export function safeFileName(name: string, extension: string): string { + const base = (name.split(/[/\\]/).pop() ?? '').replace(UNSAFE, '').normalize('NFC') + const stem = base + .replace(/\.[^.]*$/, '') + .replace(/[^\p{L}\p{N} ._()-]+/gu, ' ') + .replace(/\.{2,}/g, '.') + .replace(/\s+/g, ' ') + .replace(/^[\s.]+|[\s.]+$/g, '') + .slice(0, 80) + .trim() + return `${stem || 'attachment'}.${extension}` +} + +/** 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) { + const list = (keys ?? []).map((key) => types[key]).filter((t): t is FormFileType => Boolean(t)) + const extensions = [...new Set(list.flatMap((t) => t.extensions))] + return { + /** For ``: extensions first (what browsers filter on), then MIME types. */ + accept: [...extensions.map((e) => `.${e}`), ...new Set(list.map((t) => t.mimeType))].join(','), + extensions, + /** "PDF, DOC, DOCX" */ + labels: list.map((t) => t.label).join(', '), + } +} diff --git a/src/modules/forms/attachments/formHooks.ts b/src/modules/forms/attachments/formHooks.ts new file mode 100644 index 0000000..898a6c9 --- /dev/null +++ b/src/modules/forms/attachments/formHooks.ts @@ -0,0 +1,124 @@ +import type { CollectionAfterReadHook, CollectionBeforeValidateHook, Field } from 'payload' + +import { ValidationError } from 'payload' + +import type { FileFieldConfig, ResolvedFormAttachments } from './config.js' + +import { mailAttachmentLimit } from '../../email/attachmentLimit.js' +import { fileFieldLimits } from './config.js' +import { canCarryFiles } from './delivery.js' +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 } + +const fileBlocks = (doc: FormDoc | null | undefined) => (Array.isArray(doc?.fields) ? doc.fields.filter((f) => f?.blockType === 'file') : []) + +/** + * Forms afterRead: every File field gets `resolved` — the limits that REALLY + * apply (the editor's values, capped by the plugin option and by what the + * e-mail transport can carry) and the `accept` list of its types — and the form + * gets `fileSubmitUrl`. The browser shows and checks exactly what the server + * will enforce, also for a project's own file types. Nothing is stored. + */ +export function buildFormFilesAfterRead(options: ResolvedFormAttachments): CollectionAfterReadHook { + return async ({ doc, req }) => { + const blocks = fileBlocks(doc as FormDoc) + if (blocks.length === 0) {return doc} + const transportMax = await mailAttachmentLimit(req.payload) + for (const block of blocks) { + const limits = fileFieldLimits(block, options, transportMax) + const types = describeFileTypes(limits.allowedTypes, options.types) + block.resolved = { + accept: types.accept, + extensions: types.extensions, + maxFiles: limits.maxFiles, + maxSizeMB: limitInMB(limits.maxBytes), + maxTotalMB: limitInMB(limits.maxTotalBytes), + typeLabels: types.labels, + } + } + ;(doc as FormDoc).fileSubmitUrl = `${req.payload.config.routes?.api ?? '/api'}${options.path}` + return doc + } +} + +/** + * Forms beforeValidate: a form with a File field needs an e-mail whose + * recipients are fixed addresses — files are delivered by e-mail only, and an + * e-mail addressed with a placeholder (the confirmation to the visitor) never + * carries one. Without such an e-mail the file would have nowhere to go. + */ +export function buildFormFilesBeforeValidate(): CollectionBeforeValidateHook { + return ({ data, originalDoc, req }) => { + const form = { ...(originalDoc as FormDoc | undefined), ...(data as FormDoc | undefined) } + if (fileBlocks(form).length === 0 || canCarryFiles(form)) {return data} + const polish = req.i18n?.language === 'pl' + throw new ValidationError({ + collection: 'forms', + errors: [ + { + message: polish + ? 'Dodaj e-mail ze stałym adresem odbiorcy. Pliki z formularza są wysyłane wyłącznie e-mailem.' + : 'Add an e-mail with a fixed recipient address. Files from the form are sent by e-mail only.', + path: 'emails', + }, + ], + }) + } +} + +/** + * Fields the submission keeps about files — metadata only, never the file: + * name, type and size, whether the mail server took the message, and the key + * that makes a repeated request harmless. + */ +export const submissionFileFields: Field[] = [ + { + name: 'submissionFiles', + type: 'array', + admin: { + description: { + en: 'Sent by e-mail to the form recipients. The files are not kept on the site.', + pl: 'Wysłane e-mailem do odbiorców formularza. Pliki nie są przechowywane w witrynie.', + }, + readOnly: true, + }, + fields: [ + { + type: 'row', + fields: [ + { name: 'name', type: 'text', admin: { width: '40%' }, label: { en: 'File name', pl: 'Nazwa pliku' } }, + { name: 'type', type: 'text', admin: { width: '20%' }, label: { en: 'Type', pl: 'Typ' } }, + { name: 'size', type: 'number', admin: { width: '20%' }, label: { en: 'Size (bytes)', pl: 'Rozmiar (bajty)' } }, + { name: 'field', type: 'text', admin: { width: '20%' }, label: { en: 'Field key', pl: 'Klucz pola' } }, + ], + }, + ], + label: { en: 'Files', pl: 'Pliki' }, + labels: { plural: { en: 'Files', pl: 'Pliki' }, singular: { en: 'File', pl: 'Plik' } }, + }, + { + name: 'filesDelivery', + type: 'select', + admin: { position: 'sidebar', readOnly: true }, + label: { en: 'File delivery', pl: 'Dostarczenie pliku' }, + options: [ + { label: { en: 'Handed to the mail server', pl: 'Przekazano do serwera poczty' }, value: 'sent' }, + { label: { en: 'Not sent', pl: 'Nie wysłano' }, value: 'failed' }, + ], + }, + { + name: 'filesDeliveryNote', + type: 'text', + admin: { + condition: (data) => Boolean(data?.filesDeliveryNote), + description: { en: 'Ask the sender for the file again.', pl: 'Poproś nadawcę o ponowne przesłanie pliku.' }, + position: 'sidebar', + readOnly: true, + }, + label: { en: 'Delivery note', pl: 'Uwaga o dostarczeniu' }, + }, + { name: 'attemptKey', type: 'text', admin: { hidden: true }, index: true }, +] diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts new file mode 100644 index 0000000..9710883 --- /dev/null +++ b/src/modules/forms/attachments/submitHandler.ts @@ -0,0 +1,292 @@ +import 'server-only' + +import type { BasePayload, PayloadRequest } from 'payload' + +import busboy from 'busboy' +import { Readable } from 'node:stream' + +import type { FormNotificationTexts } from '../../notifications/types.js' +import type { SubmitActionResult } from '../createSubmitAction.js' +import type { SubmitFormResult } from '../submitForm.js' +import type { FileGate } from './fileGate.js' + +import { mailAttachmentLimit } from '../../email/attachmentLimit.js' +import { getNotificationTexts } from '../../notifications/getNotificationTexts.js' +import { resolveFormMessage } from '../../notifications/resolveFormMessage.js' +import { clientIp } from '../../shared/rateLimit.js' +import { HONEYPOT_FIELD, isHoneypotTripped } from '../honeypot.js' +import { + cleanAttemptKey, + fileFailure, + findSubmitAttempt, + passRateLimit, + passTurnstile, + storeSubmission, + validateSubmitFields, +} from '../submitForm.js' +import { getFormAttachments } from './config.js' +import { canCarryFiles } from './delivery.js' +import { createFileGate } from './fileGate.js' +import { MB } from './fileTypes.js' + +/** Room for the text parts and the multipart envelope, on top of the files. */ +const ENVELOPE_BYTES = 256 * 1024 +/** The answers as JSON: every field is capped at 5000 characters by validation; this is the outer ceiling. */ +const VALUES_BYTES = 128 * 1024 + +const STATUS: Record = { consent: 422, delivery: 502, error: 500, not_found: 404, rate_limited: 429, turnstile: 403, validation: 422 } + +/** File submissions in flight in this process — the concurrency guard. */ +let active = 0 +/** Attempt keys being handled right now → their outcome, so a duplicate request waits instead of sending twice. */ +const inflight = new Map>() + +function originAllowed(req: PayloadRequest, allowed: readonly string[] = []): boolean { + const headers = req.headers + const origin = headers.get('origin') + if (origin && allowed.some((a) => a.replace(/\/$/, '') === origin)) {return true} + const site = headers.get('sec-fetch-site') + if (site) {return site === 'same-origin'} + if (!origin) {return true} // not a browser — the gates below still apply + try { + const host = new URL(origin).host + return host === (headers.get('x-forwarded-host') ?? headers.get('host')) + } catch { + return false + } +} + +function localeOf(payload: BasePayload, value: unknown): string | undefined { + if (typeof value !== 'string' || !value) {return undefined} + const localization = payload.config.localization + if (!localization) {return undefined} + return localization.localeCodes.includes(value) ? value : undefined +} + +/** + * The submit endpoint for forms with files. The request body is read as a + * stream, and every step runs before the next starts: + * + * origin → rate limit → declared size → concurrency guard → the answers + * (honeypot, Turnstile, validation, consent) → is there an e-mail to carry a + * file → per file: field, count, name → size while reading, signature on the + * first bytes → whole-file checks, scan → e-mail → the buffers are dropped. + * + * After a refusal nothing more is kept: the rest of the body is read and + * thrown away (so the browser gets the answer instead of a broken connection), + * and past the hard ceiling the connection is cut. + */ +export async function handleFormSubmit(req: PayloadRequest): Promise { + const { payload } = req + const options = getFormAttachments(payload) + if (!options) {return Response.json({ success: false }, { status: 404 })} + const submit = options.submit + + let locale = localeOf(payload, new URL(req.url ?? 'http://localhost').searchParams.get('locale')) + let texts: FormNotificationTexts | undefined + const respond = async (result: SubmitFormResult, status?: number): Promise => { + texts ??= (await getNotificationTexts({ locale, payload })).form + const body: SubmitActionResult = result.success + ? { message: resolveFormMessage(result, texts), success: true } + : { + message: resolveFormMessage(result, texts), + reason: result.reason, + success: false, + ...('field' in result && result.field ? { field: result.field } : {}), + } + return Response.json(body, { headers: { 'Cache-Control': 'no-store' }, status: status ?? (result.success ? 200 : (STATUS[result.reason] ?? 400)) }) + } + + // 1. Same origin, the right kind of request. + if (!originAllowed(req, submit.allowedOrigins)) {return respond({ reason: 'error', success: false }, 403)} + const contentType = req.headers.get('content-type') ?? '' + if (!/^multipart\/form-data/i.test(contentType) || !req.body) {return respond({ reason: 'error', success: false }, 415)} + + // 2. Rate limit — from the headers alone, before a byte of the body. + const ip = clientIp(req.headers, submit.clientIp) || undefined + const limited = await passRateLimit({ ip, maxPerMinute: submit.maxPerMinute }) + if (limited) {return respond(limited)} + + // 3. A body that declares itself too large is refused unread. + const hardCap = Math.floor(options.maxTotalMB * MB) + ENVELOPE_BYTES + const declared = Number(req.headers.get('content-length')) + if (Number.isFinite(declared) && declared > hardCap) {return respond({ reason: 'error', success: false }, 413)} + + // 4. Concurrency guard — each file submission holds its files in memory. + if (options.maxConcurrent > 0 && active >= options.maxConcurrent) {return respond({ reason: 'rate_limited', success: false })} + active++ + + let registered: string | undefined + let settle: ((result: SubmitFormResult) => void) | undefined + let final: SubmitFormResult = { reason: 'error', success: false } + try { + final = await new Promise((resolve) => { + const fields: Record = {} + /** Set once → nothing more is kept; the rest of the body is discarded. */ + let outcome: null | SubmitFormResult = null + let gate: FileGate | null = null + let stored: null | Parameters[0] = null + let pre: null | Promise = null + let chain: Promise = Promise.resolve() + let received = 0 + + const source = Readable.fromWeb(req.body as never) + const parser = busboy({ + headers: { 'content-type': contentType }, + limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 }, + }) + + const stop = (result: SubmitFormResult) => { + outcome ??= result + } + + /** 5–8: everything that must hold before the first file byte is accepted. */ + const beforeFiles = async () => { + locale = localeOf(payload, fields._locale) ?? locale + const formId = fields._form + let values: unknown + try { + values = JSON.parse(fields._values ?? '') + } catch { + values = null + } + if (!formId || !values || typeof values !== 'object' || Array.isArray(values)) {return stop({ reason: 'error', success: false })} + const data = values as Record + + // Honeypot: a fake success, nothing checked further, nothing kept. + const honeypot = submit.honeypotField ?? HONEYPOT_FIELD + if (isHoneypotTripped(data, honeypot)) {return stop({ submissionId: '', success: true })} + const { [honeypot]: _honeypot, ...answers } = data + + const token = fields._token?.trim() || undefined + const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token }) + if (blocked) {return stop(blocked)} + + const checked = await validateSubmitFields({ data: answers, formId, locale, payload }) + if ('failure' in checked) {return stop(checked.failure)} + + // A repeated request (same attempt key) gets the first answer; nothing is sent twice. + const attemptKey = cleanAttemptKey(fields._attempt) + if (attemptKey) { + const running = inflight.get(attemptKey) + if (running) {return stop(await running)} + const earlier = await findSubmitAttempt(payload, attemptKey) + if (earlier) {return stop(earlier)} + registered = attemptKey + inflight.set(attemptKey, new Promise((done) => (settle = done))) + } + + if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })} + gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes: await mailAttachmentLimit(payload) }) + stored = { attemptKey, formId, locale, payload, validation: checked.validation } + } + + const receiveFile = async (name: string, stream: { truncated?: boolean } & Readable, filename: string) => { + pre ??= beforeFiles() + await pre + if (outcome || !gate || !stored) {return void stream.resume()} + const { formId } = stored + const refuse = async (failure: Parameters[2]) => stop(await fileFailure(payload, formId, failure, locale)) + + // 9–10. Field, count and name — before any byte of this file. + const started = gate.begin(name, filename) + if ('failure' in started) { + stream.resume() + return refuse(started.failure) + } + const { slot, token } = started + let chunks: Buffer[] = [] + let size = 0 + let headChecked = false + for await (const chunk of stream as AsyncIterable) { + if (outcome) {continue} // refused: read on and keep nothing + size += chunk.length + // 11. Size, counted while reading. + if (size > slot.maxBytes) { + chunks = [] + await refuse(slot.tooLarge()) + continue + } + chunks.push(chunk) + // 12. Signature, as soon as the first bytes are here. + if (!headChecked && size >= 16) { + headChecked = true + const wrong = slot.checkStart(chunks.length === 1 ? chunk : Buffer.concat(chunks)) + if (wrong) { + chunks = [] + await refuse(wrong) + } + } + } + if (outcome) {return} + if (stream.truncated) {return refuse(slot.tooLarge())} + // 13–14. Whole-file checks and the optional scan. + const failure = await gate.finish(token, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)) + if (failure) {await refuse(failure)} + } + + parser.on('field', (name, value, info) => { + if (info.valueTruncated || info.nameTruncated) {return stop({ reason: 'error', success: false })} + fields[name] = value + }) + parser.on('file', (name, stream, info) => { + chain = chain.then(() => receiveFile(name, stream, info.filename ?? '')).catch((err) => { + stream.resume() + payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`) + stop({ reason: 'error', success: false }) + }) + }) + for (const event of ['fieldsLimit', 'filesLimit', 'partsLimit'] as const) { + parser.on(event, () => stop({ kind: 'unknown_fields', reason: 'validation', success: false })) + } + + const finish = async () => { + try { + await chain + if (!outcome) { + pre ??= beforeFiles() // a request without a file part still runs every gate + await pre + } + if (!outcome && gate && stored) { + const missing = (gate as FileGate).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 }))} + } catch (err) { + payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`) + stop({ reason: 'error', success: false }) + } + resolve(outcome ?? { reason: 'error', success: false }) + } + + let done = false + const once = (run: () => void) => () => { + if (done) {return} + done = true + run() + } + parser.on('close', once(() => void finish())) + const broken = once(() => { + stop({ reason: 'error', success: false }) + void finish() + }) + parser.on('error', broken) + source.on('error', broken) + // Hard ceiling on what is read at all, whatever Content-Length said. + source.on('data', (chunk: Buffer) => { + received += chunk.length + if (received > hardCap) { + stop({ reason: 'error', success: false }) + source.destroy(new Error('request body over the limit')) + } + }) + source.pipe(parser) + }) + } finally { + active-- + if (registered) {inflight.delete(registered)} + settle?.(final) + } + return respond(final) +} diff --git a/src/modules/forms/builderLogic.ts b/src/modules/forms/builderLogic.ts index a0ad315..d62b451 100644 --- a/src/modules/forms/builderLogic.ts +++ b/src/modules/forms/builderLogic.ts @@ -1,5 +1,6 @@ -import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js' +import type { BuilderField, BuilderFileLimits, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js' +import { describeFileTypes, fileExtensions, MB } from './attachments/fileTypes.js' import { NON_INPUT_TYPES } from './builderTypes.js' import { isEmail } from './validators.js' @@ -102,12 +103,61 @@ export function visibleFields(fields: F[] | null | u return list.filter((field) => visible(field)) } -/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */ +/** A selected file as the logic needs it — a browser `File` fits. */ +export type BuilderFile = { name: string; size: number } + +/** + * The limits of a File field in the browser: what the server resolved + * (`field.resolved`), else the field's own values with the built-in types. + */ +export function fileFieldRules(field: BuilderField): Required { + const own = describeFileTypes(field.allowedTypes) + const r = field.resolved ?? {} + const maxSizeMB = r.maxSizeMB ?? field.maxSizeMB ?? 10 + return { + accept: r.accept ?? own.accept, + extensions: r.extensions ?? own.extensions, + maxFiles: r.maxFiles ?? field.maxFiles ?? 1, + maxSizeMB, + maxTotalMB: r.maxTotalMB ?? maxSizeMB, + typeLabels: r.typeLabels ?? own.labels, + } +} + +/** + * The first problem with the files picked for a File field, as the visitor's + * message — the same rules the server enforces (it checks the content too). + */ +export function fileFieldError( + field: BuilderField, + files: readonly BuilderFile[], + 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))} + 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) + } + if (file.size > rules.maxSizeMB * MB || file.size === 0) { + return (texts.fileTooLarge ?? generic).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 undefined +} + +/** Starting values: checkbox → boolean, checkboxGroup → string[], file → File[], the rest → string. */ export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record { return Object.fromEntries( inputFields(fields).map((f) => { if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]} if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]} + if (f.blockType === 'file') {return [f.name, []]} const v = f.defaultValue return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : ''] }), @@ -120,7 +170,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)) { @@ -130,7 +180,11 @@ export function validateBuilderFields( if (f.required) {errors[f.name] = msg} continue } - if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg} + if (f.blockType === 'file') { + const problem = Array.isArray(v) ? fileFieldError(f, v as BuilderFile[], texts) : msg + if (problem) {errors[f.name] = problem} + } + else if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg} else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg} else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) { if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg} diff --git a/src/modules/forms/builderTypes.ts b/src/modules/forms/builderTypes.ts index 6629550..7ec7ce4 100644 --- a/src/modules/forms/builderTypes.ts +++ b/src/modules/forms/builderTypes.ts @@ -13,16 +13,42 @@ export type BuilderOption = { label?: null | string; value: string } */ export type FieldCondition = { field?: null | string; values?: null | string } +/** + * What the server resolved for a File field (forms afterRead): the limits that + * really apply and the types as the browser needs them. Absent when the form + * was not read through Payload — the hook falls back to the field's own values. + */ +export type BuilderFileLimits = { + /** For ``. */ + accept?: string + /** Lowercase, without the dot. */ + extensions?: string[] + maxFiles?: number + maxSizeMB?: number + /** All files of one submission together. */ + maxTotalMB?: number + /** "PDF, DOC, DOCX" */ + typeLabels?: string +} + export type BuilderField = { + /** file — type keys ticked in the panel */ + allowedTypes?: null | string[] blockName?: null | string - /** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */ + /** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · file · country · state · message · step · a project's own type */ blockType: string defaultValue?: unknown /** step */ description?: null | string + /** file — text under the field */ + help?: null | string id?: null | string label?: null | string + /** file */ + maxFiles?: null | number maxSelected?: null | number + /** file */ + maxSizeMB?: null | number /** message — rich text, rendered on the server (RenderForm) */ message?: unknown minSelected?: null | number @@ -30,6 +56,8 @@ export type BuilderField = { options?: BuilderOption[] | null placeholder?: null | string required?: boolean | null + /** file — see BuilderFileLimits */ + resolved?: BuilderFileLimits | null /** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */ showWhen?: FieldCondition | null /** step */ @@ -42,6 +70,8 @@ export type BuilderFormDoc = { confirmationMessage?: unknown confirmationType?: 'message' | 'redirect' | null fields?: BuilderField[] | null + /** Where a submission with files is posted (set by the server for forms with a File field). */ + fileSubmitUrl?: null | string id: number | string redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null submitButtonLabel?: null | string @@ -52,6 +82,11 @@ export type BuilderFormDoc = { export type BuilderFormTexts = { back?: string error?: string + /** File field — see FormNotificationTexts. */ + fileCount?: string + fileRemove?: string + fileTooLarge?: string + fileType?: string next?: string /** "Step {current} of {total}" */ stepOf?: string diff --git a/src/modules/forms/createSubmitAction.ts b/src/modules/forms/createSubmitAction.ts index 880ea82..cb8b737 100644 --- a/src/modules/forms/createSubmitAction.ts +++ b/src/modules/forms/createSubmitAction.ts @@ -32,6 +32,31 @@ export type SubmitActionResult = { success: boolean } +type BlobLike = { arrayBuffer: () => Promise; name?: string } +const isBlob = (v: unknown): v is BlobLike => typeof v === 'object' && v !== null && typeof (v as BlobLike).arrayBuffer === 'function' + +/** + * Splits `File` values (one or an array, under a File field's key) from the + * answers — for an action or route that receives files itself and hands them to + * `submitForm({ data: fields, files })`. + */ +export async function splitFormFiles(values: Record): Promise<{ + fields: Record + files?: Record +}> { + const fields: Record = {} + const files: Record = {} + for (const [key, value] of Object.entries(values)) { + const list = Array.isArray(value) ? value : [value] + if (list.length > 0 && list.every(isBlob)) { + files[key] = await Promise.all(list.map(async (file) => ({ name: file.name ?? '', data: new Uint8Array(await file.arrayBuffer()) }))) + } else { + fields[key] = value + } + } + return Object.keys(files).length ? { fields, files } : { fields } +} + /** * The one server action every panel form posts to — honeypot → client IP → * submitForm (rate limit, Turnstile, schema validation, GDPR consent, storage) @@ -68,12 +93,16 @@ export function createSubmitAction({ const texts = (await getNotificationTexts({ locale, payload })).form const data = values && typeof values === 'object' ? values : {} if (isHoneypotTripped(data, honeypotField)) {return { message: texts.success, success: true }} - const { [honeypotField]: _honeypot, ...fields } = data + const { [honeypotField]: _honeypot, ...rest } = data + // Files a project sends through the action itself (panel forms post files to + // the streaming endpoint instead): split them from the answers. + const { fields, files } = await splitFormFiles(rest) const ip = clientIp(await headers(), ipOptions) || undefined const result = await submitForm({ consentFieldName, data: fields, + ...(files ? { files } : {}), formId: String(formId), ip, locale, diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 40cb786..1d4c88e 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -7,6 +7,11 @@ import type { AdminText } from '../admin-i18n/define.js' import type { FormsOption } from './types.js' import { userMeetsRole } from '../access/predicates.js' +import { resolveFormAttachments } from './attachments/config.js' +import { buildFileDeliveryHook, buildFileNoticeHook } from './attachments/delivery.js' +import { buildFormSubmitEndpoint } from './attachments/endpoint.js' +import { buildFileBlock } from './attachments/fileBlock.js' +import { buildFormFilesAfterRead, buildFormFilesBeforeValidate, submissionFileFields } from './attachments/formHooks.js' import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js' import { buildEmailLayoutHook } from './emailLayout.js' @@ -206,15 +211,25 @@ function hideEmails(fields: Field[]): Field[] { export function buildFormsPlugin(forms: FormsOption): Plugin { const adminGroup = forms.adminGroup === undefined ? { en: 'Forms', pl: 'Formularze' } : forms.adminGroup const group = adminGroup ? { group: adminGroup } : {} - const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined + const formsSlug = forms.formOverrides?.slug ?? 'forms' + const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug }) : undefined + // Files (forms.attachments): never stored — attached to the company e-mail by + // the two hooks around the layout, and dropped (attachments/delivery). + const attachments = forms.attachments ? resolveFormAttachments(forms.attachments) : null + const fileNotice = attachments ? buildFileNoticeHook({ formsSlug, notice: attachments.notice }) : undefined + const fileDelivery = attachments ? buildFileDeliveryHook({ formsSlug }) : undefined const beforeEmail: BeforeEmail | undefined = - layout || forms.beforeEmail + layout || forms.beforeEmail || attachments ? async (emails, args) => { - const laidOut = layout ? await layout(emails, args) : emails - return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut + 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 + return fileDelivery ? fileDelivery(changed, args) : changed } : undefined - return formBuilderPlugin({ + const fileBlockOption = forms.fields?.file + const formHooks = forms.formOverrides?.hooks + const builder = formBuilderPlugin({ ...(beforeEmail ? { beforeEmail } : {}), // Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are // panel choices only — a form uses what the editor adds, nothing changes on @@ -225,6 +240,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock, date: builtin('date'), email: withHint('email'), + // File (ipal): only with forms.attachments; `false` hides it, a block object replaces it. + ...(attachments && fileBlockOption !== false + ? { file: (typeof fileBlockOption === 'object' ? fileBlockOption : buildFileBlock(attachments)) as never } + : {}), message: builtin('message'), number: withHint('number'), payment: false, @@ -236,7 +255,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { time: forms.fields?.time === false ? false : timeBlock, ...Object.fromEntries( // `true` keeps ipal's block (with "Show only when"); false / an object override it - Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true), + Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'file' && k !== 'step' && k !== 'time' && v !== true), ), }, ...(forms.redirectRelationships @@ -258,6 +277,15 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { ...forms.formOverrides?.access, }, admin: { ...group, ...forms.formOverrides?.admin }, + ...(attachments + ? { + hooks: { + ...formHooks, + afterRead: [...(formHooks?.afterRead ?? []), buildFormFilesAfterRead(attachments)], + beforeValidate: [...(formHooks?.beforeValidate ?? []), buildFormFilesBeforeValidate()], + }, + } + : {}), fields: ({ defaultFields }) => { const protectedFields = hideEmails(localizeFormBuilder(defaultFields)) return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields @@ -272,11 +300,26 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { read: submissionsReadAccess, ...forms.formSubmissionOverrides?.access, }, - admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin }, + admin: { + ...group, + defaultColumns: attachments ? ['form', 'filesDelivery', 'createdAt'] : ['form', 'createdAt'], + ...forms.formSubmissionOverrides?.admin, + }, fields: ({ defaultFields }) => { - const labelled = labelSubmissionFields(defaultFields) + const labelled = [...labelSubmissionFields(defaultFields), ...(attachments ? submissionFileFields : [])] return forms.formSubmissionOverrides?.fields ? forms.formSubmissionOverrides.fields({ defaultFields: labelled }) : labelled }, }, }) + 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 { + ...config, + custom: { ...config.custom, ipal: { ...(config.custom?.ipal as object | undefined), formAttachments: attachments } }, + endpoints: [...(config.endpoints ?? []), buildFormSubmitEndpoint(attachments)], + } + } } diff --git a/src/modules/forms/index.ts b/src/modules/forms/index.ts index 4b85450..f43c17b 100644 --- a/src/modules/forms/index.ts +++ b/src/modules/forms/index.ts @@ -1,8 +1,17 @@ +// Files on panel forms (forms.attachments): checked, e-mailed, never stored. +export { fileFieldLimits, FORM_SUBMIT_PATH, getFormAttachments, resolveFormAttachments } from './attachments/config.js' +export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions, ResolvedFormAttachments } from './attachments/config.js' +export { canCarryFiles, fileNoticeText, fixedRecipients, mayCarryFiles } from './attachments/delivery.js' +export { buildFileBlock, fileBlock } from './attachments/fileBlock.js' +export type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.js' +export { DEFAULT_FORM_FILE_TYPES, describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from './attachments/fileTypes.js' +export type { FormFileDetect, FormFileType } from './attachments/fileTypes.js' // Panel field types: step-by-step forms + multiple choice (enabled by default). export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './builderBlocks.js' // Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm. -export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js' -export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js' +export { fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js' +export type { BuilderFile } from './builderLogic.js' +export type { BuilderField, BuilderFileLimits, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js' export { formAnalyticsOnSuccess } from './formAnalytics.js' export type { FormAnalyticsConfig } from './formAnalytics.js' // Panel-managed form analytics: fields (config-time) + onSuccess helper (client). diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 1f5106e..b5445a7 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -2,12 +2,26 @@ import 'server-only' import type { BasePayload } from 'payload' +import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.js' +import type { FormValidationResult } from './validateSubmission.js' + +import { mailAttachmentLimit } from '../email/attachmentLimit.js' import { getTurnstileConfig } from '../turnstile/config.js' import { verifyTurnstile } from '../turnstile/verify.js' +import { getFormAttachments } from './attachments/config.js' +import { canCarryFiles, FORM_FILES_CONTEXT, type FormFileDelivery } from './attachments/delivery.js' +import { checkBufferedFiles, createFileGate } from './attachments/fileGate.js' +import { formatFileSize } from './attachments/fileTypes.js' import { consumeRateLimit } from './rateLimit.js' import { validateSubmission } from './validateSubmission.js' export type SubmitFormArgs = { + /** + * A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`). + * A second request with the same key returns the first outcome and sends no + * e-mail again. Stored only with `forms.attachments`. + */ + attemptKey?: string /** * Name of the GDPR consent checkbox. A field with this name must be checked * for the submission to succeed (enforced server-side). Defaults to @@ -16,6 +30,11 @@ export type SubmitFormArgs = { consentFieldName?: string /** Submitted field data — shape matches the form's fields. */ data: Record + /** + * Files by File-field key, as whole buffers — for a project's own transfer + * path (needs `forms.attachments`). Checked like any upload and e-mailed, never stored. + */ + files?: Record /** Form-builder form ID this submission belongs to. */ formId: string /** Client IP — used for Turnstile and rate limiting. */ @@ -59,18 +78,35 @@ export type SubmitFormArgs = { * at fault (absent for whole-payload problems like unknown keys) * - `not_found` — no form with this id * - `consent` — a required GDPR consent checkbox was left unchecked + * - `delivery` — the attached file could not be sent by e-mail * - `error` — persistence failed unexpectedly */ 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). */ + file?: string /** What was wrong with it. */ - kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' + kind?: 'file_count' | '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 reason: 'validation' success: false + /** 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 @@ -85,96 +121,237 @@ export type SubmitFailure = export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure -/** - * Handles a form submission end to end: rate limit, verify Turnstile, validate - * against the form's own schema, then store. - * - * The order is cost-ascending on purpose — the cheapest checks reject first, so - * a flood never reaches Turnstile's network call or the database. - * - * Emails aren't sent here. The form-builder sends whatever an editor configured - * under the form's "Emails" tab (form-submissions hook → payload.sendEmail), - * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough. - * - * server-only: touches the Turnstile secret. - */ -export async function submitForm({ - consentFieldName, - data, - formId, +/** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */ +export async function passSubmitGates({ ip, - locale, maxPerMinute = 5, payload, turnstileHostnames, turnstileOnConfigError = 'allow', turnstileToken, -}: SubmitFormArgs): Promise { - // 1. Rate limit — cheapest gate, drops a flood before any real work. - // No IP → the limiter's shared "unknown" bucket, never a free pass. - if (maxPerMinute > 0) { - if (!(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) { - return { reason: 'rate_limited', success: false } - } - } +}: Pick): Promise { + return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken })) +} - // 2. Turnstile — decided by the SERVER's config, never by whether the client - // sent a token: configured → a token is required and verified (a bot can't - // opt out by omitting it); not configured → skipped, the widget isn't shown. +/** 1. Rate limit — cheapest gate, drops a flood before any real work. No IP → the shared "unknown" bucket, never a free pass. */ +export async function passRateLimit({ ip, maxPerMinute = 5 }: Pick): Promise { + if (maxPerMinute > 0 && !(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) { + return { reason: 'rate_limited', success: false } + } + return null +} + +/** + * 2. Turnstile — decided by the SERVER's config, never by whether the client + * sent a token: configured → a token is required and verified (a bot can't opt + * out by omitting it); not configured → skipped, the widget isn't shown. + */ +export async function passTurnstile({ + ip, + payload, + turnstileHostnames, + turnstileOnConfigError = 'allow', + turnstileToken, +}: Pick): Promise { if ((await getTurnstileConfig(payload)).enabled) { const ok = Boolean(turnstileToken) && (await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! })) - if (!ok) { - return { reason: 'turnstile', success: false } - } + if (!ok) {return { reason: 'turnstile', success: false }} } + return null +} - // 3. Validate against the form's schema. A public endpoint can't trust the - // shape of `data` — drop unknown keys, enforce required, cap length. +type ValidSubmission = Extract + +/** + * 3. Validate against the form's schema. A public endpoint can't trust the + * shape of `data` — drop unknown keys, enforce required, cap length, enforce consent. + */ +export async function validateSubmitFields({ + consentFieldName, + data, + formId, + locale, + payload, +}: Pick): Promise<{ failure: SubmitFailure } | { validation: ValidSubmission }> { // Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'. const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined) const validation = await validateSubmission(payload, formId, data, consentField) - if (!validation.ok) { - if (validation.reason === 'not_found') { - return { reason: 'not_found', success: false } - } - if (validation.reason === 'consent') { - return { field: validation.field, reason: 'consent', success: false } - } - const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined - return { + if (validation.ok) {return { validation }} + if (validation.reason === 'not_found') {return { failure: { reason: 'not_found', success: false } }} + if (validation.reason === 'consent') {return { failure: { field: validation.field, reason: 'consent', success: false } }} + const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined + return { + failure: { reason: 'validation', success: false, ...(validation.field ? { field: validation.field } : {}), ...(validation.kind ? { kind: validation.kind } : {}), ...(label ? { label } : {}), - } + }, } +} - // 4. Persist (form-builder shape: submissionData array). Triggers the email - // hook. Only validated, known fields are stored. +/** A refused file as a submit failure, with the field's label for the message. */ +export async function fileFailure(payload: BasePayload, formId: string, failure: FormFileFailure, locale?: string): Promise { + if (failure.kind === 'unknown_fields') {return { kind: 'unknown_fields', reason: 'validation', success: false }} + const label = await fieldLabel(payload, formId, failure.field, locale) + return { + field: failure.field, + kind: failure.kind, + reason: 'validation', + success: false, + ...(failure.file ? { file: failure.file } : {}), + ...(label ? { label } : {}), + ...(failure.max !== undefined ? { max: failure.max } : {}), + ...(failure.types ? { types: failure.types } : {}), + } +} + +const ATTEMPT_KEY = /^[\w-]{16,64}$/ + +/** A usable attempt key, or undefined. */ +export const cleanAttemptKey = (key: unknown): string | undefined => (typeof key === 'string' && ATTEMPT_KEY.test(key) ? key : undefined) + +/** + * The outcome of an earlier request with this attempt key, when one was stored — + * a repeated request (double click, a proxy or browser resend) gets the first + * answer and sends nothing again. Only with `forms.attachments` (the field exists then). + */ +export async function findSubmitAttempt(payload: BasePayload, attemptKey: string | undefined): Promise { + if (!attemptKey || !getFormAttachments(payload)) {return null} + try { + const found = await payload.find({ + collection: 'form-submissions', + depth: 0, + limit: 1, + where: { attemptKey: { equals: attemptKey } }, + } as never) + const doc = found.docs[0] as { filesDelivery?: string; id: number | string } | undefined + if (!doc) {return null} + return doc.filesDelivery === 'failed' ? { reason: 'delivery', submissionId: doc.id, success: false } : { submissionId: doc.id, success: true } + } catch { + return null + } +} + +/** + * 4. Persist (form-builder shape: submissionData array). Triggers the e-mail + * hook. Only validated, known fields are stored. + * + * Files are NOT stored. They ride in the request context to the e-mail hook + * (attachments/delivery), which attaches them to the company e-mail; the + * submission keeps their name, type and size and whether the mail server took them. + */ +export async function storeSubmission({ + attemptKey, + files = [], + formId, + locale, + payload, + validation, +}: { + attemptKey?: string + /** Files that passed the file gate. */ + files?: AcceptedFormFile[] + validation: ValidSubmission +} & Pick): Promise { + const attachments = getFormAttachments(payload) + const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined + 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) + // Rows in the form's field order; a File field's row is "CV.pdf (2.1 MB)". + const rows: { field: string; value: string }[] = [] + for (const field of validation.form.fields ?? []) { + if (typeof field.name !== 'string') {continue} + if (field.name in validation.cleaned) {rows.push({ field: field.name, value: text(validation.cleaned[field.name]) })} + const own = files.filter((f) => f.field === field.name) + if (own.length) {rows.push({ field: field.name, value: own.map((f) => `${f.name} (${formatFileSize(f.size)})`).join(', ') })} + } try { const submission = await payload.create({ collection: 'form-submissions', ...(locale ? { locale: locale as never } : {}), + ...(delivery ? { context: { [FORM_FILES_CONTEXT]: delivery } } : {}), data: { form: formId, - submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({ - field, - // checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails) - value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string), - })), + submissionData: rows, + ...(attachments && attemptKey ? { attemptKey } : {}), + // "Not sent" until the mail server has taken the message — a crash in between must not read as sent. + ...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}), } as never, }) - return { submissionId: submission.id, success: true } + if (!delivery) {return { submissionId: submission.id, success: true }} + + const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const } + try { + await payload.update({ + id: submission.id, + collection: 'form-submissions', + data: { filesDelivery: result.state, filesDeliveryNote: result.note ?? '' } as never, + depth: 0, + }) + } 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 } } catch (err) { payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) return { reason: 'error', success: false } + } finally { + // The buffers are not needed past this point — drop the references now. + if (delivery) {delivery.files = []} } } +/** + * Handles a form submission end to end: rate limit, verify Turnstile, validate + * against the form's own schema, check the files, then store and e-mail. + * + * The order is cost-ascending on purpose — the cheapest checks reject first, so + * a flood never reaches Turnstile's network call or the database. + * + * Emails aren't composed here. The form-builder sends whatever an editor + * configured under the form's "Emails" tab (form-submissions hook → + * payload.sendEmail), over the configured email adapter (mailAdapter). + * + * `files` (whole buffers) is for a project's own transfer path; panel forms + * send files to the streaming endpoint (attachments/endpoint), which runs + * these same stages around the read. + * + * server-only: touches the Turnstile secret. + */ +export async function submitForm(args: SubmitFormArgs): Promise { + const { attemptKey: rawKey, files, formId, locale, payload } = args + const blocked = await passSubmitGates(args) + if (blocked) {return blocked} + + const checked = await validateSubmitFields(args) + if ('failure' in checked) {return checked.failure} + const { validation } = checked + + const attemptKey = cleanAttemptKey(rawKey) + const repeated = await findSubmitAttempt(payload, attemptKey) + if (repeated) {return repeated} + + const hasFiles = Object.values(files ?? {}).some((list) => list.length > 0) + const attachments = getFormAttachments(payload) + if (!attachments || (!hasFiles && validation.fileFields.length === 0)) { + // A file without the feature (or without a File field) is an unknown field. + if (hasFiles) {return { kind: 'unknown_fields', reason: 'validation', success: false }} + return storeSubmission({ attemptKey, formId, locale, payload, validation }) + } + + if (hasFiles && !canCarryFiles(validation.form)) {return { reason: 'delivery', success: false }} + const gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) }) + const refused = await checkBufferedFiles(gate, files ?? {}) + if (refused) {return fileFailure(payload, formId, refused, locale)} + return storeSubmission({ attemptKey, files: gate.accepted, formId, locale, payload, validation }) +} + /** * The label of one form field in the page's language, so a message names the * field the way the visitor sees it ("E-mail address", not "email"). Only read diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index 2689fc7..24c372e 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -1,5 +1,7 @@ import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types' -import type { CollectionConfig, Field } from 'payload' +import type { Block, CollectionConfig, Field } from 'payload' + +import type { FormAttachmentsOption } from './attachments/config.js' /** * Receives the collection's default fields and returns the final list — add, @@ -26,6 +28,13 @@ export type FormsOption = { * formOverrides / formSubmissionOverrides still wins. */ adminGroup?: false | Record | string + /** + * Files on panel forms: adds the "File" field to the form builder. A file is + * checked, attached to the company e-mail and dropped — it is NEVER stored + * (no collection, no bucket, no download route). Default off; `true` = the + * defaults (10 MB, PDF/DOC/DOCX ticked on a new field). See docs/forms.md. + */ + attachments?: boolean | FormAttachmentsOption /** * form-builder `beforeEmail` — change the e-mails before they go out. Runs after * the ipal layout when `emailLayout` is on. @@ -51,6 +60,8 @@ export type FormsOption = { country?: boolean date?: boolean email?: boolean + /** File field (ipal) — exists only with `attachments`. `false` hides it, a block replaces it. */ + file?: Block | boolean message?: boolean number?: boolean payment?: boolean diff --git a/src/modules/forms/useBuilderForm.ts b/src/modules/forms/useBuilderForm.ts index fb2de7d..fc0a088 100644 --- a/src/modules/forms/useBuilderForm.ts +++ b/src/modules/forms/useBuilderForm.ts @@ -8,14 +8,21 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, import { safeHref } from '../links/resolveLinkHref.js' import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js' -import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js' +import { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js' import { formAnalyticsOnSuccess } from './formAnalytics.js' import { useForm } from './useForm.js' export type UseBuilderFormOptions = { /** Bound server action (RenderForm binds createSubmitAction to formId + locale). */ action: BuilderFormAction + /** + * Where a submission WITH files is posted. Default: the form's own + * `fileSubmitUrl` (set by the server), then '/api/ipal/forms/submit'. + */ + fileSubmitUrl?: string form: BuilderFormDoc + /** The page language — sent with a submission that carries files (prepareBuilderForm sets it). */ + locale?: string /** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */ navigate?: (href: string) => void /** After a successful submit — on top of the panel's analytics event. */ @@ -46,7 +53,7 @@ export type UseBuilderFormOptions = { * * */ -export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) { +export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) { const fields = useMemo(() => form.fields ?? [], [form.fields]) // Fields behind a failed "Show only when" are neither shown, validated nor sent. const visibleInputs = useCallback((values: Record) => inputFields(visibleFields(fields, values)), [fields]) @@ -56,10 +63,37 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref // A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure. const serverFieldError = useRef<{ field: string; message: string } | null>(null) + // One key per submit attempt: a repeated request (double click, a resend by the + // browser or a proxy) carries the same key and the server sends nothing twice. + // A new key only once the server has answered. + const attemptKey = useRef('') const submitAction = useCallback( async (values: Record, token?: string) => { - const shown = new Set(visibleInputs(values).map((field) => field.name)) - const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token) + const shownFields = visibleInputs(values) + const shown = new Set(shownFields.map((field) => field.name)) + const fileNames = new Set(shownFields.filter((field) => field.blockType === 'file').map((field) => field.name)) + const answers = Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name) && !fileNames.has(name))) + const files = [...fileNames].flatMap((name) => (Array.isArray(values[name]) ? (values[name] as File[]) : []).map((file) => ({ name, file }))) + + let result: Awaited> + if (files.length > 0) { + // Files never go through the server action: one multipart request to the + // plugin's endpoint — the answers first, the files last — read there as a stream. + attemptKey.current ||= (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`).replace(/[^\w-]/g, '') + const body = new FormData() + body.append('_form', String(form.id)) + if (locale) {body.append('_locale', locale)} + body.append('_attempt', attemptKey.current) + if (token) {body.append('_token', token)} + body.append('_values', JSON.stringify(answers)) + for (const { name, file } of files) {body.append(name, file, file.name)} + const url = fileSubmitUrl ?? form.fileSubmitUrl ?? '/api/ipal/forms/submit' + const response = await fetch(locale ? `${url}?locale=${encodeURIComponent(locale)}` : url, { body, credentials: 'omit', method: 'POST' }) + result = (await response.json()) as Awaited> + attemptKey.current = '' + } else { + result = await action(answers, token) + } if (result.success) {setResultMessage(result.message ?? null)} else if (result.field) { // No message from the server → name the field by its label, as the visitor sees it. @@ -68,7 +102,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref } return result }, - [action, fields, texts.validation, visibleInputs], + [action, fields, fileSubmitUrl, form.fileSubmitUrl, form.id, locale, texts.validation, visibleInputs], ) const validate = useCallback((values: Record) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts]) @@ -242,6 +276,81 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref [f, getFieldProps, textValue], ) + const helpId = useCallback((field: BuilderField) => `${fieldId(field)}-help`, [fieldId]) + + // File fields: the selected files live in the form values (File[]); the native + // inputs are kept in step with them, so removing a file really removes it. + const fileInputs = useRef(new Map()) + const syncFileInput = useCallback((name: string, files: File[]) => { + const input = fileInputs.current.get(name) + if (!input) {return} + try { + const transfer = new DataTransfer() + for (const file of files) {transfer.items.add(file)} + input.files = transfer.files + } catch { + if (files.length === 0) {input.value = ''} + } + }, []) + + /** The files picked for a File field. */ + const getFiles = useCallback( + (field: BuilderField): File[] => { + const value = f.values[field.name ?? ''] + return Array.isArray(value) ? (value as File[]) : [] + }, + [f.values], + ) + + const setFiles = useCallback( + (field: BuilderField, files: File[]) => { + const name = field.name ?? '' + f.setField(name, files) + syncFileInput(name, files) + // Instant feedback: too large, wrong type, too many — the server checks again, and the content too. + const problem = files.length ? fileFieldError(field, files, texts) : undefined + if (problem) {setErrors((prev) => ({ ...prev, [name]: problem }))} + }, + [f, setErrors, syncFileInput, texts], + ) + + /** Props of the `` of a File field. */ + const getFileProps = useCallback( + (field: BuilderField) => { + const name = field.name ?? '' + const rules = fileFieldRules(field) + const base = getFieldProps(field) + return { + ...base, + type: 'file' as const, + accept: rules.accept || undefined, + 'aria-describedby': [field.help ? helpId(field) : undefined, base['aria-describedby']].filter(Boolean).join(' ') || undefined, + multiple: rules.maxFiles > 1, + onChange: (e: ChangeEvent) => { + const picked = Array.from(e.target.files ?? []) + // Several files: each pick adds to the list (the same file twice counts once). + const current = rules.maxFiles > 1 ? getFiles(field) : [] + const known = new Set(current.map((file) => `${file.name}:${file.size}`)) + setFiles(field, [...current, ...picked.filter((file) => !known.has(`${file.name}:${file.size}`))]) + }, + ref: (input: HTMLInputElement | null) => { + if (input) {fileInputs.current.set(name, input)} + else {fileInputs.current.delete(name)} + }, + } + }, + [getFieldProps, getFiles, helpId, setFiles], + ) + + /** Removes one picked file and puts the focus back on the field. */ + const removeFile = useCallback( + (field: BuilderField, index: number) => { + setFiles(field, getFiles(field).filter((_, i) => i !== index)) + fileInputs.current.get(field.name ?? '')?.focus() + }, + [getFiles, setFiles], + ) + /** Props of one option's input in a radio group or checkboxGroup. */ const getOptionProps = useCallback( (field: BuilderField, option: BuilderOption, i: number) => { @@ -279,15 +388,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref fieldId, form, getFieldProps, + getFileProps, + getFiles, getInputProps, getOptionProps, getSelectProps, getTextareaProps, goTo, + helpId, isFirst, isFixed, isLast, next, + removeFile, /** Message the server returned on success (Notifications → success). */ resultMessage, step, diff --git a/src/modules/forms/validateSubmission.ts b/src/modules/forms/validateSubmission.ts index ac2b4dd..126602a 100644 --- a/src/modules/forms/validateSubmission.ts +++ b/src/modules/forms/validateSubmission.ts @@ -6,8 +6,13 @@ import { visibleFields } from './builderLogic.js' /** A form-builder field, trimmed to what validation needs. */ type FormField = { + /** file */ + allowedTypes?: null | string[] blockType?: string label?: string + /** file */ + maxFiles?: null | number + maxSizeMB?: null | number /** checkboxGroup limits. */ maxSelected?: null | number minSelected?: null | number @@ -20,6 +25,8 @@ type FormField = { } type FormDoc = { + /** Emails tab — read by the file delivery (which e-mail may carry a file). */ + emails?: { bcc?: null | string; cc?: null | string; emailTo?: null | string }[] | null fields?: FormField[] id: number | string /** Per-form notification address, when the client added the field. */ @@ -39,7 +46,13 @@ export type FormValidationResult = ok: false reason: 'invalid' } - | { cleaned: Record; form: FormDoc; ok: true } + | { + cleaned: Record + /** File fields the visitor could see — their files are checked separately (attachments/fileGate). */ + fileFields: ({ name: string } & FormField)[] + form: FormDoc + ok: true + } | { field: string; ok: false; reason: 'consent' } | { ok: false; reason: 'not_found' } @@ -186,12 +199,22 @@ export async function validateSubmission( const shown = new Set(visibleFields(form.fields, data)) const cleaned: Record = {} + const fileFields: ({ name: string } & FormField)[] = [] for (const field of fields) { // Hidden by a condition: not required, not stored. The consent gate never hides — // an editor can't switch GDPR consent off with a condition. if (!shown.has(field) && field.name !== consentFieldName) {continue} const value = data[field.name] + // A File field carries no text value: its files arrive separately and are + // checked by the file gate. Anything sent under its key as data is tampering. + if (field.blockType === 'file') { + if (value != null && value !== '' && !(Array.isArray(value) && value.length === 0)) { + return { field: field.name, kind: 'invalid_format', ok: false, reason: 'invalid' } + } + fileFields.push(field) + continue + } const isBlank = value == null || (typeof value === 'string' && value.trim() === '') || @@ -235,5 +258,5 @@ export async function validateSubmission( return { kind: 'unknown_fields', ok: false, reason: 'invalid' } } - return { cleaned, form, ok: true } + return { cleaned, fileFields, form, ok: true } } diff --git a/src/modules/integrations/texts.ts b/src/modules/integrations/texts.ts index 8078c67..0dc8188 100644 --- a/src/modules/integrations/texts.ts +++ b/src/modules/integrations/texts.ts @@ -17,6 +17,7 @@ export function resolveLabel(label: IntegrationLabel | undefined, language: stri /** Status codes whose message has its own text — shown in the editor's language. */ export const STATUS_CODE_TEXTS: Record = { 'bad-response': 'statusTurnstileBadResponse', + 'graph-large-files': 'statusEmailGraphLargeFiles', 'graph-unavailable': 'statusEmailGraphUnavailable', 'internal-error': 'statusTurnstileInternalError', 'invalid-input-secret': 'statusTurnstileInvalidSecret', diff --git a/src/modules/notifications/defaults.ts b/src/modules/notifications/defaults.ts index 2d6c4fa..6fd95cb 100644 --- a/src/modules/notifications/defaults.ts +++ b/src/modules/notifications/defaults.ts @@ -12,6 +12,11 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = { back: 'Back', consent: 'Accept the privacy policy to send the form.', error: 'The form could not be sent. Please try again in a moment.', + fileCount: 'Attach at most {max} files in "{field}".', + fileNotSent: 'We could not send your file. Try again, or send it by e-mail.', + fileRemove: 'Remove {file}', + fileTooLarge: '"{file}" is too large. The limit is {max} MB.', + fileType: '"{file}" is not an accepted file type. Accepted: {types}.', next: 'Next', notFound: 'This form is no longer available.', rateLimited: 'Too many attempts. Please wait a moment and try again.', @@ -29,6 +34,11 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = { back: 'Wstecz', consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.', error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.', + fileCount: 'W polu „{field}” można dodać najwyżej {max} plików.', + fileNotSent: 'Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem.', + fileRemove: 'Usuń {file}', + fileTooLarge: 'Plik „{file}” jest za duży. Limit to {max} MB.', + fileType: 'Plik „{file}” ma niedozwolony typ. Dozwolone: {types}.', next: 'Dalej', notFound: 'Ten formularz nie jest już dostępny.', rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.', diff --git a/src/modules/notifications/getNotificationTexts.ts b/src/modules/notifications/getNotificationTexts.ts index 314fc7e..b39f602 100644 --- a/src/modules/notifications/getNotificationTexts.ts +++ b/src/modules/notifications/getNotificationTexts.ts @@ -32,6 +32,11 @@ export async function getNotificationTexts({ back: f.back || fb.back, consent: f.consent || fb.consent, error: f.error || fb.error, + fileCount: f.fileCount || fb.fileCount, + fileNotSent: f.fileNotSent || fb.fileNotSent, + fileRemove: f.fileRemove || fb.fileRemove, + fileTooLarge: f.fileTooLarge || fb.fileTooLarge, + fileType: f.fileType || fb.fileType, next: f.next || fb.next, notFound: f.notFound || fb.notFound, rateLimited: f.rateLimited || fb.rateLimited, diff --git a/src/modules/notifications/resolveFormMessage.ts b/src/modules/notifications/resolveFormMessage.ts index b29a712..8e99485 100644 --- a/src/modules/notifications/resolveFormMessage.ts +++ b/src/modules/notifications/resolveFormMessage.ts @@ -1,6 +1,15 @@ import type { SubmitFormResult } from '../forms/index.js' import type { FormNotificationTexts } from './types.js' +/** + * The texts resolveFormMessage needs. The File-field texts are optional, so an + * object written before they existed still fits (the field or general text is used). + */ +export type FormMessageTexts = { [K in 'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType']?: string } & Omit< + FormNotificationTexts, + 'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType' +> + /** * Maps a submitForm result to the user-facing message, interpolating {field} * with the field's label (its key when the form has no label) for validation @@ -12,12 +21,14 @@ import type { FormNotificationTexts } from './types.js' * Never surfaces raw backend/exception detail — 'error' maps to a friendly * generic message, not the thrown error's text (which could leak internals). */ -export function resolveFormMessage(result: SubmitFormResult, texts: FormNotificationTexts): string { +export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageTexts): string { if (result.success) {return texts.success} switch (result.reason) { case 'consent': return texts.consent + case 'delivery': + return texts.fileNotSent ?? texts.error case 'not_found': return texts.notFound case 'rate_limited': @@ -27,6 +38,15 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormNotifica 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 + .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 field ? texts.validation.replace('{field}', field) : texts.error } case 'error': diff --git a/src/modules/notifications/types.ts b/src/modules/notifications/types.ts index a440fc0..5d8b846 100644 --- a/src/modules/notifications/types.ts +++ b/src/modules/notifications/types.ts @@ -10,6 +10,16 @@ export type FormNotificationTexts = { /** Shown when a required GDPR consent checkbox was left unchecked. */ consent: string 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. */ + fileNotSent: 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). */ + fileTooLarge: string + /** File field: a file of a type the field does not accept, with {file} and {types}. */ + fileType: string /** Step-by-step forms: "Next" button. */ next: string notFound: string