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
+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.