267 lines
14 KiB
Markdown
267 lines
14 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
|
|
|
|
The `turnstileSiteKey` / `turnstileSecretKey` fields are in SiteIntegrations (Spam protection tab): **the
|
|
panel is the source of the keys.** The secret key is write-only there — the panel and the API show "a value is
|
|
set", never the value ([security.md](./security.md) "Stored secrets"). Env fallback for the public site key:
|
|
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`.
|
|
|
|
> **Deprecated: `TURNSTILE_SECRET_KEY` from the environment.** It still works when the panel field is empty,
|
|
> and will be removed in a later release that the changelog names in advance. A site that relies on it logs
|
|
> `[iapl] Deprecated: the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable…` once
|
|
> per start, and `iapl-doctor --url` reports it (`turnstile-env-key`). **Move it:** copy the key into Site
|
|
> integrations → Spam protection → Secret key, send a test form, then remove the variable from the environment
|
|
> (Coolify). Local development with Cloudflare's test keys in `.env` keeps working until the removal.
|
|
|
|
**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 (deprecated, see Config; the same one
|
|
`iaplEnvRules({ turnstile: true })` names). 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 |
|
|
|---|---|---|
|
|
| `[iapl] Turnstile degraded (missing-secret): …` | no secret in the panel or in env (on every verification) | `degraded` |
|
|
| `[iapl] Turnstile degraded (invalid-input-secret): …` | wrong secret, or a site key / secret pair from different widgets | `degraded` |
|
|
| `[iapl] Turnstile: siteverify request failed: …` + `degraded (network-error)` | the container cannot reach `challenges.cloudflare.com` (8 s timeout) | `degraded` |
|
|
| `[iapl] Turnstile degraded (internal-error \| bad-response)` | Cloudflare returned 5xx / an internal error / an unexpected response | `degraded` |
|
|
| `[iapl] Turnstile rejected: timeout-or-duplicate` | token used twice or older than 300 s | `reject` |
|
|
| `[iapl] 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 | a **text form accepts** (`'allow'`) — rate limit, honeypot and validation still work; a **form with files** (the file endpoint) **rejects** (`'reject'`) |
|
|
|
|
**`forms.turnstileOnConfigError`** sets what `degraded` means, once for the project:
|
|
|
|
```ts
|
|
iapl({ forms: {
|
|
// turnstileOnConfigError: 'reject', // every form fails closed
|
|
// turnstileOnConfigError: 'allow', // every form keeps working, forms with files too
|
|
// turnstileOnConfigError: { text: 'allow', files: 'allow' }, // per kind
|
|
} })
|
|
```
|
|
|
|
Default `{ text: 'allow', files: 'reject' }`: an enquiry matters more than spam, but an accepted bot submission
|
|
with a file puts an attachment into a mailbox. A value at a call site (`turnstileOnConfigError` in
|
|
`createSubmitAction` / `submitForm`, `attachments.submit.turnstileOnConfigError`) still wins. Not involved while
|
|
Turnstile is off (no keys). **What an existing site sees:** nothing while Turnstile works; while it is degraded,
|
|
forms with a File field answer "verification failed" instead of sending — fix the keys (the dashboard alert and
|
|
`iapl-doctor --url`, rule `turnstile-degraded`, say so), or set `{ files: 'allow' }`.
|
|
|
|
> Note: where the policy is `'allow'`, a wrong secret in the panel (`invalid-input-secret`)
|
|
> means forms accept submissions **without effective verification** —
|
|
> visible as an alert in the panel, in the log, and in `iapl-doctor --url` (`turnstile-degraded`: a warning,
|
|
> an error after a day). `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 → Spam protection** — 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 (the env variable `TURNSTILE_SECRET_KEY` with an empty field still works but is deprecated: the
|
|
panel is the source). `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()` clears `token` **and makes the widget run its challenge again**, so a new token arrives a moment later
|
|
— a token is single-use, and a form the server refused can be sent again. (Up to 1.15.5 it only cleared the
|
|
React state, and the next send had no token until the old one expired.) Your own `<Turnstile>` outside the
|
|
provider: change its `resetSignal` prop to get the same.
|
|
|
|
`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'` |
|
|
| `resetSignal` | `number` | `0` | change the value → the widget issues a new token (what `reset()` does for the provider's widget) |
|
|
|
|
### 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 / open:** `forms.turnstileOnConfigError` for the project (`'reject'`, `'allow'`, or
|
|
`{ text, files }`); `turnstileOnConfigError` in `submitForm` / `createSubmitAction` /
|
|
`attachments.submit` for one call site (or `onConfigError` in `verifyTurnstile`). From `/server`:
|
|
`passTurnstile`, `passSubmitGates`, `resolveTurnstileOnConfigError`, `TURNSTILE_ON_CONFIG_ERROR_DEFAULT`.
|
|
- **Keys:** the panel is the source; empty site key → env `NEXT_PUBLIC_TURNSTILE_SITE_KEY`; empty secret →
|
|
env `TURNSTILE_SECRET_KEY` (**deprecated**, see Config). `turnstileSecretFromEnv(integrations)` and
|
|
`TURNSTILE_SECRET_ENV` are exported.
|
|
- **Access to the keys:** Site integrations is admin-only (read and update); change it with
|
|
`iapl({ globalOverrides: { 'site-integrations': { access: … } } })` — keep `read` restricted, the secret lives there.
|
|
- **Look:** `theme` on `<Turnstile>` / `<TurnstileWidget theme>`, `turnstileTheme` in `RenderForm` / `BuilderForm`.
|
|
- **Your own integration:** limit first, then ask Cloudflare — `consumeRateLimit({ key: clientIp(req), scope: 'signup' })` before `checkTurnstile`, so a flood of posts does not become a flood of requests to Cloudflare (the plugin's forms do it in this order: `passRateLimit`, then `passTurnstile`). `checkTurnstile` (full `pass` / `reject` / `degraded` classification),
|
|
`verifyTurnstile`, `getTurnstileConfig`, `<Turnstile>`, `useTurnstile` / `useOptionalTurnstile`.
|