Files
ipal-kit/src/modules/forms/validateSubmission.ts
T

263 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { BasePayload } from 'payload'
import type { FieldCondition } from './builderTypes.js'
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
/** checkboxGroup limits. */
maxSelected?: null | number
maxSizeMB?: null | number
minSelected?: null | number
name?: string
/** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
/** "Show only when" — hidden fields are neither required nor stored. */
showWhen?: FieldCondition | null
}
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. */
notificationEmail?: string
title?: string
}
/**
* Validation outcome — codes, not user-facing strings. The frontend turns these
* into its own copy (see SubmitFailure in submitForm).
*/
export type FormValidationResult =
| {
/** Offending field, when a single field is at fault. */
field?: string
kind: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
ok: false
reason: 'invalid'
}
| {
cleaned: Record<string, unknown>
/** 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' }
/** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** HH:MM or HH:MM:SS (a time input), 00:00–23:59. */
const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
/**
* Keys injected by the captcha widget itself, not by the form definition.
* Cloudflare Turnstile adds a hidden <input name="cf-turnstile-response"> after
* a successful challenge; reCAPTCHA adds 'g-recaptcha-response'. Since the
* plugin drives Turnstile end-to-end, these are legitimate artifacts — they
* must not count as "unknown fields" and trip the anti-tampering check.
*/
const CAPTCHA_KEYS = new Set(['cf-turnstile-response', 'g-recaptcha-response'])
/** Hard ceiling on a single field's length, independent of the form config. */
const MAX_FIELD_LENGTH = 5000
/**
* ONE address, nothing else. The form-builder can send a confirmation to
* `{{email}}`, so a value like "[email protected], [email protected]" or one with a line break would
* turn the site into a spam relay (and CR/LF into header injection). Commas,
* semicolons, whitespace and angle brackets are rejected outright.
*/
const EMAIL = /^[^\s@,;<>"()[\]\\]+@[^\s"(),;<>@[\\\]][^\s"(),.;<>@[\\\]]*\.[^\s"(),;<>@[\\\]]{2,}$/
const MAX_EMAIL_LENGTH = 254
// Control characters except tab and line breaks (U+0000–U+001F, U+007F), plus
// bidi overrides that can disguise text in the admin panel and e-mails.
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format' | 'required'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
* panel, and normalizes it. Anything not a plain value for that type is
* rejected — a hand-crafted request can't smuggle objects, extra recipients or
* values outside a select's options.
*/
function checkValue(field: FormField, value: unknown): Checked {
if (value === undefined || value === null || value === '') {return { value }}
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'checkboxGroup': {
// string[] of distinct option values, within the panel's min/max.
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {return { error: 'invalid_format' }}
const picked = [...new Set(value as string[])]
const allowed = new Set((field.options ?? []).map((o) => String(o?.value)))
if (picked.some((v) => !allowed.has(v))) {return { error: 'invalid_format' }}
if (picked.length === 0) {return { value: undefined }}
if (field.minSelected && picked.length < field.minSelected) {return { error: 'required' }}
if (field.maxSelected && picked.length > field.maxSelected) {return { error: 'invalid_format' }}
return { value: picked }
}
case 'date': {
if (typeof value !== 'string' || !DATE.test(value.trim()) || Number.isNaN(Date.parse(value.trim()))) {
return { error: 'invalid_format' }
}
return { value: value.trim() }
}
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
return email.length <= MAX_EMAIL_LENGTH && EMAIL.test(email) ? { value: email } : { error: 'invalid_format' }
}
case 'number': {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
return Number.isFinite(n) ? { value: n } : { error: 'invalid_format' }
}
case 'radio':
case 'select': {
if (typeof value !== 'string' && typeof value !== 'number') {return { error: 'invalid_format' }}
const allowed = (field.options ?? []).map((o) => String(o?.value))
// No options configured → nothing to compare against; still a plain value.
return allowed.length === 0 || allowed.includes(String(value)) ? { value } : { error: 'invalid_format' }
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
case 'time':
return typeof value === 'string' && TIME.test(value.trim()) ? { value: value.trim() } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
return typeof value === 'string'
? { value: value.replace(CONTROL, '').replace(/[\r\n]+/g, ' ') }
: { error: 'invalid_format' }
}
}
/**
* Default name for a GDPR consent field. A checkbox with this name is treated
* as a consent gate: it MUST be checked for the submission to go through,
* enforced here server-side regardless of how the field was configured in the
* panel (so an editor can't weaken it by forgetting `required` or, worse,
* pre-ticking it with defaultValue: true — which GDPR forbids). Configurable
* via FormsOption.consentFieldName.
*/
const DEFAULT_CONSENT_FIELD = 'consent'
/**
* Checks submitted data against the form's own definition, rather than trusting
* whatever arrived.
*
* The server action is a public endpoint: a caller can skip the rendered form
* and post arbitrary keys. Without this, unknown fields would be stored,
* required fields could be missing, and an oversized value could sail through.
* So we load the form, keep only keys that are real fields, reject when a
* required one is blank, and cap length.
*
* Returns the loaded form on success so the caller doesn't fetch it twice, and
* a code + offending field on failure so the frontend can point at it.
*/
export async function validateSubmission(
payload: BasePayload,
formId: string,
data: Record<string, unknown>,
consentFieldName: string = DEFAULT_CONSENT_FIELD,
): Promise<FormValidationResult> {
let form: FormDoc
try {
form = (await payload.findByID({
id: formId,
collection: 'forms',
depth: 0,
})) as FormDoc
} catch {
return { ok: false, reason: 'not_found' }
}
const fields = (form.fields ?? []).filter(
(f): f is { name: string } & FormField =>
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
)
const known = new Map(fields.map((f) => [f.name, f]))
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
const shown = new Set(visibleFields(form.fields, data))
const cleaned: Record<string, unknown> = {}
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() === '') ||
value === false ||
(Array.isArray(value) && value.length === 0)
// GDPR consent gate: a field matching the consent name must be truthy
// (checked). Enforced independently of `required`, so it can't be weakened
// in the panel. This is the one field where server-side enforcement is the
// legal guarantee — the frontend can't bypass it, the editor can't misset it.
if (field.name === consentFieldName) {
if (value !== true) {
return { field: field.name, ok: false, reason: 'consent' }
}
} else if (field.required && isBlank) {
return { field: field.name, kind: 'required', ok: false, reason: 'invalid' }
}
if (typeof value === 'string' && value.length > MAX_FIELD_LENGTH) {
return { field: field.name, kind: 'too_long', ok: false, reason: 'invalid' }
}
const checked = field.name === consentFieldName ? { value } : checkValue(field, value)
if (checked.error) {
return { field: field.name, kind: checked.error, ok: false, reason: 'invalid' }
}
// Only carry through keys that belong to the form — unknown keys from a
// hand-crafted request are dropped, not stored.
if (checked.value !== undefined) {
cleaned[field.name] = checked.value
}
}
// Reject outright if the payload carried keys the form doesn't define — a
// sign the request wasn't produced by the rendered form. Captcha keys are
// exempt: the widget injects them into the rendered form, so they're expected,
// not tampering.
const unknownKeys = Object.keys(data).filter((k) => !known.has(k) && !CAPTCHA_KEYS.has(k))
if (unknownKeys.length > 0) {
return { kind: 'unknown_fields', ok: false, reason: 'invalid' }
}
return { cleaned, fileFields, form, ok: true }
}