import 'server-only' import type { BasePayload } from 'payload' import { getTurnstileConfig } from '../turnstile/config.js' import { verifyTurnstile } from '../turnstile/verify.js' import { consumeRateLimit } from './rateLimit.js' import { validateSubmission } from './validateSubmission.js' export type SubmitFormArgs = { /** * 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 /** 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 * - `error` — persistence failed unexpectedly */ export type SubmitFailure = | { /** The offending field's name, when one field is at fault. */ field?: string /** What was wrong with it. */ kind?: '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 reason: 'validation' success: false } | { 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 /** * 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, 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 } } } // 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. 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 } } } // 3. Validate against the form's schema. A public endpoint can't trust the // shape of `data` — drop unknown keys, enforce required, cap length. // 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 { 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. try { const submission = await payload.create({ collection: 'form-submissions', ...(locale ? { locale: locale as never } : {}), 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), })), } as never, }) return { submissionId: submission.id, success: true } } catch (err) { payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) return { reason: 'error', success: false } } } /** * 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 } }