init commit for iPAL-kit plugin
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
'use client'
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
render: (el: HTMLElement, opts: Record<string, unknown>) => string
|
||||
reset: (id?: string) => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT_SRC = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||
|
||||
/** Loads the Turnstile script once, shared across all widget instances. */
|
||||
function ensureScript(): void {
|
||||
if (typeof document === 'undefined') {return}
|
||||
if (document.querySelector(`script[src="${SCRIPT_SRC}"]`)) {return}
|
||||
const script = document.createElement('script')
|
||||
script.src = SCRIPT_SRC
|
||||
script.async = true
|
||||
script.defer = true
|
||||
document.head.appendChild(script)
|
||||
}
|
||||
|
||||
export type TurnstileProps = {
|
||||
/** Called with the token once solved, or null on expiry/error. */
|
||||
onToken: (token: null | string) => void
|
||||
/**
|
||||
* Public Turnstile site key. The client project reads it server-side from
|
||||
* SiteIntegrations (turnstileSiteKey) and passes it in — the widget is a pure
|
||||
* client component and can't read Payload itself.
|
||||
*/
|
||||
siteKey: string
|
||||
theme?: 'auto' | 'dark' | 'light'
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare Turnstile widget — reusable across any form. Renders the challenge
|
||||
* and reports the token via onToken. The token must then be verified
|
||||
* server-side (see verifyTurnstile) before a submission is trusted.
|
||||
*
|
||||
* siteKey is a prop rather than an env var so all Turnstile config lives in one
|
||||
* place (SiteIntegrations), consistent with the plugin's panel-managed model.
|
||||
* The script is injected directly (no next/script dependency) so the widget
|
||||
* stays framework-agnostic.
|
||||
*/
|
||||
export function Turnstile({ onToken, siteKey, theme = 'auto' }: TurnstileProps) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const widgetId = useRef<null | string>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!siteKey) {return}
|
||||
|
||||
ensureScript()
|
||||
|
||||
function render() {
|
||||
if (!ref.current || !window.turnstile || widgetId.current) {return}
|
||||
widgetId.current = window.turnstile.render(ref.current, {
|
||||
callback: (token: string) => onToken(token),
|
||||
'error-callback': () => onToken(null),
|
||||
'expired-callback': () => onToken(null),
|
||||
sitekey: siteKey,
|
||||
theme,
|
||||
})
|
||||
}
|
||||
|
||||
render()
|
||||
// Script may load after mount — retry briefly until ready.
|
||||
const interval = setInterval(render, 300)
|
||||
return () => clearInterval(interval)
|
||||
}, [siteKey, theme, onToken])
|
||||
|
||||
if (!siteKey) {return null}
|
||||
|
||||
return <div ref={ref} />
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
'use client'
|
||||
// Client-only exports — the Turnstile widget. Kept separate from index.ts so
|
||||
// the server-only verify never leaks into a browser bundle.
|
||||
export { Turnstile } from './Turnstile.js'
|
||||
export type { TurnstileProps } from './Turnstile.js'
|
||||
@@ -0,0 +1,3 @@
|
||||
// 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'
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
|
||||
type SiteverifyResponse = {
|
||||
challenge_ts?: string
|
||||
'error-codes'?: string[]
|
||||
hostname?: string
|
||||
success: boolean
|
||||
}
|
||||
|
||||
type IntegrationsWithTurnstile = {
|
||||
turnstileSecretKey?: null | string
|
||||
}
|
||||
|
||||
type VerifyTurnstileArgs = {
|
||||
/** Optional client IP for stricter verification. */
|
||||
ip?: string
|
||||
/** Payload instance — used to read the secret from SiteIntegrations. */
|
||||
payload: BasePayload
|
||||
/** Token produced by the client-side widget. */
|
||||
token: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 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".
|
||||
*/
|
||||
export async function verifyTurnstile({
|
||||
ip,
|
||||
payload,
|
||||
token,
|
||||
}: VerifyTurnstileArgs): Promise<boolean> {
|
||||
if (!token) {return false}
|
||||
|
||||
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
|
||||
const secret = integrations.turnstileSecretKey
|
||||
if (!secret) {return false}
|
||||
|
||||
const body = new URLSearchParams({ response: token, secret })
|
||||
if (ip) {body.append('remoteip', ip)}
|
||||
|
||||
try {
|
||||
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
body,
|
||||
method: 'POST',
|
||||
})
|
||||
const data = (await res.json()) as SiteverifyResponse
|
||||
return data.success
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user