Fix turnstile

This commit is contained in:
2026-10-15 15:53:32 +02:00
parent 7dc93ac5ed
commit 70b676660d
80 changed files with 1136 additions and 902 deletions
+41 -18
View File
@@ -1,37 +1,60 @@
import type { Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { Plugin } from 'payload'
import type { FormsOption } from './types.js'
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)
/**
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
*
* Provides the form/form-submissions collections and field types. Email
* delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel
* sender (submitForm) does that, so the form-builder's built-in email (which
* needs a Payload email adapter) is left unused.
* Provides the forms / form-submissions collections and field types. E-mails
* after a submission are the form-builder's own (Forms → Emails), sent through
* the project's email adapter (mailAdapter()).
*
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
* anyone can POST /api/form-submissions and skip everything submitForm enforces
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
* creation is limited to logged-in users; the site submits through submitForm
* (server action → Local API, which bypasses access by design). A project that
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({
fields: {
checkbox: true,
email: true,
message: true,
number: true,
payment: false,
select: true,
text: true,
textarea: true,
email: true,
number: true,
select: true,
checkbox: true,
message: true,
payment: false,
...forms.fields,
},
...(forms.redirectRelationships ? { redirectRelationships: forms.redirectRelationships } : {}),
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
: {}),
// Client-supplied collection overrides (e.g. a per-form notification
// address). The plugin provides the hook, not the opinion about which
// extra fields a form should carry.
...(forms.formOverrides ? { formOverrides: forms.formOverrides } : {}),
...(forms.formSubmissionOverrides
? { formSubmissionOverrides: forms.formSubmissionOverrides }
: {}),
// Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar.
formOverrides: {
labels: { singular: 'Form', plural: 'Forms' },
...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin },
},
formSubmissionOverrides: {
labels: { singular: 'Submission', plural: 'Submissions' },
...forms.formSubmissionOverrides,
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
access: {
create: submissionsCreateAccess,
...forms.formSubmissionOverrides?.access,
},
},
})
}
+32 -34
View File
@@ -1,21 +1,17 @@
import 'server-only'
import type { BasePayload } from 'payload'
import { verifyTurnstile } from '../turnstile/index.js'
import { checkRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
import { checkRateLimit } from './rateLimit.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 'consent'.
*/
consentFieldName?: string
/** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown>
payload: BasePayload
/** Form-builder form ID this submission belongs to. */
formId: string
/** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown>
/** Turnstile token; when present it is verified, when absent it is skipped. */
turnstileToken?: string
/** Client IP — used for Turnstile and rate limiting. */
ip?: string
/**
@@ -23,15 +19,17 @@ export type SubmitFormArgs = {
* Set to 0 to disable (e.g. when a real limiter sits in front).
*/
maxPerMinute?: number
payload: BasePayload
/**
* Name of the GDPR consent checkbox. A field with this name must be checked
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
*/
consentFieldName?: 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; when present it is verified, when absent it is skipped. */
turnstileToken?: string
}
/**
@@ -52,26 +50,26 @@ export type SubmitFormArgs = {
* - `error` — persistence failed unexpectedly
*/
export type SubmitFailure =
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| {
success: false
reason: 'validation'
/** The offending field's name, when one field is at fault. */
field?: string
/** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields'
reason: 'validation'
success: false
}
| { success: false; reason: 'not_found' }
| {
field?: string
success: false
/** A GDPR consent field existed on the form but wasn't checked. */
reason: 'consent'
success: false
field?: string
}
| { reason: 'error'; success: false }
| { reason: 'not_found'; success: false }
| { reason: 'rate_limited'; success: false }
| { reason: 'turnstile'; success: false }
| { success: false; reason: 'error' }
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
export type SubmitFormResult = SubmitFailure | { success: true; submissionId: string | number }
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
@@ -87,27 +85,27 @@ export type SubmitFormResult = { submissionId: number | string; success: true }
* server-only: touches the Turnstile secret.
*/
export async function submitForm({
consentFieldName,
data,
payload,
formId,
data,
turnstileToken,
ip,
maxPerMinute = 5,
payload,
consentFieldName,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
if (!checkRateLimit({ key: ip, max: maxPerMinute })) {
return { reason: 'rate_limited', success: false }
return { success: false, reason: 'rate_limited' }
}
}
// 2. Turnstile — verify when a token is supplied; reject on failure.
if (turnstileToken !== undefined) {
const ok = await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken })
const ok = await verifyTurnstile({ token: turnstileToken, payload, ip, onConfigError: turnstileOnConfigError })
if (!ok) {
return { reason: 'turnstile', success: false }
return { success: false, reason: 'turnstile' }
}
}
@@ -116,14 +114,14 @@ export async function submitForm({
const validation = await validateSubmission(payload, formId, data, consentFieldName)
if (!validation.ok) {
if (validation.reason === 'not_found') {
return { reason: 'not_found', success: false }
return { success: false, reason: 'not_found' }
}
if (validation.reason === 'consent') {
return { field: validation.field, reason: 'consent', success: false }
return { success: false, reason: 'consent', field: validation.field }
}
return {
reason: 'validation',
success: false,
reason: 'validation',
...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}),
}
@@ -142,9 +140,9 @@ export async function submitForm({
})),
} as never,
})
return { submissionId: submission.id, success: true }
return { success: true, submissionId: submission.id }
} catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { reason: 'error', success: false }
return { success: false, reason: 'error' }
}
}
+19 -13
View File
@@ -19,23 +19,25 @@ export type FormsCollectionOverrides = {
* form-builder plugin. Kept minimal; the plugin passes these through.
*/
export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
text?: boolean
textarea?: boolean
email?: boolean
number?: boolean
select?: boolean
checkbox?: boolean
message?: boolean
payment?: boolean
}
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Name of the checkbox field treated as a GDPR consent gate. A form field
* with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'.
*/
consentFieldName?: string
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
select?: boolean
text?: boolean
textarea?: boolean
}
/**
* Override the forms collection. The plugin stays opinion-free about what a
* form needs beyond its fields — a client that wants, say, a per-form
@@ -51,6 +53,10 @@ export type FormsOption = {
formOverrides?: FormsCollectionOverrides
/** Override the form-submissions collection (same shape). */
formSubmissionOverrides?: FormsCollectionOverrides
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
* `false` = Payload default ("Collections"). An explicit `admin.group` in
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: string | false
}