Fixed turnstile
This commit is contained in:
@@ -1,4 +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 { verifyTurnstile } from './verify.js'
|
||||
export { checkTurnstile, verifyTurnstile } from './verify.js'
|
||||
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
|
||||
type SiteverifyResponse = {
|
||||
@@ -13,50 +14,124 @@ type SiteverifyResponse = {
|
||||
|
||||
type IntegrationsWithTurnstile = {
|
||||
turnstileSecretKey?: null | string
|
||||
turnstileStatus?: IntegrationStatus | null
|
||||
}
|
||||
|
||||
type VerifyTurnstileArgs = {
|
||||
/** Optional client IP for stricter verification. */
|
||||
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
|
||||
ip?: string
|
||||
/**
|
||||
* What to do when verification can't run because of OUR side (missing/wrong
|
||||
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
|
||||
* rate limit, honeypot and validation still apply — and show the problem in
|
||||
* 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. */
|
||||
const ENV_SECRET = 'TURNSTILE_SECRET_KEY'
|
||||
const STATUS_FIELD = 'turnstileStatus'
|
||||
|
||||
/**
|
||||
* Verifies a Turnstile token with Cloudflare, server-side only.
|
||||
*
|
||||
* The secret comes from the SiteIntegrations global (editor-managed, per the
|
||||
* plugin's "secrets in the panel" model), read via the Local API which bypasses
|
||||
* access control. `server-only` guarantees this never reaches the browser
|
||||
* bundle, keeping the secret off the client.
|
||||
*
|
||||
* Returns false on any failure (missing secret/token, network error, rejected
|
||||
* challenge) — callers treat false as "do not trust this submission".
|
||||
* - `pass` — token valid.
|
||||
* - `reject` — the VISITOR's token is bad (forged, reused, expired, malformed) → refuse.
|
||||
* - `degraded` — OUR side is broken (no/wrong secret, Cloudflare unreachable or
|
||||
* erroring) → the visitor can't fix it; by default the submission
|
||||
* is accepted and the panel shows the problem.
|
||||
*/
|
||||
export async function verifyTurnstile({
|
||||
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
|
||||
export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
|
||||
|
||||
/** 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.',
|
||||
'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.',
|
||||
}
|
||||
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).',
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies a Turnstile token with Cloudflare and classifies the result (server-only).
|
||||
*
|
||||
* 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,
|
||||
}: VerifyTurnstileArgs): Promise<boolean> {
|
||||
if (!token) {return false}
|
||||
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
|
||||
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
|
||||
|
||||
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
|
||||
const secret = integrations.turnstileSecretKey
|
||||
if (!secret) {return false}
|
||||
const previous = integrations[STATUS_FIELD]
|
||||
const secret = integrations.turnstileSecretKey?.trim() || process.env[ENV_SECRET]?.trim()
|
||||
|
||||
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' }
|
||||
}
|
||||
|
||||
if (!secret) {return degraded('missing-secret')}
|
||||
|
||||
const body = new URLSearchParams({ response: token, secret })
|
||||
if (ip) {body.append('remoteip', ip)}
|
||||
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',
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
const data = (await res.json()) as SiteverifyResponse
|
||||
return data.success
|
||||
} catch {
|
||||
return false
|
||||
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 (data.success) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
|
||||
return { outcome: 'pass' }
|
||||
}
|
||||
|
||||
const codes = data['error-codes'] ?? []
|
||||
const configCode = codes.find((c) => c in CONFIG_ERRORS)
|
||||
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' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Boolean wrapper used by submitForm. `onConfigError` decides what a `degraded`
|
||||
* result means: 'allow' (default) keeps the site's forms working while the
|
||||
* panel shows the problem; 'reject' fails closed.
|
||||
*/
|
||||
export async function verifyTurnstile({ onConfigError = 'allow', ...args }: VerifyTurnstileArgs): Promise<boolean> {
|
||||
const { outcome } = await checkTurnstile(args)
|
||||
return outcome === 'pass' || (outcome === 'degraded' && onConfigError === 'allow')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user