Security: mandatory Turnstile when configured, admin-only test email, roles on create, safer client IP

- Turnstile is on only when both keys are set (panel or env); then submitForm
  requires a valid token, so a bot can no longer skip the check by omitting it.
  Not configured -> no widget, no check. New getTurnstileConfig() for layouts.
- /api/ipal/test-email now requires the admin role (403 for other users).
- roles field: create access is admin-only, so open sign-up can't self-assign admin.
- clientIp reads X-Forwarded-For from the right, accepts Headers, can be pinned
  via option or IPAL_IP_HEADER; exposed on search/MCP routes.
- Pluggable shared rate-limit store (setRateLimitStore) for multi-instance setups.
- Replace the template int.spec with real unit tests in test/ (44 tests).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 23:54:25 +02:00
co-authored by Claude Opus 5.5
parent aa284736c9
commit ce0a390351
25 changed files with 786 additions and 133 deletions
+4 -1
View File
@@ -16,7 +16,10 @@ ipalKit({
```
Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może
zmieniać role) do wskazanej kolekcji. Kolekcja należy do Ciebie
nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie
przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji.
Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc
pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie
(create-payload-app) — plugin tylko dokłada pole.
> Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej
@@ -2,7 +2,7 @@
'use server'
import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server'
import { isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export async function sendForm(
@@ -15,8 +15,7 @@ export async function sendForm(
const texts = (await getNotificationTexts({ payload, locale })).form
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success, nothing stored
const { [HONEYPOT_FIELD]: _hp, ...data } = values
const h = await headers() // fine in a server action — never in the page tree (breaks SSG)
const ip = h.get('cf-connecting-ip') ?? h.get('x-forwarded-for')?.split(',')[0]?.trim() ?? undefined
const ip = clientIp(await headers()) || undefined // headers(): fine in a server action — never in the page tree (breaks SSG)
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
+1 -1
View File
@@ -184,7 +184,7 @@ sekretów w .env → log + fallback na SMTP (nie cicha awaria).
W tabie SMTP jest przycisk **Send test**: podaj adres, kliknij, wyślij testowy
mail przez AKTUALNY transport. Pokazuje wynik (✓/✗ z błędem). Endpoint
`POST /api/ipal/test-email` (admin-only). Zapisz zmiany przed testem — endpoint
`POST /api/ipal/test-email` (tylko rola `admin`: niezalogowany → 401, inna rola → 403). Zapisz zmiany przed testem — endpoint
czyta z bazy, nie z pola na ekranie.
> Bezcenne przy diagnozie Graph — od razu widzisz `ErrorSendAsDenied`,
+20 -5
View File
@@ -64,7 +64,7 @@ doklejasz przez `.bind`, kod błędu zamieniasz na tekst z panelu:
'use server'
import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server'
import { isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export async function sendForm(
@@ -77,8 +77,7 @@ export async function sendForm(
const texts = (await getNotificationTexts({ payload, locale })).form
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: udawany sukces
const { [HONEYPOT_FIELD]: _hp, ...data } = values
const h = await headers() // OK w server action — NIE w drzewie strony (SSG)
const ip = h.get('cf-connecting-ip') ?? h.get('x-forwarded-for')?.split(',')[0]?.trim() ?? undefined
const ip = clientIp(await headers()) || undefined // headers(): OK w server action — NIE w drzewie strony (SSG)
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
@@ -92,11 +91,27 @@ const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, f
Wynik `submitForm`: `{ success: true, submissionId }` albo `{ success: false, reason, … }`
(kody niżej). Opcje: `maxPerMinute` (domyślnie 5, `0` wyłącza), `consentFieldName`.
### IP klienta i rate limit
`clientIp(req | headers, { header?, trustedProxies? })` czyta kolejno
`cf-connecting-ip`, `x-real-ip`, a z `X-Forwarded-For` bierze wpis **od prawej**
(lewy wpisuje sam klient, więc mógłby podawać nowe IP przy każdym żądaniu i omijać
limit). Na produkcji przypnij nagłówek, któremu ufasz, np. `IPAL_IP_HEADER=cf-connecting-ip`
za Cloudflare. Bez tego klient, który trafi do aplikacji z pominięciem proxy, może
podstawić dowolny z tych nagłówków. Ta sama opcja `clientIp` jest w `createSearchRoute`
i `createMcpRoute`.
Limity domyślnie trzymane są w pamięci, osobno dla każdej instancji. Kilka instancji
→ wspólny store (np. Redis) raz przy starcie: `setRateLimitStore({ hit })`
(przykład w JSDoc `RateLimitStore`). Gdy store padnie, żądanie przechodzi (log ostrzeżenia).
## Flow i gwarancje
1. **Rate limit** per IP → `rate_limited`.
2. **Turnstile** (jeśli token) → nieudany → odrzuć **przed** zapisem (brak
spamu w bazie). Brak tokenu = pominięcie (decydujesz per formularz).
2. **Turnstile** — decyduje konfiguracja **serwera**, nie to, czy front wysłał token.
Oba klucze ustawione (panel albo env) → token **wymagany**: brak lub nieudany →
`turnstile`, odrzucone **przed** zapisem. Klucze nieustawione → widget się nie
pokazuje, a sprawdzenie jest pomijane. Szczegóły: [turnstile.md](./turnstile.md).
3. **Walidacja** względem definicji formularza z panelu (+ wymuszona zgoda RODO).
4. **Zapis** submission (form-submissions) → form-builder wysyła maile z zakładki Emails.
+16 -11
View File
@@ -7,18 +7,25 @@ czyta secret server-side.
## Config
Brak opcji — pola `turnstileSiteKey` / `turnstileSecretKey` są w
SiteIntegrations (tab Turnstile). Edytor wpisuje klucze w panelu.
SiteIntegrations (tab Turnstile). Edytor wpisuje klucze w panelu (fallback z env:
`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 }`.
## Front — widget (client)
Import z `@intecion/ipal-kit/client`. `siteKey` pobierz server-side i przekaż jako prop:
```tsx
// server component — pobiera publiczny siteKey z panelu
import { getSiteIntegrations } from '@intecion/ipal-kit'
// server component — publiczny siteKey, null gdy Turnstile wyłączony
import { getTurnstileConfig } from '@intecion/ipal-kit'
const { turnstileSiteKey } = await getSiteIntegrations(payload)
// przekaż do swojego client-formularza → widget
const { siteKey } = await getTurnstileConfig(payload)
// przekaż do swojego client-formularza → widget (siteKey null → widget nic nie renderuje)
```
```tsx
@@ -111,15 +118,13 @@ przekazywania siteKey do każdego formularza.
```tsx
// app/(frontend)/[locale]/layout.tsx (server)
import { getSiteIntegrations } from '@intecion/ipal-kit'
import { getTurnstileConfig } from '@intecion/ipal-kit'
import { TurnstileProvider } from '@intecion/ipal-kit/client'
import { getCachedPayload } from '@/lib/content'
export default async function Layout({ children }) {
// tylko publiczny siteKey — sekret Turnstile nigdy nie trafia do klienta
const { turnstileSiteKey: siteKey } = await getSiteIntegrations<{ turnstileSiteKey?: string }>(
await getCachedPayload(),
)
// tylko publiczny siteKey (null, gdy Turnstile nie jest skonfigurowany) — sekret nigdy nie trafia do klienta
const { siteKey } = await getTurnstileConfig(await getCachedPayload())
return (
<html>
<body>
@@ -157,7 +162,7 @@ function ContactForm() {
```
`token` → do submitForm. `TurnstileWidget` → wstaw gdzie ma być. `reset()` → po
wysłaniu. `enabled` → false gdy brak klucza (dev bez Turnstile).
wysłaniu. `enabled` → false gdy Turnstile nie jest skonfigurowany (widget i weryfikacja wyłączone).
### Dlaczego Turnstile NIE jest w pełni "wstaw i zapomnij" jak CookieBanner