/** * Cloudflare Turnstile server-side verification. * * Pass the token from the client widget + your secret key. This module * never reads process.env — the consuming app supplies config. * * Docs: https://developers.cloudflare.com/turnstile/get-started/server-side-validation/ * Adapted from the proven @adamarant/cms implementation. */ const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify' export interface TurnstileVerifyOptions { /** The token returned by the Turnstile widget on the client. */ token: string /** Your Turnstile secret key. */ secretKey: string /** Optional end-user IP (recommended). */ remoteIp?: string /** Optional idempotency key to allow safe retries of the same token. */ idempotencyKey?: string /** Override the siteverify endpoint (useful for tests). */ endpoint?: string } export interface TurnstileVerifyResult { success: boolean /** Raw error codes from Cloudflare, if any. */ errorCodes?: string[] /** ISO timestamp of the challenge, if provided. */ challengeTs?: string /** Hostname the challenge was solved on, if provided. */ hostname?: string } interface SiteverifyResponse { success: boolean 'error-codes'?: string[] challenge_ts?: string hostname?: string } /** * Verify a Turnstile token against Cloudflare's siteverify endpoint. * Returns `{ success: false }` (never throws) on network or parse errors, * with `errorCodes` populated so the caller can log. */ export async function verifyTurnstileToken( options: TurnstileVerifyOptions ): Promise { const { token, secretKey, remoteIp, idempotencyKey, endpoint } = options if (!token) { return { success: false, errorCodes: ['missing-input-response'] } } if (!secretKey) { return { success: false, errorCodes: ['missing-input-secret'] } } const body = new URLSearchParams() body.set('secret', secretKey) body.set('response', token) if (remoteIp) body.set('remoteip', remoteIp) if (idempotencyKey) body.set('idempotency_key', idempotencyKey) try { const res = await fetch(endpoint ?? SITEVERIFY_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), }) if (!res.ok) { return { success: false, errorCodes: [`http-${res.status}`] } } const data = (await res.json()) as SiteverifyResponse return { success: data.success === true, errorCodes: data['error-codes'], challengeTs: data.challenge_ts, hostname: data.hostname, } } catch (err) { const message = err instanceof Error ? err.message : 'unknown-error' return { success: false, errorCodes: [`fetch-failed:${message}`] } } }