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
+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' }
}
/**