Files
ipal-kit/docs/turnstile.md
T
Radosław SmolińskiandClaude Opus 5.5 b61b753ec2 Merge main (security-perf + SEO) into docs; finish English docs and agent guide
- Resolve conflicts in analytics, consent, content, i18n, mcp and stats,
  keeping the docs fixes and the new code behaviour, verified against src
- Translate the remaining 14 module pages, ipal-seo-check skill and script
- Integrate the security-perf and SEO agent-guide text: getRobots,
  isPathVisible, Search & AI (DNS verification first, meta fields optional),
  sitemap index/cache/503, consentMode basic/advanced, policyVersion,
  globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess,
  firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale
  claims fixed across AGENT.md, skills, frontend, developer guide, vibe
- docsConsistency: pending list removed (all docs English); relative links
  now also check #anchors

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:59:52 +02:00

234 lines
11 KiB
Markdown

# turnstile
Cloudflare Turnstile: widget (client) + verification (server). Keys come from
SiteIntegrations (admin panel, not env). The widget gets `siteKey` as a prop; verify
reads the secret server-side.
## Config
No options — the `turnstileSiteKey` / `turnstileSecretKey` fields are in
SiteIntegrations (Turnstile tab). The editor enters the keys in the panel (env fallback:
`NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY`).
**On = both keys set.** Then the widget shows, and `submitForm`
**requires** a valid token: a missing token is a rejection, so a bot cannot skip
the check simply by not sending one. Not configured (or only one key,
which is logged) → no widget, no check, forms work.
`getTurnstileConfig(payload)` returns the state → `{ enabled, siteKey }`.
## Frontend — widget (client)
Import from `@intecion/ipal-kit/client`. Fetch `siteKey` server-side and pass it as a prop:
```tsx
// server component — public siteKey, null when Turnstile is off
import { getTurnstileConfig } from '@intecion/ipal-kit'
const { siteKey } = await getTurnstileConfig(payload)
// pass it to your client form → widget (siteKey null → the widget renders nothing)
```
```tsx
'use client'
import { Turnstile } from '@intecion/ipal-kit/client'
import { useState } from 'react'
function ContactForm({ siteKey }) {
const [token, setToken] = useState<string | null>(null)
return (
<form>
{/* fields */}
<Turnstile siteKey={siteKey} onToken={setToken} theme="auto" />
<button disabled={!token}>Wyślij</button>
</form>
)
}
```
The widget loads the Turnstile script itself (without `next/script`) and returns the token through
`onToken` (null on expiry/error).
## Frontend — verify (server)
```ts
import { verifyTurnstile } from '@intecion/ipal-kit/server'
const ok = await verifyTurnstile({ token, payload, ip })
if (!ok) {
// reject the submission
}
```
`verifyTurnstile` reads the secret from SiteIntegrations (Local API), and when the field is
empty — from the **`TURNSTILE_SECRET_KEY`** variable (the same one
`ipalEnvRules({ turnstile: true })` requires). It returns `true` for `pass`, `false` for `reject`,
and for `degraded` (a problem on our side, see below) — depending on
`onConfigError`: **by default `'allow'` → `true`**, `'reject'` → `false`. No token
→ `false`. Every result other than `pass` is **logged** in the server logs:
| Log | Cause | Result |
|---|---|---|
| `[ipal] Turnstile degraded (missing-secret): …` | no secret in the panel or in env (on every verification) | `degraded` |
| `[ipal] Turnstile degraded (invalid-input-secret): …` | wrong secret, or a site key / secret pair from different widgets | `degraded` |
| `[ipal] Turnstile: siteverify request failed: …` + `degraded (network-error)` | the container cannot reach `challenges.cloudflare.com` (8 s timeout) | `degraded` |
| `[ipal] Turnstile degraded (internal-error \| bad-response)` | Cloudflare returned 5xx / an internal error / an unexpected response | `degraded` |
| `[ipal] Turnstile rejected: timeout-or-duplicate` | token used twice or older than 300 s | `reject` |
| `[ipal] Turnstile rejected: invalid-input-response` | broken / empty token from the frontend | `reject` |
`verifyTurnstile` / `checkTurnstile` options: `token`, `payload` (required), `ip?`,
`sendRemoteIp?` (`false`), `hostnames?`, and for `verifyTurnstile` only — `onConfigError?` (`'allow'`).
### A failure on our side ≠ rejecting the form
`checkTurnstile` (from `/server`) classifies the result:
| Result | When | `submitForm` (default) |
|---|---|---|
| `pass` | valid token | accepts |
| `reject` | bad token from the **visitor**: `invalid-input-response`, `timeout-or-duplicate`, no token | **rejects** (`reason: 'turnstile'`) |
| `degraded` | an error **on our side**: no secret, `invalid-input-secret` / `missing-input-secret`, Cloudflare unreachable / 5xx / `internal-error` / unexpected response | **accepts** (`turnstileOnConfigError: 'allow'`) — rate limit, honeypot and validation still work |
> Note: with the default `'allow'`, a wrong secret in the panel (`invalid-input-secret`)
> means forms accept submissions **without effective verification** —
> visible only as an alert in the panel and in the log. `submitForm` checks Turnstile only
> when both keys are set (`getTurnstileConfig().enabled`); then a missing token
> always → `reason: 'turnstile'`.
On `degraded` the panel shows the problem:
- **Dashboard** — a red "Integration problem…" alert with a link to Site Integrations
(`admin.components.beforeDashboard`, wired by the plugin automatically),
- **Site Integrations → Turnstile** — a banner with the cause, code and time.
The server saves the status when it verifies a form (no cron), at most once per 10 min
while the error lasts, and at once when the state changes. Saving new keys in the panel
clears the status; the current one appears after the next form submission.
Strict (fail closed): `submitForm({ …, turnstileOnConfigError: 'reject' })`.
The default `allow` is deliberate: `degraded` is caused only by our configuration or a Cloudflare
outage — a visitor cannot force it, and forms do not go down together with Cloudflare.
**Token hostname (optional):** `createSubmitAction({ …, turnstileHostnames: ['www.firma.pl', 'firma.pl'] })`
(or `submitForm` / `verifyTurnstile({ hostnames })`) rejects a token solved on another domain
(`reason: 'turnstile'`, log `token solved on "…"`). Useful when the widget allows any hostname.
Cloudflare's test keys return `example.com` — leave it empty in dev.
After a plugin update: `pnpm payload generate:importmap` (new panel components);
Postgres: `pnpm payload migrate:create` (the `turnstileStatus` field in SiteIntegrations).
`remoteip` is **not** sent by default — behind Cloudflare and Coolify's proxy (Traefik) the IP
the app sees is often different from the one the challenge was solved from (IPv6 on a
phone vs the proxy's IPv4). Turn on: `verifyTurnstile({ …, sendRemoteIp: true })`.
**Diagnosis "the form always rejects Turnstile":** first the server logs (table
above), then whether the secret is in the database — in Coolify open the MongoDB resource → Terminal and run:
`mongosh <db> --eval 'db.globals.findOne({globalType:"site-integrations"}, {turnstileSecretKey:1})'`
(the Mongo adapter keeps all globals in the `globals` collection).
Do not write the secret from code (`updateGlobal` in `onInit` / an action) — it overwrites the panel on
every start; if you prefer env, set `TURNSTILE_SECRET_KEY` and leave the field empty. `server-only` guarantees it never
reaches the browser bundle.
> In forms you usually do not call `verifyTurnstile` directly —
> `submitForm` does it (see [forms.md](./forms.md)).
## Simpler wiring — TurnstileProvider + useTurnstile (recommended)
Like CookieBanner: siteKey once in the layout, forms take it from context. No more
passing siteKey to every form.
### 1. Provider in the layout (once, siteKey from the server)
With `SiteProviders` (developer guide (PROGRAMISTA.md) §2.8) the provider is already wired — the key comes from `getSiteShell(locale).turnstileSiteKey`,
and `RenderForm` renders the widget on the last step of the form. By hand:
```tsx
// app/(frontend)/[locale]/layout.tsx (server)
import { getTurnstileConfig } from '@intecion/ipal-kit'
import { TurnstileProvider } from '@intecion/ipal-kit/client'
import { getCachedPayload } from '@/lib/content'
export default async function Layout({ children }) {
// only the public siteKey (null when Turnstile is not configured) — the secret never reaches the client
const { siteKey } = await getTurnstileConfig(await getCachedPayload())
return (
<html>
<body>
<TurnstileProvider siteKey={siteKey}>
{children}
</TurnstileProvider>
</body>
</html>
)
}
```
### 2. Form — useTurnstile (no siteKey plumbing)
```tsx
'use client'
import { useTurnstile } from '@intecion/ipal-kit/client'
function ContactForm() {
const { token, TurnstileWidget, reset, enabled } = useTurnstile()
async function handleSubmit(data) {
const result = await submitAction(formId, data, token ?? undefined) // server action → submitForm (forms.md)
reset() // the token is single-use — a new one for every submission, also after an error
}
return (
<form onSubmit={...}>
{/* form fields */}
<TurnstileWidget /> {/* the widget where you want it */}
<button type="submit">Wyślij</button>
</form>
)
}
```
`token` → to submitForm. `TurnstileWidget` (optional `theme` prop) → put it where you want it.
`reset()` → after submitting. `enabled` → false when the provider got `siteKey: null` (the widget does not
render; server-side verification is decided by `getTurnstileConfig` anyway).
`reset()` only **clears `token` in React state** — it does not call `turnstile.reset()` on the
Cloudflare widget. A new token appears only when the widget generates one again
(e.g. after expiry, about 300 s) or is mounted again.
`useTurnstile()` outside `<TurnstileProvider>` throws. `useOptionalTurnstile()`
(also from `/client`) returns `enabled: false` there instead of throwing — `BuilderForm` uses it.
### `<Turnstile>` props
| Prop | Type | Default | Description |
|---|---|---|---|
| `siteKey` | `string` | — | empty → renders nothing |
| `onToken` | `(token: string \| null) => void` | — | token once solved; `null` on expiry / error / theme change |
| `theme` | `'page' \| 'auto' \| 'light' \| 'dark'` | `'page'` | `'page'` = the site's theme (`data-theme`, ThemeScript), no theme → `'auto'` |
### Why Turnstile is NOT fully "drop in and forget" like CookieBanner
CookieBanner is self-contained (it renders, manages consent, needs no interaction).
Turnstile is by nature PART of a form — it returns a token that the form must
send on submit and verify server-side. You cannot "drop it
anywhere" — it must be inside the form, next to its submit logic.
Provider+hook is as simple as it gets: siteKey once (like CookieBanner), and in the
form only `<TurnstileWidget/>` + `token`. The rest (verification) happens
in submitForm automatically.
### The old way (still works)
`<Turnstile siteKey={...} onToken={...} />` directly — if you need
full control or have an unusual case. The provider is a convenience layer over it.
## Turn off, override, extend
- **Turn off:** leave both keys empty (panel and env) → no widget, `submitForm` skips the check.
The Turnstile fields in Site Integrations are currently always added.
- **Fail closed:** `turnstileOnConfigError: 'reject'` in `submitForm` / `createSubmitAction`
(or `onConfigError: 'reject'` in `verifyTurnstile`).
- **Keys:** the panel wins; empty field → env `NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY`.
- **Access to the keys:** Site Integrations is admin-only (read and update); change it with
`ipalKit({ globalOverrides: { 'site-integrations': { access: … } } })` — keep `read` restricted, the secret lives there.
- **Look:** `theme` on `<Turnstile>` / `<TurnstileWidget theme>`, `turnstileTheme` in `RenderForm` / `BuilderForm`.
- **Your own integration:** `checkTurnstile` (full `pass` / `reject` / `degraded` classification),
`verifyTurnstile`, `getTurnstileConfig`, `<Turnstile>`, `useTurnstile` / `useOptionalTurnstile`.