Lint: fix all ESLint errors (391 -> 0), lint and typecheck tests
Mostly perfectionist import/key sorting and curly braces from --fix, plus: - spread instead of .apply() in the Meta Pixel stub - non-capturing group in the locale-code pattern - React 19 use(Context) / <Context value> in TurnstileProvider - email regex rewritten without super-linear backtracking (covered by a test) - console.warn/error allowed (deliberate server diagnostics) - test/tsconfig.json so the project service and tsc see test files Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,17 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, useCallback, useContext, useState } from 'react'
|
||||
import { createContext, use, useCallback, useState } from 'react'
|
||||
|
||||
import { Turnstile } from './Turnstile.js'
|
||||
|
||||
type TurnstileContextValue = {
|
||||
setToken: (t: null | string) => void
|
||||
/** Public site key from the provider (read server-side, passed once). */
|
||||
siteKey: string | null
|
||||
siteKey: null | string
|
||||
/** Current token (null until solved / after expiry). */
|
||||
token: string | null
|
||||
setToken: (t: string | null) => void
|
||||
token: null | string
|
||||
}
|
||||
|
||||
const TurnstileContext = createContext<TurnstileContextValue | null>(null)
|
||||
const TurnstileContext = createContext<null | TurnstileContextValue>(null)
|
||||
|
||||
/**
|
||||
* Provides the Turnstile site key once for the whole app, like ConsentProvider
|
||||
@@ -29,17 +30,17 @@ const TurnstileContext = createContext<TurnstileContextValue | null>(null)
|
||||
* token stays null — submitForm skips the check too, so the form just works.
|
||||
*/
|
||||
export function TurnstileProvider({
|
||||
siteKey,
|
||||
children,
|
||||
siteKey,
|
||||
}: {
|
||||
siteKey: string | null
|
||||
children: React.ReactNode
|
||||
siteKey: null | string
|
||||
}) {
|
||||
const [token, setToken] = useState<string | null>(null)
|
||||
const [token, setToken] = useState<null | string>(null)
|
||||
return (
|
||||
<TurnstileContext.Provider value={{ siteKey, token, setToken }}>
|
||||
<TurnstileContext value={{ setToken, siteKey, token }}>
|
||||
{children}
|
||||
</TurnstileContext.Provider>
|
||||
</TurnstileContext>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -53,27 +54,27 @@ export function TurnstileProvider({
|
||||
* // after submit: reset() // clear for the next submission
|
||||
*/
|
||||
export function useTurnstile(): {
|
||||
token: string | null
|
||||
TurnstileWidget: (props?: { theme?: 'light' | 'dark' | 'auto' }) => React.ReactNode
|
||||
reset: () => void
|
||||
/** True when Turnstile is configured (site key present). */
|
||||
enabled: boolean
|
||||
reset: () => void
|
||||
token: null | string
|
||||
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode
|
||||
} {
|
||||
const ctx = useContext(TurnstileContext)
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx) {
|
||||
throw new Error('useTurnstile must be used within <TurnstileProvider>')
|
||||
}
|
||||
const { siteKey, token, setToken } = ctx
|
||||
const { setToken, siteKey, token } = ctx
|
||||
|
||||
const reset = useCallback(() => setToken(null), [setToken])
|
||||
|
||||
const TurnstileWidget = useCallback(
|
||||
(props?: { theme?: 'light' | 'dark' | 'auto' }) => {
|
||||
if (!siteKey) return null
|
||||
return <Turnstile siteKey={siteKey} onToken={setToken} theme={props?.theme} />
|
||||
(props?: { theme?: 'auto' | 'dark' | 'light' }) => {
|
||||
if (!siteKey) {return null}
|
||||
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
|
||||
},
|
||||
[siteKey, setToken],
|
||||
)
|
||||
|
||||
return { token, TurnstileWidget, reset, enabled: Boolean(siteKey) }
|
||||
return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 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, checkTurnstile } from './verify.js'
|
||||
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
|
||||
export { getTurnstileConfig } from './config.js'
|
||||
export type { TurnstileConfig } from './config.js'
|
||||
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 type { TurnstileCheck, TurnstileOutcome } from './verify.js'
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
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'
|
||||
import { TURNSTILE_SECRET_ENV as ENV_SECRET } from './config.js'
|
||||
|
||||
type SiteverifyResponse = {
|
||||
success: boolean
|
||||
'error-codes'?: string[]
|
||||
challenge_ts?: string
|
||||
'error-codes'?: string[]
|
||||
hostname?: string
|
||||
success: boolean
|
||||
}
|
||||
|
||||
type IntegrationsWithTurnstile = {
|
||||
turnstileSecretKey?: string | null
|
||||
turnstileSecretKey?: null | string
|
||||
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 —
|
||||
@@ -36,6 +28,16 @@ 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
|
||||
}
|
||||
|
||||
const STATUS_FIELD = 'turnstileStatus'
|
||||
@@ -47,20 +49,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 = 'pass' | 'reject' | 'degraded'
|
||||
export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string }
|
||||
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> = {
|
||||
'missing-input-secret': 'The secret key is missing in the request.',
|
||||
'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).',
|
||||
'internal-error': 'Cloudflare reported an internal error while verifying.',
|
||||
'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).',
|
||||
'bad-response': 'Cloudflare returned an unexpected response.',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,12 +73,12 @@ const PLUGIN_ERRORS: Record<string, string> = {
|
||||
* SiteIntegrations is updated (throttled) so the panel shows failures.
|
||||
*/
|
||||
export async function checkTurnstile({
|
||||
token,
|
||||
payload,
|
||||
ip,
|
||||
payload,
|
||||
sendRemoteIp = false,
|
||||
token,
|
||||
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
|
||||
if (!token) return { outcome: 'reject', code: 'missing-input-response' }
|
||||
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
|
||||
|
||||
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
|
||||
const previous = integrations[STATUS_FIELD]
|
||||
@@ -85,29 +87,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, { state: 'degraded', code, message })
|
||||
return { outcome: 'degraded', code }
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
|
||||
return { code, outcome: 'degraded' }
|
||||
}
|
||||
|
||||
if (!secret) return degraded('missing-secret')
|
||||
if (!secret) {return degraded('missing-secret')}
|
||||
|
||||
const body = new URLSearchParams({ secret, response: token })
|
||||
if (sendRemoteIp && ip) body.append('remoteip', ip)
|
||||
const body = new URLSearchParams({ response: token, secret })
|
||||
if (sendRemoteIp && ip) {body.append('remoteip', ip)}
|
||||
|
||||
let data: SiteverifyResponse
|
||||
try {
|
||||
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
body,
|
||||
method: 'POST',
|
||||
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' })
|
||||
@@ -116,11 +118,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 { outcome: 'reject', code: codes[0] ?? 'unknown' }
|
||||
return { code: codes[0] ?? 'unknown', outcome: 'reject' }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user