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
+10 -4
View File
@@ -3,9 +3,15 @@ import type { FormsOption } from './types.js';
/**
* 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 declare function buildFormsPlugin(forms: FormsOption): Plugin;
+53 -16
View File
@@ -1,22 +1,33 @@
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder';
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ const submissionsCreateAccess = ({ req })=>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) {
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 ? {
@@ -25,12 +36,38 @@ import { formBuilderPlugin } from '@payloadcms/plugin-form-builder';
// 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
}
}
});
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/formsPluginConfig.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\nimport { formBuilderPlugin } from '@payloadcms/plugin-form-builder'\n\nimport type { FormsOption } from './types.js'\n\n/**\n * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.\n *\n * Provides the form/form-submissions collections and field types. Email\n * delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel\n * sender (submitForm) does that, so the form-builder's built-in email (which\n * needs a Payload email adapter) is left unused.\n */\nexport function buildFormsPlugin(forms: FormsOption): Plugin {\n return formBuilderPlugin({\n fields: {\n checkbox: true,\n email: true,\n message: true,\n number: true,\n payment: false,\n select: true,\n text: true,\n textarea: true,\n ...forms.fields,\n },\n ...(forms.redirectRelationships ? { redirectRelationships: forms.redirectRelationships } : {}),\n // Client-supplied collection overrides (e.g. a per-form notification\n // address). The plugin provides the hook, not the opinion about which\n // extra fields a form should carry.\n ...(forms.formOverrides ? { formOverrides: forms.formOverrides } : {}),\n ...(forms.formSubmissionOverrides\n ? { formSubmissionOverrides: forms.formSubmissionOverrides }\n : {}),\n })\n}\n"],"names":["formBuilderPlugin","buildFormsPlugin","forms","fields","checkbox","email","message","number","payment","select","text","textarea","redirectRelationships","formOverrides","formSubmissionOverrides"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,kCAAiC;AAInE;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,KAAkB;IACjD,OAAOF,kBAAkB;QACvBG,QAAQ;YACNC,UAAU;YACVC,OAAO;YACPC,SAAS;YACTC,QAAQ;YACRC,SAAS;YACTC,QAAQ;YACRC,MAAM;YACNC,UAAU;YACV,GAAGT,MAAMC,MAAM;QACjB;QACA,GAAID,MAAMU,qBAAqB,GAAG;YAAEA,uBAAuBV,MAAMU,qBAAqB;QAAC,IAAI,CAAC,CAAC;QAC7F,qEAAqE;QACrE,sEAAsE;QACtE,oCAAoC;QACpC,GAAIV,MAAMW,aAAa,GAAG;YAAEA,eAAeX,MAAMW,aAAa;QAAC,IAAI,CAAC,CAAC;QACrE,GAAIX,MAAMY,uBAAuB,GAC7B;YAAEA,yBAAyBZ,MAAMY,uBAAuB;QAAC,IACzD,CAAC,CAAC;IACR;AACF"}
{"version":3,"sources":["../../../src/modules/forms/formsPluginConfig.ts"],"sourcesContent":["import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'\nimport type { Plugin } from 'payload'\nimport type { FormsOption } from './types.js'\n\n/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */\nconst submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)\n\n/**\n * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.\n *\n * Provides the forms / form-submissions collections and field types. E-mails\n * after a submission are the form-builder's own (Forms → Emails), sent through\n * the project's email adapter (mailAdapter()).\n *\n * SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.\n * anyone can POST /api/form-submissions and skip everything submitForm enforces\n * (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL\n * creation is limited to logged-in users; the site submits through submitForm\n * (server action → Local API, which bypasses access by design). A project that\n * really needs public REST submissions can override `formSubmissionOverrides.access.create`.\n */\nexport function buildFormsPlugin(forms: FormsOption): Plugin {\n const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup\n const group = adminGroup ? { group: adminGroup } : {}\n return formBuilderPlugin({\n fields: {\n text: true,\n textarea: true,\n email: true,\n number: true,\n select: true,\n checkbox: true,\n message: true,\n payment: false,\n ...forms.fields,\n },\n ...(forms.redirectRelationships\n ? { redirectRelationships: forms.redirectRelationships }\n : {}),\n // Client-supplied collection overrides (e.g. a per-form notification\n // address). The plugin provides the hook, not the opinion about which\n // extra fields a form should carry.\n // Tidy panel by default: both collections under one sidebar group with plain\n // labels — no per-project overrides needed just to sort the sidebar.\n formOverrides: {\n labels: { singular: 'Form', plural: 'Forms' },\n ...forms.formOverrides,\n admin: { ...group, ...forms.formOverrides?.admin },\n },\n formSubmissionOverrides: {\n labels: { singular: 'Submission', plural: 'Submissions' },\n ...forms.formSubmissionOverrides,\n admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },\n access: {\n create: submissionsCreateAccess,\n ...forms.formSubmissionOverrides?.access,\n },\n },\n })\n}\n"],"names":["formBuilderPlugin","submissionsCreateAccess","req","Boolean","user","buildFormsPlugin","forms","adminGroup","undefined","group","fields","text","textarea","email","number","select","checkbox","message","payment","redirectRelationships","formOverrides","labels","singular","plural","admin","formSubmissionOverrides","defaultColumns","access","create"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,kCAAiC;AAInE,8EAA8E,GAC9E,MAAMC,0BAA0B,CAAC,EAAEC,GAAG,EAA+B,GAAKC,QAAQD,IAAIE,IAAI;AAE1F;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,iBAAiBC,KAAkB;IACjD,MAAMC,aAAaD,MAAMC,UAAU,KAAKC,YAAY,UAAUF,MAAMC,UAAU;IAC9E,MAAME,QAAQF,aAAa;QAAEE,OAAOF;IAAW,IAAI,CAAC;IACpD,OAAOP,kBAAkB;QACvBU,QAAQ;YACNC,MAAM;YACNC,UAAU;YACVC,OAAO;YACPC,QAAQ;YACRC,QAAQ;YACRC,UAAU;YACVC,SAAS;YACTC,SAAS;YACT,GAAGZ,MAAMI,MAAM;QACjB;QACA,GAAIJ,MAAMa,qBAAqB,GAC3B;YAAEA,uBAAuBb,MAAMa,qBAAqB;QAAC,IACrD,CAAC,CAAC;QACN,qEAAqE;QACrE,sEAAsE;QACtE,oCAAoC;QACpC,6EAA6E;QAC7E,qEAAqE;QACrEC,eAAe;YACbC,QAAQ;gBAAEC,UAAU;gBAAQC,QAAQ;YAAQ;YAC5C,GAAGjB,MAAMc,aAAa;YACtBI,OAAO;gBAAE,GAAGf,KAAK;gBAAE,GAAGH,MAAMc,aAAa,EAAEI,KAAK;YAAC;QACnD;QACAC,yBAAyB;YACvBJ,QAAQ;gBAAEC,UAAU;gBAAcC,QAAQ;YAAc;YACxD,GAAGjB,MAAMmB,uBAAuB;YAChCD,OAAO;gBAAE,GAAGf,KAAK;gBAAEiB,gBAAgB;oBAAC;oBAAQ;iBAAY;gBAAE,GAAGpB,MAAMmB,uBAAuB,EAAED,KAAK;YAAC;YAClGG,QAAQ;gBACNC,QAAQ3B;gBACR,GAAGK,MAAMmB,uBAAuB,EAAEE,MAAM;YAC1C;QACF;IACF;AACF"}
+28 -28
View File
@@ -1,15 +1,13 @@
import 'server-only';
import type { BasePayload } from 'payload';
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;
/**
@@ -17,15 +15,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;
};
/**
* Why a submission failed — a code, never a user-facing string.
@@ -45,34 +45,34 @@ 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;
} | {
field?: string;
success: false;
reason: 'not_found';
} | {
success: false;
/** A GDPR consent field existed on the form but wasn't checked. */
reason: 'consent';
success: false;
field?: string;
} | {
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;
export type SubmitFormResult = SubmitFailure | {
success: true;
} | SubmitFailure;
submissionId: string | number;
};
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
* against the form's own schema, then store.
@@ -86,4 +86,4 @@ export type SubmitFormResult = {
*
* server-only: touches the Turnstile secret.
*/
export declare function submitForm({ consentFieldName, data, formId, ip, maxPerMinute, payload, turnstileOnConfigError, turnstileToken, }: SubmitFormArgs): Promise<SubmitFormResult>;
export declare function submitForm({ payload, formId, data, turnstileToken, ip, maxPerMinute, consentFieldName, turnstileOnConfigError, }: SubmitFormArgs): Promise<SubmitFormResult>;
+18 -18
View File
@@ -1,7 +1,7 @@
import 'server-only';
import { verifyTurnstile } from '../turnstile/index.js';
import { checkRateLimit } from './rateLimit.js';
import { validateSubmission } from './validateSubmission.js';
import { checkRateLimit } from './rateLimit.js';
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
* against the form's own schema, then store.
@@ -14,7 +14,7 @@ import { validateSubmission } from './validateSubmission.js';
* 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, maxPerMinute = 5, payload, turnstileOnConfigError = 'allow', turnstileToken }) {
*/ export async function submitForm({ payload, formId, data, turnstileToken, ip, maxPerMinute = 5, consentFieldName, turnstileOnConfigError = 'allow' }) {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
if (!checkRateLimit({
@@ -22,23 +22,23 @@ import { validateSubmission } from './validateSubmission.js';
max: maxPerMinute
})) {
return {
reason: 'rate_limited',
success: false
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,
token: turnstileToken,
payload,
token: turnstileToken
ip,
onConfigError: turnstileOnConfigError
});
if (!ok) {
return {
reason: 'turnstile',
success: false
success: false,
reason: 'turnstile'
};
}
}
@@ -48,20 +48,20 @@ import { validateSubmission } from './validateSubmission.js';
if (!validation.ok) {
if (validation.reason === 'not_found') {
return {
reason: 'not_found',
success: false
success: false,
reason: 'not_found'
};
}
if (validation.reason === 'consent') {
return {
field: validation.field,
success: false,
reason: 'consent',
success: false
field: validation.field
};
}
return {
reason: 'validation',
success: false,
reason: 'validation',
...validation.field ? {
field: validation.field
} : {},
@@ -84,14 +84,14 @@ import { validateSubmission } from './validateSubmission.js';
}
});
return {
submissionId: submission.id,
success: true
success: true,
submissionId: submission.id
};
} catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${err.message}`);
return {
reason: 'error',
success: false
success: false,
reason: 'error'
};
}
}
File diff suppressed because one or more lines are too long
+19 -13
View File
@@ -18,23 +18,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
@@ -50,6 +52,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;
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/types.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\n/**\n * Receives the collection's default fields and returns the final list — add,\n * remove, or reorder. Same shape the form-builder uses.\n */\nexport type FormsFieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\n/**\n * Overrides for a forms-related collection: replace the fields and/or any\n * other collection setting (admin, access, hooks…).\n */\nexport type FormsCollectionOverrides = {\n fields?: FormsFieldsOverride\n} & Partial<Omit<CollectionConfig, 'fields'>>\n\n/**\n * Forms configuration — mirrors the fields a client enables in the\n * form-builder plugin. Kept minimal; the plugin passes these through.\n */\nexport type FormsOption = {\n /**\n * Name of the checkbox field treated as a GDPR consent gate. A form field\n * with this name must be checked for submission to succeed — enforced\n * server-side in submitForm. Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Field types available in the form builder. Sensible defaults applied. */\n fields?: {\n checkbox?: boolean\n email?: boolean\n message?: boolean\n number?: boolean\n payment?: boolean\n select?: boolean\n text?: boolean\n textarea?: boolean\n }\n /**\n * Override the forms collection. The plugin stays opinion-free about what a\n * form needs beyond its fields — a client that wants, say, a per-form\n * notification address adds it here:\n *\n * formOverrides: {\n * fields: ({ defaultFields }) => [\n * ...defaultFields,\n * { name: 'notificationEmail', type: 'email' },\n * ],\n * }\n */\n formOverrides?: FormsCollectionOverrides\n /** Override the form-submissions collection (same shape). */\n formSubmissionOverrides?: FormsCollectionOverrides\n /** Collections a form can redirect to (e.g. ['pages']). */\n redirectRelationships?: string[]\n}\n"],"names":[],"mappings":"AAgBA;;;CAGC,GACD,WAmCC"}
{"version":3,"sources":["../../../src/modules/forms/types.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\n/**\n * Receives the collection's default fields and returns the final list — add,\n * remove, or reorder. Same shape the form-builder uses.\n */\nexport type FormsFieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\n/**\n * Overrides for a forms-related collection: replace the fields and/or any\n * other collection setting (admin, access, hooks…).\n */\nexport type FormsCollectionOverrides = {\n fields?: FormsFieldsOverride\n} & Partial<Omit<CollectionConfig, 'fields'>>\n\n/**\n * Forms configuration — mirrors the fields a client enables in the\n * form-builder plugin. Kept minimal; the plugin passes these through.\n */\nexport type FormsOption = {\n /** Field types available in the form builder. Sensible defaults applied. */\n fields?: {\n text?: boolean\n textarea?: boolean\n email?: boolean\n number?: boolean\n select?: boolean\n checkbox?: boolean\n message?: boolean\n payment?: boolean\n }\n /** Collections a form can redirect to (e.g. ['pages']). */\n redirectRelationships?: string[]\n /**\n * Name of the checkbox field treated as a GDPR consent gate. A form field\n * with this name must be checked for submission to succeed — enforced\n * server-side in submitForm. Defaults to 'consent'.\n */\n consentFieldName?: string\n /**\n * Override the forms collection. The plugin stays opinion-free about what a\n * form needs beyond its fields — a client that wants, say, a per-form\n * notification address adds it here:\n *\n * formOverrides: {\n * fields: ({ defaultFields }) => [\n * ...defaultFields,\n * { name: 'notificationEmail', type: 'email' },\n * ],\n * }\n */\n formOverrides?: FormsCollectionOverrides\n /** Override the form-submissions collection (same shape). */\n formSubmissionOverrides?: FormsCollectionOverrides\n /**\n * Admin sidebar group for Forms + Form Submissions. Default 'Forms'.\n * `false` = Payload default (\"Collections\"). An explicit `admin.group` in\n * formOverrides / formSubmissionOverrides still wins.\n */\n adminGroup?: string | false\n}\n"],"names":[],"mappings":"AAgBA;;;CAGC,GACD,WAyCC"}