import type { BasePayload } from 'payload' import { getSiteIntegrations } from '../payload/getSiteIntegrations.js' type IntegrationsWithTurnstileKeys = { turnstileSecretKey?: null | string turnstileSiteKey?: null | string } /** Env fallbacks — the same names ipalEnvRules({ turnstile: true }) requires. */ export const TURNSTILE_SITE_KEY_ENV = 'NEXT_PUBLIC_TURNSTILE_SITE_KEY' export const TURNSTILE_SECRET_ENV = 'TURNSTILE_SECRET_KEY' export type TurnstileConfig = { /** True when BOTH keys are set — the widget shows and submitForm requires a token. */ enabled: boolean /** Public site key for ; null when Turnstile is off. */ siteKey: null | string } let warnedPartial = false function resolveKeys(integrations: IntegrationsWithTurnstileKeys) { return { secret: integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || '', siteKey: integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || '', } } /** * Why Turnstile is half-configured (only one of the two keys set), or null when * it's fully on or fully off. Shown as a dashboard alert by IntegrationAlerts — * the half-configured state silently turns Turnstile OFF, which an editor who * just pasted one key wouldn't expect. */ export function turnstileKeyProblem(integrations: IntegrationsWithTurnstileKeys): null | string { const { secret, siteKey } = resolveKeys(integrations) if (Boolean(siteKey) === Boolean(secret)) {return null} return `${siteKey ? 'Secret key' : 'Site key'} is missing, so Turnstile is OFF — forms are not protected. Fill in both keys (or clear both).` } /** * Whether Turnstile is on, and the public key to render it with. * * Turnstile is on only when BOTH keys are configured (SiteIntegrations → Turnstile * in the panel, falling back to NEXT_PUBLIC_TURNSTILE_SITE_KEY / * TURNSTILE_SECRET_KEY). Not configured → no widget and no check: the site works * without it. Configured → the widget shows and submitForm REQUIRES a valid * token, so a bot can't skip the check by leaving the token out. * * Half-configured (only one key) counts as off — a widget without a secret * can't be verified, a secret without a widget would reject every visitor — * and is logged once so it doesn't go unnoticed. * * // layout.tsx (server) * const { siteKey } = await getTurnstileConfig(payload) * … * * Returns only the public key — the secret never leaves the server. */ export async function getTurnstileConfig(payload: BasePayload): Promise { const integrations = await getSiteIntegrations(payload) const { secret, siteKey } = resolveKeys(integrations) if (siteKey && secret) {return { enabled: true, siteKey }} if ((siteKey || secret) && !warnedPartial) { warnedPartial = true console.warn( `[ipal] Turnstile is half-configured (${siteKey ? 'secret key' : 'site key'} missing) — ` + 'treating it as off. Fill in both keys in Site Integrations → Turnstile.', ) } return { enabled: false, siteKey: null } }