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
+3 -3
View File
@@ -1,11 +1,11 @@
import type { PayloadEmailAdapter } from 'payload';
import { type GraphAdapterArgs } from './graphAdapter.js';
import { type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js';
import { type GraphAdapterArgs } from './graphAdapter.js';
export type MailAdapterArgs = {
smtp?: PanelSmtpAdapterArgs;
graph?: GraphAdapterArgs;
fallbackFromAddress?: string;
fallbackFromName?: string;
graph?: GraphAdapterArgs;
smtp?: PanelSmtpAdapterArgs;
};
/**
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
+42 -7
View File
@@ -1,6 +1,9 @@
import { getSiteIntegrations } from '../payload/index.js';
import { graphAdapter } from './graphAdapter.js';
import { recordIntegrationStatus } from '../integrations/status.js';
import { panelSmtpAdapter } from './panelSmtpAdapter.js';
import { graphAdapter } from './graphAdapter.js';
const STATUS_FIELD = 'emailStatus';
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */ const describe = (err)=>(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200);
/** True when the agency Graph credentials are present in the environment. */ function graphAvailable() {
return Boolean(process.env.GRAPH_TENANT_ID && process.env.GRAPH_CLIENT_ID && process.env.GRAPH_CLIENT_SECRET && process.env.GRAPH_SENDER);
}
@@ -41,16 +44,48 @@ import { panelSmtpAdapter } from './panelSmtpAdapter.js';
sendEmail: async (message)=>{
const settings = await getSiteIntegrations(payload);
const choice = settings.emailTransport ?? 'smtp';
if (choice === 'graph') {
if (graphAvailable()) {
return graph.sendEmail(message);
}
const previous = settings[STATUS_FIELD];
const useGraph = choice === 'graph' && graphAvailable();
const graphFallback = choice === 'graph' && !useGraph;
if (graphFallback) {
// Panel asked for Graph but the agency creds aren't configured for
// this project. Fall back to SMTP rather than silently dropping mail.
payload.logger.warn('[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.');
return smtp.sendEmail(message);
}
return smtp.sendEmail(message);
const transport = useGraph ? 'Microsoft Graph' : 'SMTP';
const code = useGraph ? 'graph-error' : 'smtp-error';
let result;
try {
result = await (useGraph ? graph : smtp).sendEmail(message);
} catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code,
message: `${transport}: ${describe(err)}`
});
throw err // callers (form-builder, Send test) still see the failure
;
}
// The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission).
const failed = result;
if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`
});
return result;
}
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
await recordIntegrationStatus(payload, STATUS_FIELD, previous, graphFallback ? {
state: 'degraded',
code: 'graph-unavailable',
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.'
} : {
state: 'ok'
});
return result;
}
};
};
File diff suppressed because one or more lines are too long
+12 -10
View File
@@ -32,8 +32,8 @@ import { getSiteIntegrations } from '../payload/index.js';
if (!host || !user || !pass) {
payload.logger.error('[ipal] Email not sent: SMTP is not configured in Site Integrations.');
return {
error: 'SMTP is not configured in Site Integrations.',
sent: false
sent: false,
error: 'SMTP is not configured in Site Integrations.'
};
}
// The panel is the source of truth for the sender; fall back to whatever
@@ -48,13 +48,13 @@ import { getSiteIntegrations } from '../payload/index.js';
const stripCRLF = (v)=>String(v ?? '').replace(/[\r\n]+/g, ' ').trim();
const { default: nodemailer } = await import('nodemailer');
const transporter = nodemailer.createTransport({
auth: {
pass,
user
},
host,
port,
secure: port === 465
secure: port === 465,
auth: {
user,
pass
}
});
try {
const info = await transporter.sendMail({
@@ -65,16 +65,18 @@ import { getSiteIntegrations } from '../payload/index.js';
} : {}
});
return {
messageId: info.messageId,
sent: true
sent: true,
messageId: info.messageId
};
} catch (err) {
// Never surface SMTP internals to the caller — a form submission
// shouldn't fail loudly because the mailbox is misconfigured.
payload.logger.error(`[ipal] Email send failed: ${err.message}`);
// `detail` is for the panel status (mailAdapter), not for end users.
return {
sent: false,
error: 'Failed to send email.',
sent: false
detail: err.message
};
}
}
File diff suppressed because one or more lines are too long
+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"}
+5 -5
View File
@@ -1,16 +1,16 @@
import type { Payload } from 'payload';
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string;
/** Status groups to check: field name → label. */
checks?: Record<string, string>;
/** Injected by Payload into admin server components. */
payload?: Payload;
/** Status groups to check: field name → label. */
checks?: Record<string, string>;
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string;
};
/**
* Dashboard alert (admin.components.beforeDashboard): lists integrations that
* are currently failing, with a link to Site Integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing).
*/
export declare function IntegrationAlerts({ adminRoute, checks, payload }: Props): Promise<import("react/jsx-runtime").JSX.Element | null>;
export declare function IntegrationAlerts({ payload, checks, adminRoute }: Props): Promise<import("react/jsx-runtime").JSX.Element | null>;
export default IntegrationAlerts;
+11 -14
View File
@@ -3,12 +3,11 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
* Dashboard alert (admin.components.beforeDashboard): lists integrations that
* are currently failing, with a link to Site Integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing).
*/ export async function IntegrationAlerts({ adminRoute = '/admin', checks = {
turnstileStatus: 'Turnstile'
}, payload }) {
if (!payload) {
return null;
}
*/ export async function IntegrationAlerts({ payload, checks = {
turnstileStatus: 'Turnstile',
emailStatus: 'Email'
}, adminRoute = '/admin' }) {
if (!payload) return null;
let doc;
try {
doc = await payload.findGlobal({
@@ -22,21 +21,19 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
label,
status: doc?.[field]
})).filter((x)=>x.status?.state === 'degraded');
if (!failing.length) {
return null;
}
if (!failing.length) return null;
return /*#__PURE__*/ _jsxs("div", {
role: "alert",
style: {
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem'
padding: '1rem 1.25rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))'
},
children: [
/*#__PURE__*/ _jsx("strong", {
children: "Integration problem — the site still works, but a safeguard is off."
children: "Integration problem — the site still works, but something needs attention."
}),
/*#__PURE__*/ _jsx("ul", {
style: {
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/integrations/IntegrationAlerts.tsx"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport type { IntegrationStatus } from './status.js'\n\ntype Props = {\n /** Admin route, for the link. Default '/admin'. */\n adminRoute?: string\n /** Status groups to check: field name → label. */\n checks?: Record<string, string>\n /** Injected by Payload into admin server components. */\n payload?: Payload\n}\n\n/**\n * Dashboard alert (admin.components.beforeDashboard): lists integrations that\n * are currently failing, with a link to Site Integrations. Renders nothing when\n * everything is fine — and never throws (DB not ready → nothing).\n */\nexport async function IntegrationAlerts({ adminRoute = '/admin', checks = { turnstileStatus: 'Turnstile' }, payload }: Props) {\n if (!payload) {return null}\n let doc: Record<string, unknown>\n try {\n doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>\n } catch {\n return null\n }\n const failing = Object.entries(checks)\n .map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))\n .filter((x) => x.status?.state === 'degraded')\n if (!failing.length) {return null}\n\n return (\n <div\n role=\"alert\"\n style={{\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n border: '1px solid var(--theme-error-400, #e5484d)',\n borderRadius: 4,\n marginBottom: '1.5rem',\n padding: '1rem 1.25rem',\n }}\n >\n <strong>Integration problem — the site still works, but a safeguard is off.</strong>\n <ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>\n {failing.map(({ label, status }) => (\n <li key={label}>\n <strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}\n </li>\n ))}\n </ul>\n <a href={`${adminRoute.replace(/\\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>\n Open Site Integrations →\n </a>\n </div>\n )\n}\n\nexport default IntegrationAlerts\n"],"names":["IntegrationAlerts","adminRoute","checks","turnstileStatus","payload","doc","findGlobal","slug","depth","failing","Object","entries","map","field","label","status","filter","x","state","length","div","role","style","background","border","borderRadius","marginBottom","padding","strong","ul","margin","paddingLeft","li","message","code","a","href","replace","display","marginTop"],"mappings":";AAaA;;;;CAIC,GACD,OAAO,eAAeA,kBAAkB,EAAEC,aAAa,QAAQ,EAAEC,SAAS;IAAEC,iBAAiB;AAAY,CAAC,EAAEC,OAAO,EAAS;IAC1H,IAAI,CAACA,SAAS;QAAC,OAAO;IAAI;IAC1B,IAAIC;IACJ,IAAI;QACFA,MAAO,MAAMD,QAAQE,UAAU,CAAC;YAAEC,MAAM;YAA8BC,OAAO;QAAE;IACjF,EAAE,OAAM;QACN,OAAO;IACT;IACA,MAAMC,UAAUC,OAAOC,OAAO,CAACT,QAC5BU,GAAG,CAAC,CAAC,CAACC,OAAOC,MAAM,GAAM,CAAA;YAAEA;YAAOC,QAAQV,KAAK,CAACQ,MAAM;QAAkC,CAAA,GACxFG,MAAM,CAAC,CAACC,IAAMA,EAAEF,MAAM,EAAEG,UAAU;IACrC,IAAI,CAACT,QAAQU,MAAM,EAAE;QAAC,OAAO;IAAI;IAEjC,qBACE,MAACC;QACCC,MAAK;QACLC,OAAO;YACLC,YAAY;YACZC,QAAQ;YACRC,cAAc;YACdC,cAAc;YACdC,SAAS;QACX;;0BAEA,KAACC;0BAAO;;0BACR,KAACC;gBAAGP,OAAO;oBAAEQ,QAAQ;oBAAcC,aAAa;gBAAS;0BACtDtB,QAAQG,GAAG,CAAC,CAAC,EAAEE,KAAK,EAAEC,MAAM,EAAE,iBAC7B,MAACiB;;0CACC,MAACJ;;oCAAQd;oCAAM;;;4BAAU;4BAAEC,QAAQkB,WAAWlB,QAAQmB,QAAQ;;uBADvDpB;;0BAKb,KAACqB;gBAAEC,MAAM,GAAGnC,WAAWoC,OAAO,CAAC,OAAO,IAAI,0BAA0B,CAAC;gBAAEf,OAAO;oBAAEgB,SAAS;oBAAgBC,WAAW;gBAAS;0BAAG;;;;AAKtI;AAEA,eAAevC,kBAAiB"}
{"version":3,"sources":["../../../src/modules/integrations/IntegrationAlerts.tsx"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { IntegrationStatus } from './status.js'\n\ntype Props = {\n /** Injected by Payload into admin server components. */\n payload?: Payload\n /** Status groups to check: field name → label. */\n checks?: Record<string, string>\n /** Admin route, for the link. Default '/admin'. */\n adminRoute?: string\n}\n\n/**\n * Dashboard alert (admin.components.beforeDashboard): lists integrations that\n * are currently failing, with a link to Site Integrations. Renders nothing when\n * everything is fine — and never throws (DB not ready → nothing).\n */\nexport async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {\n if (!payload) return null\n let doc: Record<string, unknown>\n try {\n doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>\n } catch {\n return null\n }\n const failing = Object.entries(checks)\n .map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))\n .filter((x) => x.status?.state === 'degraded')\n if (!failing.length) return null\n\n return (\n <div\n role=\"alert\"\n style={{\n marginBottom: '1.5rem',\n padding: '1rem 1.25rem',\n borderRadius: 4,\n border: '1px solid var(--theme-error-400, #e5484d)',\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n }}\n >\n <strong>Integration problem — the site still works, but something needs attention.</strong>\n <ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>\n {failing.map(({ label, status }) => (\n <li key={label}>\n <strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}\n </li>\n ))}\n </ul>\n <a href={`${adminRoute.replace(/\\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>\n Open Site Integrations →\n </a>\n </div>\n )\n}\n\nexport default IntegrationAlerts\n"],"names":["IntegrationAlerts","payload","checks","turnstileStatus","emailStatus","adminRoute","doc","findGlobal","slug","depth","failing","Object","entries","map","field","label","status","filter","x","state","length","div","role","style","marginBottom","padding","borderRadius","border","background","strong","ul","margin","paddingLeft","li","message","code","a","href","replace","display","marginTop"],"mappings":";AAYA;;;;CAIC,GACD,OAAO,eAAeA,kBAAkB,EAAEC,OAAO,EAAEC,SAAS;IAAEC,iBAAiB;IAAaC,aAAa;AAAQ,CAAC,EAAEC,aAAa,QAAQ,EAAS;IAChJ,IAAI,CAACJ,SAAS,OAAO;IACrB,IAAIK;IACJ,IAAI;QACFA,MAAO,MAAML,QAAQM,UAAU,CAAC;YAAEC,MAAM;YAA8BC,OAAO;QAAE;IACjF,EAAE,OAAM;QACN,OAAO;IACT;IACA,MAAMC,UAAUC,OAAOC,OAAO,CAACV,QAC5BW,GAAG,CAAC,CAAC,CAACC,OAAOC,MAAM,GAAM,CAAA;YAAEA;YAAOC,QAAQV,KAAK,CAACQ,MAAM;QAAkC,CAAA,GACxFG,MAAM,CAAC,CAACC,IAAMA,EAAEF,MAAM,EAAEG,UAAU;IACrC,IAAI,CAACT,QAAQU,MAAM,EAAE,OAAO;IAE5B,qBACE,MAACC;QACCC,MAAK;QACLC,OAAO;YACLC,cAAc;YACdC,SAAS;YACTC,cAAc;YACdC,QAAQ;YACRC,YAAY;QACd;;0BAEA,KAACC;0BAAO;;0BACR,KAACC;gBAAGP,OAAO;oBAAEQ,QAAQ;oBAAcC,aAAa;gBAAS;0BACtDtB,QAAQG,GAAG,CAAC,CAAC,EAAEE,KAAK,EAAEC,MAAM,EAAE,iBAC7B,MAACiB;;0CACC,MAACJ;;oCAAQd;oCAAM;;;4BAAU;4BAAEC,QAAQkB,WAAWlB,QAAQmB,QAAQ;;uBADvDpB;;0BAKb,KAACqB;gBAAEC,MAAM,GAAGhC,WAAWiC,OAAO,CAAC,OAAO,IAAI,0BAA0B,CAAC;gBAAEf,OAAO;oBAAEgB,SAAS;oBAAgBC,WAAW;gBAAS;0BAAG;;;;AAKtI;AAEA,eAAexC,kBAAiB"}
+3 -3
View File
@@ -1,13 +1,13 @@
type Props = {
/** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string;
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string;
/** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string;
};
/**
* Status banner on an integration's tab (Site Integrations). Shows nothing until
* the integration has been used once; a red box while it's failing; a short
* green line once it works again.
*/
export declare function IntegrationStatusBanner({ label, statusField }: Props): import("react/jsx-runtime").JSX.Element | null;
export declare function IntegrationStatusBanner({ statusField, label }: Props): import("react/jsx-runtime").JSX.Element | null;
export default IntegrationStatusBanner;
+10 -14
View File
@@ -2,9 +2,7 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useFormFields } from '@payloadcms/ui';
const fmt = (iso)=>{
if (typeof iso !== 'string' || !iso) {
return '';
}
if (typeof iso !== 'string' || !iso) return '';
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString();
};
@@ -12,20 +10,18 @@ const fmt = (iso)=>{
* Status banner on an integration's tab (Site Integrations). Shows nothing until
* the integration has been used once; a red box while it's failing; a short
* green line once it works again.
*/ export function IntegrationStatusBanner({ label, statusField }) {
*/ export function IntegrationStatusBanner({ statusField, label }) {
const state = useFormFields(([f])=>f[`${statusField}.state`]?.value);
const message = useFormFields(([f])=>f[`${statusField}.message`]?.value);
const code = useFormFields(([f])=>f[`${statusField}.code`]?.value);
const since = useFormFields(([f])=>f[`${statusField}.since`]?.value);
const checkedAt = useFormFields(([f])=>f[`${statusField}.checkedAt`]?.value);
if (!state) {
return null;
}
if (!state) return null;
if (state === 'ok') {
return /*#__PURE__*/ _jsxs("div", {
style: {
fontSize: '0.85rem',
marginBottom: '1.5rem',
fontSize: '0.85rem',
opacity: 0.75
},
children: [
@@ -40,11 +36,11 @@ const fmt = (iso)=>{
return /*#__PURE__*/ _jsxs("div", {
role: "alert",
style: {
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '0.9rem 1rem'
padding: '0.9rem 1rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))'
},
children: [
/*#__PURE__*/ _jsxs("strong", {
@@ -61,8 +57,8 @@ const fmt = (iso)=>{
}) : null,
/*#__PURE__*/ _jsxs("div", {
style: {
fontSize: '0.8rem',
marginTop: '0.35rem',
fontSize: '0.8rem',
opacity: 0.75
},
children: [
@@ -73,8 +69,8 @@ const fmt = (iso)=>{
}),
/*#__PURE__*/ _jsx("div", {
style: {
fontSize: '0.8rem',
marginTop: '0.35rem',
fontSize: '0.8rem',
opacity: 0.75
},
children: "Fix the keys below and save — the status is checked again on the next form submission."
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/integrations/IntegrationStatusBanner.tsx"],"sourcesContent":["'use client'\nimport { useFormFields } from '@payloadcms/ui'\n\ntype Props = {\n /** Integration name shown in the banner, e.g. 'Turnstile'. */\n label: string\n /** Name of the hidden status group (buildIntegrationStatusField). */\n statusField: string\n}\n\nconst fmt = (iso: unknown) => {\n if (typeof iso !== 'string' || !iso) {return ''}\n const d = new Date(iso)\n return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()\n}\n\n/**\n * Status banner on an integration's tab (Site Integrations). Shows nothing until\n * the integration has been used once; a red box while it's failing; a short\n * green line once it works again.\n */\nexport function IntegrationStatusBanner({ label, statusField }: Props) {\n const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined\n const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined\n const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined\n const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)\n const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)\n\n if (!state) {return null}\n\n if (state === 'ok') {\n return (\n <div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>\n ✓ {label} working{since ? ` since ${fmt(since)}` : ''}.\n </div>\n )\n }\n\n return (\n <div\n role=\"alert\"\n style={{\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n border: '1px solid var(--theme-error-400, #e5484d)',\n borderRadius: 4,\n marginBottom: '1.5rem',\n padding: '0.9rem 1rem',\n }}\n >\n <strong>{label} is not working — forms are accepted without this check.</strong>\n {message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}\n <div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>\n {code ? `Code: ${code}. ` : ''}\n {since ? `Since ${fmt(since)}. ` : ''}\n {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}\n </div>\n <div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>\n Fix the keys below and save — the status is checked again on the next form submission.\n </div>\n </div>\n )\n}\n\nexport default IntegrationStatusBanner\n"],"names":["useFormFields","fmt","iso","d","Date","Number","isNaN","getTime","toLocaleString","IntegrationStatusBanner","label","statusField","state","f","value","message","code","since","checkedAt","div","style","fontSize","marginBottom","opacity","role","background","border","borderRadius","padding","strong","marginTop"],"mappings":"AAAA;;AACA,SAASA,aAAa,QAAQ,iBAAgB;AAS9C,MAAMC,MAAM,CAACC;IACX,IAAI,OAAOA,QAAQ,YAAY,CAACA,KAAK;QAAC,OAAO;IAAE;IAC/C,MAAMC,IAAI,IAAIC,KAAKF;IACnB,OAAOG,OAAOC,KAAK,CAACH,EAAEI,OAAO,MAAM,KAAKJ,EAAEK,cAAc;AAC1D;AAEA;;;;CAIC,GACD,OAAO,SAASC,wBAAwB,EAAEC,KAAK,EAAEC,WAAW,EAAS;IACnE,MAAMC,QAAQZ,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGF,YAAY,MAAM,CAAC,CAAC,EAAEG;IAChE,MAAMC,UAAUf,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGF,YAAY,QAAQ,CAAC,CAAC,EAAEG;IACpE,MAAME,OAAOhB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGF,YAAY,KAAK,CAAC,CAAC,EAAEG;IAC9D,MAAMG,QAAQjB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGF,YAAY,MAAM,CAAC,CAAC,EAAEG;IAChE,MAAMI,YAAYlB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGF,YAAY,UAAU,CAAC,CAAC,EAAEG;IAExE,IAAI,CAACF,OAAO;QAAC,OAAO;IAAI;IAExB,IAAIA,UAAU,MAAM;QAClB,qBACE,MAACO;YAAIC,OAAO;gBAAEC,UAAU;gBAAWC,cAAc;gBAAUC,SAAS;YAAK;;gBAAG;gBACvEb;gBAAM;gBAASO,QAAQ,CAAC,OAAO,EAAEhB,IAAIgB,QAAQ,GAAG;gBAAG;;;IAG5D;IAEA,qBACE,MAACE;QACCK,MAAK;QACLJ,OAAO;YACLK,YAAY;YACZC,QAAQ;YACRC,cAAc;YACdL,cAAc;YACdM,SAAS;QACX;;0BAEA,MAACC;;oBAAQnB;oBAAM;;;YACdK,wBAAU,KAACI;gBAAIC,OAAO;oBAAEU,WAAW;gBAAU;0BAAIf;iBAAiB;0BACnE,MAACI;gBAAIC,OAAO;oBAAEC,UAAU;oBAAUS,WAAW;oBAAWP,SAAS;gBAAK;;oBACnEP,OAAO,CAAC,MAAM,EAAEA,KAAK,EAAE,CAAC,GAAG;oBAC3BC,QAAQ,CAAC,MAAM,EAAEhB,IAAIgB,OAAO,EAAE,CAAC,GAAG;oBAClCC,YAAY,CAAC,UAAU,EAAEjB,IAAIiB,WAAW,CAAC,CAAC,GAAG;;;0BAEhD,KAACC;gBAAIC,OAAO;oBAAEC,UAAU;oBAAUS,WAAW;oBAAWP,SAAS;gBAAK;0BAAG;;;;AAK/E;AAEA,eAAed,wBAAuB"}
{"version":3,"sources":["../../../src/modules/integrations/IntegrationStatusBanner.tsx"],"sourcesContent":["'use client'\nimport { useFormFields } from '@payloadcms/ui'\n\ntype Props = {\n /** Name of the hidden status group (buildIntegrationStatusField). */\n statusField: string\n /** Integration name shown in the banner, e.g. 'Turnstile'. */\n label: string\n}\n\nconst fmt = (iso: unknown) => {\n if (typeof iso !== 'string' || !iso) return ''\n const d = new Date(iso)\n return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()\n}\n\n/**\n * Status banner on an integration's tab (Site Integrations). Shows nothing until\n * the integration has been used once; a red box while it's failing; a short\n * green line once it works again.\n */\nexport function IntegrationStatusBanner({ statusField, label }: Props) {\n const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined\n const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined\n const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined\n const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)\n const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)\n\n if (!state) return null\n\n if (state === 'ok') {\n return (\n <div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>\n ✓ {label} working{since ? ` since ${fmt(since)}` : ''}.\n </div>\n )\n }\n\n return (\n <div\n role=\"alert\"\n style={{\n marginBottom: '1.5rem',\n padding: '0.9rem 1rem',\n borderRadius: 4,\n border: '1px solid var(--theme-error-400, #e5484d)',\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n }}\n >\n <strong>{label} is not working — forms are accepted without this check.</strong>\n {message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}\n <div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>\n {code ? `Code: ${code}. ` : ''}\n {since ? `Since ${fmt(since)}. ` : ''}\n {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}\n </div>\n <div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>\n Fix the keys below and save — the status is checked again on the next form submission.\n </div>\n </div>\n )\n}\n\nexport default IntegrationStatusBanner\n"],"names":["useFormFields","fmt","iso","d","Date","Number","isNaN","getTime","toLocaleString","IntegrationStatusBanner","statusField","label","state","f","value","message","code","since","checkedAt","div","style","marginBottom","fontSize","opacity","role","padding","borderRadius","border","background","strong","marginTop"],"mappings":"AAAA;;AACA,SAASA,aAAa,QAAQ,iBAAgB;AAS9C,MAAMC,MAAM,CAACC;IACX,IAAI,OAAOA,QAAQ,YAAY,CAACA,KAAK,OAAO;IAC5C,MAAMC,IAAI,IAAIC,KAAKF;IACnB,OAAOG,OAAOC,KAAK,CAACH,EAAEI,OAAO,MAAM,KAAKJ,EAAEK,cAAc;AAC1D;AAEA;;;;CAIC,GACD,OAAO,SAASC,wBAAwB,EAAEC,WAAW,EAAEC,KAAK,EAAS;IACnE,MAAMC,QAAQZ,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,MAAM,CAAC,CAAC,EAAEI;IAChE,MAAMC,UAAUf,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,QAAQ,CAAC,CAAC,EAAEI;IACpE,MAAME,OAAOhB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,KAAK,CAAC,CAAC,EAAEI;IAC9D,MAAMG,QAAQjB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,MAAM,CAAC,CAAC,EAAEI;IAChE,MAAMI,YAAYlB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,UAAU,CAAC,CAAC,EAAEI;IAExE,IAAI,CAACF,OAAO,OAAO;IAEnB,IAAIA,UAAU,MAAM;QAClB,qBACE,MAACO;YAAIC,OAAO;gBAAEC,cAAc;gBAAUC,UAAU;gBAAWC,SAAS;YAAK;;gBAAG;gBACvEZ;gBAAM;gBAASM,QAAQ,CAAC,OAAO,EAAEhB,IAAIgB,QAAQ,GAAG;gBAAG;;;IAG5D;IAEA,qBACE,MAACE;QACCK,MAAK;QACLJ,OAAO;YACLC,cAAc;YACdI,SAAS;YACTC,cAAc;YACdC,QAAQ;YACRC,YAAY;QACd;;0BAEA,MAACC;;oBAAQlB;oBAAM;;;YACdI,wBAAU,KAACI;gBAAIC,OAAO;oBAAEU,WAAW;gBAAU;0BAAIf;iBAAiB;0BACnE,MAACI;gBAAIC,OAAO;oBAAEU,WAAW;oBAAWR,UAAU;oBAAUC,SAAS;gBAAK;;oBACnEP,OAAO,CAAC,MAAM,EAAEA,KAAK,EAAE,CAAC,GAAG;oBAC3BC,QAAQ,CAAC,MAAM,EAAEhB,IAAIgB,OAAO,EAAE,CAAC,GAAG;oBAClCC,YAAY,CAAC,UAAU,EAAEjB,IAAIiB,WAAW,CAAC,CAAC,GAAG;;;0BAEhD,KAACC;gBAAIC,OAAO;oBAAEU,WAAW;oBAAWR,UAAU;oBAAUC,SAAS;gBAAK;0BAAG;;;;AAK/E;AAEA,eAAed,wBAAuB"}
+2 -2
View File
@@ -1,2 +1,2 @@
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus, } from './status.js';
export type { IntegrationState, IntegrationStatus } from './status.js';
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner, } from './status.js';
export type { IntegrationStatus, IntegrationState } from './status.js';
+1 -1
View File
@@ -1,3 +1,3 @@
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './status.js';
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './status.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/integrations/index.ts"],"sourcesContent":["export {\n buildIntegrationStatusBanner,\n buildIntegrationStatusField,\n recordIntegrationStatus,\n} from './status.js'\nexport type { IntegrationState, IntegrationStatus } from './status.js'\n"],"names":["buildIntegrationStatusBanner","buildIntegrationStatusField","recordIntegrationStatus"],"mappings":"AAAA,SACEA,4BAA4B,EAC5BC,2BAA2B,EAC3BC,uBAAuB,QAClB,cAAa"}
{"version":3,"sources":["../../../src/modules/integrations/index.ts"],"sourcesContent":["export {\n recordIntegrationStatus,\n buildIntegrationStatusField,\n buildIntegrationStatusBanner,\n} from './status.js'\nexport type { IntegrationStatus, IntegrationState } from './status.js'\n"],"names":["recordIntegrationStatus","buildIntegrationStatusField","buildIntegrationStatusBanner"],"mappings":"AAAA,SACEA,uBAAuB,EACvBC,2BAA2B,EAC3BC,4BAA4B,QACvB,cAAa"}
+10 -10
View File
@@ -10,17 +10,17 @@ import type { BasePayload, Field } from 'payload';
* at most every REFRESH_MS while an error persists, so a broken integration on a
* busy form doesn't turn every submission into a DB write.
*/
export type IntegrationState = 'degraded' | 'ok';
export type IntegrationState = 'ok' | 'degraded';
export type IntegrationStatus = {
/** Last time the integration was used (refreshed at most every REFRESH_MS). */
checkedAt?: null | string;
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: null | string;
/** Human explanation shown in the panel (English — panel language). */
message?: null | string;
/** When the current state started. */
since?: null | string;
state?: IntegrationState | null;
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: string | null;
/** Human explanation shown in the panel (English — panel language). */
message?: string | null;
/** When the current state started. */
since?: string | null;
/** Last time the integration was used (refreshed at most every REFRESH_MS). */
checkedAt?: string | null;
};
/** Hidden group field holding the status — add next to the integration's fields. */
export declare function buildIntegrationStatusField(name: string): Field;
@@ -31,7 +31,7 @@ export declare function buildIntegrationStatusBanner(statusField: string, label:
* request that triggered it.
*/
export declare function recordIntegrationStatus(payload: BasePayload, field: string, previous: IntegrationStatus | null | undefined, next: {
state: IntegrationState;
code?: string;
message?: string;
state: IntegrationState;
}): Promise<void>;
+12 -16
View File
@@ -42,11 +42,11 @@ const SITE_INTEGRATIONS = 'site-integrations';
admin: {
components: {
Field: {
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
clientProps: {
label,
statusField
},
path: '@intecion/ipal-kit/client#IntegrationStatusBanner'
statusField,
label
}
}
}
}
@@ -60,29 +60,25 @@ const SITE_INTEGRATIONS = 'site-integrations';
const changed = previous?.state !== next.state || next.state === 'degraded' && previous?.code !== next.code;
const stale = next.state === 'degraded' && (!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS);
// Healthy and already recorded as healthy (or never recorded) → nothing to do.
if (!changed && !stale) {
return;
}
if (next.state === 'ok' && !previous?.state) {
return;
}
if (!changed && !stale) return;
if (next.state === 'ok' && !previous?.state) return;
const status = {
checkedAt: now.toISOString(),
state: next.state,
code: next.code ?? null,
message: next.message ?? null,
since: changed ? now.toISOString() : previous?.since ?? now.toISOString(),
state: next.state
checkedAt: now.toISOString()
};
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS,
context: {
ipalIntegrationStatus: true
},
data: {
[field]: status
},
depth: 0
depth: 0,
context: {
ipalIntegrationStatus: true
}
});
} catch (err) {
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err);
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -1,3 +1,3 @@
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
export { checkTurnstile, verifyTurnstile } from './verify.js';
export { verifyTurnstile, checkTurnstile } from './verify.js';
export type { TurnstileCheck, TurnstileOutcome } from './verify.js';
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
+2 -2
View File
@@ -1,6 +1,6 @@
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
// Server-only exports. verify.ts imports 'server-only', so this must never be
// imported from a client component — use ./client for the widget instead.
export { checkTurnstile, verifyTurnstile } from './verify.js';
export { verifyTurnstile, checkTurnstile } from './verify.js';
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/turnstile/index.ts"],"sourcesContent":["export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'\n// Server-only exports. verify.ts imports 'server-only', so this must never be\n// imported from a client component — use ./client for the widget instead.\nexport { checkTurnstile, verifyTurnstile } from './verify.js'\nexport type { TurnstileCheck, TurnstileOutcome } from './verify.js'\n"],"names":["TurnstileProvider","useTurnstile","checkTurnstile","verifyTurnstile"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,YAAY,QAAQ,yBAAwB;AACxE,8EAA8E;AAC9E,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,eAAe,QAAQ,cAAa"}
{"version":3,"sources":["../../../src/modules/turnstile/index.ts"],"sourcesContent":["// Server-only exports. verify.ts imports 'server-only', so this must never be\n// imported from a client component — use ./client for the widget instead.\nexport { verifyTurnstile, checkTurnstile } from './verify.js'\nexport type { TurnstileCheck, TurnstileOutcome } from './verify.js'\nexport { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'\n"],"names":["verifyTurnstile","checkTurnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA,8EAA8E;AAC9E,0EAA0E;AAC1E,SAASA,eAAe,EAAEC,cAAc,QAAQ,cAAa;AAE7D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,yBAAwB"}
+13 -13
View File
@@ -1,8 +1,18 @@
import 'server-only';
import type { BasePayload } from 'payload';
type VerifyTurnstileArgs = {
/** Token produced by the client-side widget. */
token: string;
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload;
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
ip?: string;
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean;
/**
* What to do when verification can't run because of OUR side (missing/wrong
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
@@ -10,16 +20,6 @@ type VerifyTurnstileArgs = {
* the panel. 'reject': refuse (fail closed).
*/
onConfigError?: 'allow' | 'reject';
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload;
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean;
/** Token produced by the client-side widget. */
token: string;
};
/**
* - `pass` — token valid.
@@ -28,10 +28,10 @@ type VerifyTurnstileArgs = {
* erroring) → the visitor can't fix it; by default the submission
* is accepted and the panel shows the problem.
*/
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject';
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded';
export type TurnstileCheck = {
code?: string;
outcome: TurnstileOutcome;
code?: string;
};
/**
* Verifies a Turnstile token with Cloudflare and classifies the result (server-only).
@@ -40,7 +40,7 @@ export type TurnstileCheck = {
* Every result is logged when not `pass`, and the integration status on
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export declare function checkTurnstile({ ip, payload, sendRemoteIp, token, }: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck>;
export declare function checkTurnstile({ token, payload, ip, sendRemoteIp, }: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck>;
/**
* Boolean wrapper used by submitForm. `onConfigError` decides what a `degraded`
* result means: 'allow' (default) keeps the site's forms working while the
+24 -36
View File
@@ -1,17 +1,17 @@
import 'server-only';
import { recordIntegrationStatus } from '../integrations/status.js';
import { getSiteIntegrations } from '../payload/index.js';
import { recordIntegrationStatus } from '../integrations/status.js';
/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */ const ENV_SECRET = 'TURNSTILE_SECRET_KEY';
const STATUS_FIELD = 'turnstileStatus';
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */ const CONFIG_ERRORS = {
'internal-error': 'Cloudflare reported an internal error while verifying.',
'missing-input-secret': 'The secret key is missing in the request.',
'invalid-input-secret': 'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
'missing-input-secret': 'The secret key is missing in the request.'
'internal-error': 'Cloudflare reported an internal error while verifying.'
};
const PLUGIN_ERRORS = {
'bad-response': 'Cloudflare returned an unexpected response.',
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).'
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
'bad-response': 'Cloudflare returned an unexpected response.'
};
/**
* Verifies a Turnstile token with Cloudflare and classifies the result (server-only).
@@ -19,13 +19,11 @@ const PLUGIN_ERRORS = {
* Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY.
* Every result is logged when not `pass`, and the integration status on
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/ export async function checkTurnstile({ ip, payload, sendRemoteIp = false, token }) {
if (!token) {
return {
code: 'missing-input-response',
outcome: 'reject'
};
}
*/ export async function checkTurnstile({ token, payload, ip, sendRemoteIp = false }) {
if (!token) return {
outcome: 'reject',
code: 'missing-input-response'
};
const integrations = await getSiteIntegrations(payload);
const previous = integrations[STATUS_FIELD];
const secret = integrations.turnstileSecretKey?.trim() || process.env[ENV_SECRET]?.trim();
@@ -33,43 +31,35 @@ const PLUGIN_ERRORS = {
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`;
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`);
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code,
message,
state: 'degraded'
message
});
return {
code,
outcome: 'degraded'
outcome: 'degraded',
code
};
};
if (!secret) {
return degraded('missing-secret');
}
if (!secret) return degraded('missing-secret');
const body = new URLSearchParams({
response: token,
secret
secret,
response: token
});
if (sendRemoteIp && ip) {
body.append('remoteip', ip);
}
if (sendRemoteIp && ip) body.append('remoteip', ip);
let data;
try {
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
body,
method: 'POST',
body,
signal: AbortSignal.timeout(8000)
});
if (res.status >= 500) {
return degraded('internal-error');
}
if (res.status >= 500) return degraded('internal-error');
data = await res.json();
} catch (err) {
console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err);
return degraded('network-error');
}
if (typeof data?.success !== 'boolean') {
return degraded('bad-response');
}
if (typeof data?.success !== 'boolean') return degraded('bad-response');
if (data.success) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'ok'
@@ -80,14 +70,12 @@ const PLUGIN_ERRORS = {
}
const codes = data['error-codes'] ?? [];
const configCode = codes.find((c)=>c in CONFIG_ERRORS);
if (configCode) {
return degraded(configCode);
}
if (configCode) return degraded(configCode);
// Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request.
console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`);
return {
code: codes[0] ?? 'unknown',
outcome: 'reject'
outcome: 'reject',
code: codes[0] ?? 'unknown'
};
}
/**
File diff suppressed because one or more lines are too long