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 * ipalKit({ forms: { consentFieldName } }), then 'consent'. */ 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. */ ip?: string /** Page language — the form-builder reads the form (e-mail texts, labels) in it. */ locale?: string /** * Rate limit: max submissions per IP per minute. Defaults to 5. * Set to 0 to disable (e.g. when a real limiter sits in front). */ maxPerMinute?: number payload: BasePayload /** Hostnames a Turnstile token must come from (see verifyTurnstile `hostnames`). Unset = not checked. */ turnstileHostnames?: string[] /** * Turnstile can't be verified because of OUR side (missing/wrong secret, * Cloudflare unreachable): 'allow' (default) accepts the submission and shows * the problem in the panel; 'reject' refuses it. */ turnstileOnConfigError?: 'allow' | 'reject' /** * Turnstile token. Required whenever Turnstile is configured (both keys — * see getTurnstileConfig): a missing token is then rejected. Ignored when * Turnstile is not configured. */ turnstileToken?: string } /** * Why a submission failed — a code, never a user-facing string. * * The plugin knows what went wrong; it deliberately doesn't decide how to say * it. The frontend maps these to its own copy, in its own language, and renders * whatever component fits — a field error, a toast, a full message. The plugin * has no business choosing the wording or the locale. * * - `rate_limited` — too many submissions from this IP * - `turnstile` — bot check failed * - `validation` — a field is missing/too long, or unknown keys were sent; * `field` and `kind` narrow it down when a specific field is * 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 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". `field` * and `file`: the File field and the file name(s), so the message shows * at the field and names the file; `optional`: the field is not required. */ field?: string file?: string optional?: boolean reason: 'delivery' submissionId?: number | string success: false } | { /** The offending field's name, when one field is at fault. */ field?: string /** The refused file's name (file_too_large, file_type, file_refused). */ file?: string /** What was wrong with it. */ kind?: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' /** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */ label?: string /** The limit behind file_too_large (MB) or file_count (files). */ max?: number /** A file problem on a field that is not required — the form can be sent without the file. */ optional?: boolean reason: 'validation' success: false /** Accepted types, "PDF, DOCX" (file_type). */ types?: string } | { field?: string /** A GDPR consent field existed on the form but wasn't checked. */ reason: 'consent' success: false } | { reason: 'error'; success: false } | { reason: 'not_found'; success: false } | { reason: 'rate_limited'; success: false } | { reason: 'turnstile'; success: false } export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure /** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */ export async function passSubmitGates({ ip, maxPerMinute = 5, payload, turnstileHostnames, turnstileOnConfigError = 'allow', turnstileToken, }: Pick): Promise { return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken })) } /** 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 }} } return null } 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) {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 } : {}), }, } } /** 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.optional ? { optional: true } : {}), ...(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; submissionFiles?: { field?: string; name?: string }[] } | undefined if (!doc) {return null} if (doc.filesDelivery !== 'failed') {return { submissionId: doc.id, success: true }} const kept = doc.submissionFiles ?? [] return { reason: 'delivery', submissionId: doc.id, success: false, ...(kept[0]?.field ? { field: kept[0].field } : {}), ...(kept.length ? { file: kept.map((f) => f.name).join(', ') } : {}), } } catch { return null } } /** * 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 fileNames = files.map((f) => ({ name: f.name, field: f.field })) const text = (value: unknown) => // checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails) value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string) // 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: 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, }) 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}`) } if (result.state === 'sent') {return { submissionId: submission.id, success: true }} // The message belongs at the File field and names the file — never the mail server's own words. const fileField = validation.fileFields.find((f) => f.name === fileNames[0]?.field) return { field: fileNames[0]?.field, file: fileNames.map((f) => f.name).join(', '), reason: 'delivery', submissionId: submission.id, success: false, ...(fileField && !fileField.required ? { optional: true } : {}), } } catch (err) { payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) return { reason: 'error', success: false } } 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 || validation.fileFields.length === 0) { // A file without the feature (or without a File field) is an unknown field. if (hasFiles) { // Never dropped silently: the caller sent files this site (or this form) does not take. payload.logger.warn( attachments ? `[ipal] submitForm: files were sent to form ${formId}, which has no File field — refused.` : '[ipal] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in ipalKit({ forms: { attachments: true } }).', ) return { kind: 'unknown_fields', reason: 'validation', success: false } } return storeSubmission({ attemptKey, formId, locale, payload, validation }) } if (hasFiles && !canCarryFiles(validation.form)) {return { field: Object.keys(files ?? {})[0], 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 * when a submission fails; never throws. */ async function fieldLabel(payload: BasePayload, formId: string, name: string, locale?: string): Promise { try { const form = (await payload.findByID({ id: formId, collection: 'forms', depth: 0, ...(locale ? { locale: locale as never } : {}), })) as { fields?: { label?: unknown; name?: unknown }[] } const label = form.fields?.find((f) => f.name === name)?.label return typeof label === 'string' && label.trim() ? label.trim() : undefined } catch { return undefined } }