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
+58 -14
View File
@@ -1,28 +1,34 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
type TransportIntegrations = {
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'graph' | 'smtp' | null
emailTransport?: 'smtp' | 'graph' | null
emailStatus?: IntegrationStatus | null
}
const STATUS_FIELD = 'emailStatus'
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
const describe = (err: unknown) =>
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
export type MailAdapterArgs = {
smtp?: PanelSmtpAdapterArgs
graph?: GraphAdapterArgs
fallbackFromAddress?: string
fallbackFromName?: string
graph?: GraphAdapterArgs
smtp?: PanelSmtpAdapterArgs
}
/** True when the agency Graph credentials are present in the environment. */
function graphAvailable(): boolean {
return Boolean(
process.env.GRAPH_TENANT_ID &&
process.env.GRAPH_CLIENT_ID &&
process.env.GRAPH_CLIENT_SECRET &&
process.env.GRAPH_SENDER,
process.env.GRAPH_CLIENT_ID &&
process.env.GRAPH_CLIENT_SECRET &&
process.env.GRAPH_SENDER,
)
}
@@ -69,20 +75,58 @@ export const mailAdapter =
sendEmail: async (message: SendEmailOptions) => {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
const useGraph = choice === 'graph' && graphAvailable()
const graphFallback = choice === 'graph' && !useGraph
if (choice === 'graph') {
if (graphAvailable()) {
return graph.sendEmail(message)
}
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: unknown
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 as { sent?: boolean; error?: string; detail?: string } | null
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
},
}
}
+15 -16
View File
@@ -1,15 +1,14 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
/** SMTP fields the adapter reads from SiteIntegrations. */
type SmtpIntegrations = {
smtpFromAddress?: null | string
smtpFromName?: null | string
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpUser?: null | string
smtpHost?: string | null
smtpPort?: number | null
smtpUser?: string | null
smtpPassword?: string | null
smtpFromAddress?: string | null
smtpFromName?: string | null
}
export type PanelSmtpAdapterArgs = {
@@ -59,8 +58,10 @@ export const panelSmtpAdapter =
const pass = smtp.smtpPassword
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 }
payload.logger.error(
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
)
return { sent: false, error: 'SMTP is not configured in Site Integrations.' }
}
// The panel is the source of truth for the sender; fall back to whatever
@@ -77,18 +78,15 @@ export const panelSmtpAdapter =
// normalises CRLF in standard headers, but the form-builder interpolates
// user data into the subject via {{field}} placeholders, so strip any
// newlines from header-bound values before they reach the transport.
const stripCRLF = (v: unknown): string =>
String(v ?? '')
.replace(/[\r\n]+/g, ' ')
.trim()
const stripCRLF = (v: unknown): string => 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, // implicit TLS on 465, STARTTLS otherwise
auth: { user, pass },
})
try {
@@ -97,12 +95,13 @@ export const panelSmtpAdapter =
from,
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
})
return { messageId: info.messageId, sent: true }
return { 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 as Error).message}`)
return { error: 'Failed to send email.', sent: false }
// `detail` is for the panel status (mailAdapter), not for end users.
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message }
}
},
})
+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
}
+11 -12
View File
@@ -1,14 +1,13 @@
import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
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
}
/**
@@ -16,8 +15,8 @@ type Props = {
* 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 }: Props) {
if (!payload) {return null}
export async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {
if (!payload) return null
let doc: Record<string, unknown>
try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
@@ -27,20 +26,20 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { turn
const failing = Object.entries(checks)
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
.filter((x) => x.status?.state === 'degraded')
if (!failing.length) {return null}
if (!failing.length) return null
return (
<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',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>Integration problem — the site still works, but a safeguard is off.</strong>
<strong>Integration problem — the site still works, but something needs attention.</strong>
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
{failing.map(({ label, status }) => (
<li key={label}>
@@ -2,14 +2,14 @@
import { useFormFields } from '@payloadcms/ui'
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
}
const fmt = (iso: unknown) => {
if (typeof iso !== 'string' || !iso) {return ''}
if (typeof iso !== 'string' || !iso) return ''
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
}
@@ -19,18 +19,18 @@ const fmt = (iso: unknown) => {
* 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 }: Props) {
export function IntegrationStatusBanner({ statusField, label }: Props) {
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
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 (
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
</div>
)
@@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ label, statusField }: Props) {
<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',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>{label} is not working — forms are accepted without this check.</strong>
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
{code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission.
</div>
</div>
+3 -3
View File
@@ -1,6 +1,6 @@
export {
buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
buildIntegrationStatusField,
buildIntegrationStatusBanner,
} from './status.js'
export type { IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationStatus, IntegrationState } from './status.js'
+16 -16
View File
@@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload'
* 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
}
const REFRESH_MS = 10 * 60_000
@@ -53,8 +53,8 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
admin: {
components: {
Field: {
clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
clientProps: { statusField, label },
},
},
},
@@ -69,7 +69,7 @@ export async function recordIntegrationStatus(
payload: BasePayload,
field: string,
previous: IntegrationStatus | null | undefined,
next: { code?: string; message?: string; state: IntegrationState },
next: { state: IntegrationState; code?: string; message?: string },
): Promise<void> {
const now = new Date()
const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)
@@ -78,22 +78,22 @@ export async function recordIntegrationStatus(
(!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: IntegrationStatus = {
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 as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
context: { ipalIntegrationStatus: true },
})
} catch (err) {
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
+2 -2
View File
@@ -1,5 +1,5 @@
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 type { TurnstileCheck, TurnstileOutcome } from './verify.js'
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
+34 -36
View File
@@ -1,25 +1,33 @@
import 'server-only'
import type { BasePayload } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
type SiteverifyResponse = {
challenge_ts?: string
'error-codes'?: string[]
hostname?: string
success: boolean
'error-codes'?: string[]
challenge_ts?: string
hostname?: string
}
type IntegrationsWithTurnstile = {
turnstileSecretKey?: null | string
turnstileSecretKey?: string | null
turnstileStatus?: IntegrationStatus | null
}
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 —
@@ -27,16 +35,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
}
/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */
@@ -50,20 +48,20 @@ const STATUS_FIELD = 'turnstileStatus'
* 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 TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded'
export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string }
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */
const CONFIG_ERRORS: Record<string, string> = {
'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: Record<string, string> = {
'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).',
'bad-response': 'Cloudflare returned an unexpected response.',
}
/**
@@ -74,12 +72,12 @@ const PLUGIN_ERRORS: Record<string, string> = {
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export async function checkTurnstile({
ip,
payload,
sendRemoteIp = false,
token,
payload,
ip,
sendRemoteIp = false,
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
if (!token) return { outcome: 'reject', code: 'missing-input-response' }
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
const previous = integrations[STATUS_FIELD]
@@ -88,29 +86,29 @@ export async function checkTurnstile({
const degraded = async (code: string): Promise<TurnstileCheck> => {
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
return { code, outcome: 'degraded' }
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'degraded', code, message })
return { outcome: 'degraded', code }
}
if (!secret) {return degraded('missing-secret')}
if (!secret) return degraded('missing-secret')
const body = new URLSearchParams({ response: token, secret })
if (sendRemoteIp && ip) {body.append('remoteip', ip)}
const body = new URLSearchParams({ secret, response: token })
if (sendRemoteIp && ip) body.append('remoteip', ip)
let data: SiteverifyResponse
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()) as SiteverifyResponse
} 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' })
@@ -119,11 +117,11 @@ export async function checkTurnstile({
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' }
return { outcome: 'reject', code: codes[0] ?? 'unknown' }
}
/**