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]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:59:52 +02:00
co-authored by Claude Opus 5.5
107 changed files with 5476 additions and 2541 deletions
+119 -110
View File
@@ -1,31 +1,31 @@
# turnstile
Cloudflare Turnstile: widget (client) + weryfikacja (server). Klucze z
SiteIntegrations (panel, nie env). Widget dostaje `siteKey` jako prop; verify
czyta secret server-side.
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
Brak opcji — pola `turnstileSiteKey` / `turnstileSecretKey` są w
SiteIntegrations (tab Turnstile). Edytor wpisuje klucze w panelu (fallback z env:
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`).
**Włączony = oba klucze ustawione.** Wtedy widget się pokazuje, a `submitForm`
**wymaga** poprawnego tokenu: brak tokenu to odrzucenie, więc bot nie ominie
sprawdzenia, po prostu go nie wysyłając. Nieskonfigurowany (lub tylko jeden klucz,
co trafia do logu) → widgetu nie ma, sprawdzenia nie ma, formularze działają.
Stan zwraca `getTurnstileConfig(payload)` → `{ enabled, siteKey }`.
**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 }`.
## Front — widget (client)
## Frontend — widget (client)
Import z `@intecion/ipal-kit/client`. `siteKey` pobierz server-side i przekaż jako prop:
Import from `@intecion/ipal-kit/client`. Fetch `siteKey` server-side and pass it as a prop:
```tsx
// server component — publiczny siteKey, null gdy Turnstile wyłączony
// server component — public siteKey, null when Turnstile is off
import { getTurnstileConfig } from '@intecion/ipal-kit'
const { siteKey } = await getTurnstileConfig(payload)
// przekaż do swojego client-formularza → widget (siteKey null → widget nic nie renderuje)
// pass it to your client form → widget (siteKey null → the widget renders nothing)
```
```tsx
@@ -37,7 +37,7 @@ function ContactForm({ siteKey }) {
const [token, setToken] = useState<string | null>(null)
return (
<form>
{/* pola */}
{/* fields */}
<Turnstile siteKey={siteKey} onToken={setToken} theme="auto" />
<button disabled={!token}>Wyślij</button>
</form>
@@ -45,92 +45,99 @@ function ContactForm({ siteKey }) {
}
```
Widget ładuje skrypt Turnstile sam (bez `next/script`), zwraca token przez
`onToken` (null przy wygaśnięciu/błędzie).
The widget loads the Turnstile script itself (without `next/script`) and returns the token through
`onToken` (null on expiry/error).
## Front — verify (server)
## Frontend — verify (server)
```ts
import { verifyTurnstile } from '@intecion/ipal-kit/server'
const ok = await verifyTurnstile({ token, payload, ip })
if (!ok) {
// odrzuć zgłoszenie
// reject the submission
}
```
`verifyTurnstile` czyta secret z SiteIntegrations (Local API), a gdy pole jest
puste — ze zmiennej **`TURNSTILE_SECRET_KEY`** (ta sama, której wymaga
`ipalEnvRules({ turnstile: true })`). Zwraca `true` dla `pass`, `false` dla `reject`,
a dla `degraded` (problem po naszej stronie, patrz niżej) — zależnie od
`onConfigError`: **domyślnie `'allow'` → `true`**, `'reject'` → `false`. Brak tokenu
→ `false`. Każdy wynik inny niż `pass` jest **logowany** w logach serwera:
`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 | Przyczyna | Wynik |
| Log | Cause | Result |
|---|---|---|
| `[ipal] Turnstile degraded (missing-secret): …` | brak sekretu w panelu i w env (przy każdej weryfikacji) | `degraded` |
| `[ipal] Turnstile degraded (invalid-input-secret): …` | zły sekret albo para site key / secret z różnych widgetów | `degraded` |
| `[ipal] Turnstile: siteverify request failed: …` + `degraded (network-error)` | brak wyjścia do `challenges.cloudflare.com` z kontenera (timeout 8 s) | `degraded` |
| `[ipal] Turnstile degraded (internal-error \| bad-response)` | Cloudflare zwrócił 5xx / błąd wewnętrzny / nieoczekiwaną odpowiedź | `degraded` |
| `[ipal] Turnstile rejected: timeout-or-duplicate` | token użyty drugi raz albo starszy niż 300 s | `reject` |
| `[ipal] Turnstile rejected: invalid-input-response` | uszkodzony / pusty token z frontu | `reject` |
| `[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` |
Opcje `verifyTurnstile` / `checkTurnstile`: `token`, `payload` (wymagane), `ip?`,
`sendRemoteIp?` (`false`), a tylko `verifyTurnstile` — `onConfigError?` (`'allow'`).
`verifyTurnstile` / `checkTurnstile` options: `token`, `payload` (required), `ip?`,
`sendRemoteIp?` (`false`), `hostnames?`, and for `verifyTurnstile` only — `onConfigError?` (`'allow'`).
### Awaria po naszej stronie ≠ odrzucenie formularza
### A failure on our side ≠ rejecting the form
`checkTurnstile` (z `/server`) klasyfikuje wynik:
`checkTurnstile` (from `/server`) classifies the result:
| Wynik | Kiedy | `submitForm` (domyślnie) |
| Result | When | `submitForm` (default) |
|---|---|---|
| `pass` | token poprawny | przyjmuje |
| `reject` | zły token **odwiedzającego**: `invalid-input-response`, `timeout-or-duplicate`, brak tokenu | **odrzuca** (`reason: 'turnstile'`) |
| `degraded` | błąd **po naszej stronie**: brak sekretu, `invalid-input-secret` / `missing-input-secret`, Cloudflare nieosiągalny / 5xx / `internal-error` / nieoczekiwana odpowiedź | **przyjmuje** (`turnstileOnConfigError: 'allow'`) — limit, honeypot i walidacja dalej działają |
| `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 |
> Uwaga: przy domyślnym `'allow'` błędny sekret w panelu (`invalid-input-secret`)
> oznacza, że formularze przyjmują zgłoszenia **bez skutecznej weryfikacji** —
> widoczne tylko jako alert w panelu i log. `submitForm` sprawdza Turnstile tylko
> gdy oba klucze są ustawione (`getTurnstileConfig().enabled`); wtedy brak tokenu
> zawsze → `reason: 'turnstile'`.
> 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'`.
Przy `degraded` panel pokazuje problem:
- **Dashboard** — czerwony alert „Integration problem…” z linkiem do Site Integrations
(`admin.components.beforeDashboard`, wpinany przez plugin automatycznie),
- **Site Integrations → Turnstile** — baner z przyczyną, kodem i czasem.
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.
Status zapisuje serwer przy weryfikacji formularza (bez crona), najwyżej raz na 10 min
przy trwającym błędzie i od razu przy zmianie stanu. Zapis nowych kluczy w panelu
czyści status; po następnym wysłaniu formularza pojawi się aktualny.
Twardo (fail closed): `submitForm({ …, turnstileOnConfigError: 'reject' })`.
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.
Po aktualizacji pluginu: `pnpm payload generate:importmap` (nowe komponenty panelu);
Postgres: `pnpm payload migrate:create` (pole `turnstileStatus` w SiteIntegrations).
**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.
`remoteip` **nie jest** wysyłany domyślnie — za Cloudflare/Traefikiem/Dockerem IP
widziane przez aplikację bywa inne niż to, z którego rozwiązano wyzwanie (IPv6 na
telefonie vs IPv4 proxy). Włączenie: `verifyTurnstile({ …, sendRemoteIp: true })`.
After a plugin update: `pnpm payload generate:importmap` (new panel components);
Postgres: `pnpm payload migrate:create` (the `turnstileStatus` field in SiteIntegrations).
**Diagnoza „formularz zawsze odrzuca Turnstile”:** najpierw logi serwera (tabela
wyżej), potem czy sekret jest w bazie:
`docker exec <mongo> mongosh <db> --eval 'db.globals.findOne({globalType:"site-integrations"}, {turnstileSecretKey:1})'`
(adapter Mongo trzyma wszystkie globale w kolekcji `globals`).
Nie zapisuj sekretu kodem (`updateGlobal` w `onInit` / akcji) — nadpisuje panel przy
każdym starcie; jeśli wolisz env, ustaw `TURNSTILE_SECRET_KEY` i zostaw pole puste. `server-only` gwarantuje, że nie
trafi do bundla przeglądarki.
`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 })`.
> W formularzach zwykle nie wołasz `verifyTurnstile` wprost — robi to
> `submitForm` (patrz [forms.md](./forms.md)).
**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.
## Uproszczone wpięcie — TurnstileProvider + useTurnstile (zalecane)
> In forms you usually do not call `verifyTurnstile` directly —
> `submitForm` does it (see [forms.md](./forms.md)).
Jak CookieBanner: siteKey raz w layoutcie, formularze biorą z kontekstu. Koniec
przekazywania siteKey do każdego formularza.
## Simpler wiring — TurnstileProvider + useTurnstile (recommended)
### 1. Provider w layoutcie (raz, siteKey z serwera)
Like CookieBanner: siteKey once in the layout, forms take it from context. No more
passing siteKey to every form.
Z `SiteProviders` (PROGRAMISTA §2.8) provider jest już wpięty — klucz z `getSiteShell(locale).turnstileSiteKey`,
widget renderuje `RenderForm` na ostatnim kroku formularza. Ręcznie:
### 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)
@@ -139,7 +146,7 @@ import { TurnstileProvider } from '@intecion/ipal-kit/client'
import { getCachedPayload } from '@/lib/content'
export default async function Layout({ children }) {
// tylko publiczny siteKey (null, gdy Turnstile nie jest skonfigurowany) — sekret nigdy nie trafia do klienta
// only the public siteKey (null when Turnstile is not configured) — the secret never reaches the client
const { siteKey } = await getTurnstileConfig(await getCachedPayload())
return (
<html>
@@ -153,7 +160,7 @@ export default async function Layout({ children }) {
}
```
### 2. Formularz — useTurnstile (zero plumbingu siteKey)
### 2. Form — useTurnstile (no siteKey plumbing)
```tsx
'use client'
@@ -164,61 +171,63 @@ function ContactForm() {
async function handleSubmit(data) {
const result = await submitAction(formId, data, token ?? undefined) // server action → submitForm (forms.md)
reset() // token jest jednorazowy — nowy na każde wysłanie, także po błędzie
reset() // the token is single-use — a new one for every submission, also after an error
}
return (
<form onSubmit={...}>
{/* pola formularza */}
<TurnstileWidget /> {/* widget tam, gdzie ma być */}
{/* form fields */}
<TurnstileWidget /> {/* the widget where you want it */}
<button type="submit">Wyślij</button>
</form>
)
}
```
`token` → do submitForm. `TurnstileWidget` (opcjonalny prop `theme`) → wstaw gdzie ma być.
`reset()` → po wysłaniu. `enabled` → false gdy provider dostał `siteKey: null` (widget nie
renderuje się; weryfikację po stronie serwera i tak decyduje `getTurnstileConfig`).
`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()` tylko **czyści `token` w stanie Reacta** — nie woła `turnstile.reset()` na
widżecie Cloudflare. Nowy token pojawi się dopiero, gdy widżet wygeneruje go ponownie
(np. po wygaśnięciu, ok. 300 s) albo zostanie zamontowany od nowa.
`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()` poza `<TurnstileProvider>` rzuca błąd. `useOptionalTurnstile()`
(też z `/client`) zwraca wtedy `enabled: false` zamiast rzucać — używa go `BuilderForm`.
`useTurnstile()` outside `<TurnstileProvider>` throws. `useOptionalTurnstile()`
(also from `/client`) returns `enabled: false` there instead of throwing — `BuilderForm` uses it.
### Props `<Turnstile>`
### `<Turnstile>` props
| Prop | Typ | Domyślnie | Opis |
| Prop | Type | Default | Description |
|---|---|---|---|
| `siteKey` | `string` | — | pusty → nic nie renderuje |
| `onToken` | `(token: string \| null) => void` | — | token po rozwiązaniu; `null` przy wygaśnięciu / błędzie / zmianie motywu |
| `theme` | `'page' \| 'auto' \| 'light' \| 'dark'` | `'page'` | `'page'` = motyw strony (`data-theme`, ThemeScript), bez motywu → `'auto'` |
| `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'` |
### Dlaczego Turnstile NIE jest w pełni "wstaw i zapomnij" jak CookieBanner
### Why Turnstile is NOT fully "drop in and forget" like CookieBanner
CookieBanner jest samodzielny (renderuje się, zarządza zgodą, zero interakcji).
Turnstile z natury jest CZĘŚCIĄ formularza — zwraca token, który formularz musi
wysłać przy submit i zweryfikować server-side. Nie da się go „wstawić
gdziekolwiek" — musi być w formularzu, przy jego logice wysyłki.
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 to maksimum uproszczenia: siteKey raz (jak CookieBanner), a w
formularzu tylko `<TurnstileWidget/>` + `token`. Reszta (weryfikacja) dzieje się
w submitForm automatycznie.
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.
### Stary sposób (nadal działa)
### The old way (still works)
`<Turnstile siteKey={...} onToken={...} />` bezpośrednio — jeśli potrzebujesz
pełnej kontroli albo masz nietypowy przypadek. Provider to warstwa wygody nad tym.
`<Turnstile siteKey={...} onToken={...} />` directly — if you need
full control or have an unusual case. The provider is a convenience layer over it.
## Wyłączenie, nadpisanie, rozszerzenie
## Turn off, override, extend
- **Wyłączenie:** zostaw oba klucze puste (panel i env) → brak widgetu, `submitForm` pomija sprawdzenie.
Pola Turnstile w Site Integrations są obecnie zawsze dodawane.
- **Fail closed:** `turnstileOnConfigError: 'reject'` w `submitForm` / `createSubmitAction`
(albo `onConfigError: 'reject'` w `verifyTurnstile`).
- **Klucze:** panel wygrywa; puste pole → env `NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY`.
- **Wygląd:** `theme` na `<Turnstile>` / `<TurnstileWidget theme>`, `turnstileTheme` w `RenderForm` / `BuilderForm`.
- **Własna integracja:** `checkTurnstile` (pełna klasyfikacja `pass` / `reject` / `degraded`),
- **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`.