diff --git a/dev/int.spec.ts b/dev/int.spec.ts deleted file mode 100644 index 04e6982..0000000 --- a/dev/int.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { Payload } from 'payload' - -import config from '@payload-config' -import { createPayloadRequest, getPayload } from 'payload' -import { afterAll, beforeAll, describe, expect, test } from 'vitest' - -import { customEndpointHandler } from '../src/endpoints/customEndpointHandler.js' - -let payload: Payload - -afterAll(async () => { - await payload.destroy() -}) - -beforeAll(async () => { - payload = await getPayload({ config }) -}) - -describe('Plugin integration tests', () => { - test('should query custom endpoint added by plugin', async () => { - const request = new Request('http://localhost:3000/api/my-plugin-endpoint', { - method: 'GET', - }) - - const payloadRequest = await createPayloadRequest({ config, request }) - const response = await customEndpointHandler(payloadRequest) - expect(response.status).toBe(200) - - const data = await response.json() - expect(data).toMatchObject({ - message: 'Hello from custom endpoint', - }) - }) - - test('can create post with custom text field added by plugin', async () => { - const post = await payload.create({ - collection: 'posts', - data: { - addedByPlugin: 'added by plugin', - }, - }) - expect(post.addedByPlugin).toBe('added by plugin') - }) - - test('plugin creates and seeds plugin-collection', async () => { - expect(payload.collections['plugin-collection']).toBeDefined() - - const { docs } = await payload.find({ collection: 'plugin-collection' }) - - expect(docs).toHaveLength(1) - }) -}) diff --git a/docs/access.md b/docs/access.md index a4a847f..1a751cf 100644 --- a/docs/access.md +++ b/docs/access.md @@ -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 diff --git a/docs/agent/skills/ipal-form/resources/actions.ts b/docs/agent/skills/ipal-form/resources/actions.ts index 2bec06b..6e0f02f 100644 --- a/docs/agent/skills/ipal-form/resources/actions.ts +++ b/docs/agent/skills/ipal-form/resources/actions.ts @@ -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) } } diff --git a/docs/email.md b/docs/email.md index bfd08a5..bec799e 100644 --- a/docs/email.md +++ b/docs/email.md @@ -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`, diff --git a/docs/forms.md b/docs/forms.md index 1242e46..e4079fc 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -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. diff --git a/docs/turnstile.md b/docs/turnstile.md index 5e1230c..3b2b753 100644 --- a/docs/turnstile.md +++ b/docs/turnstile.md @@ -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 ( @@ -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 diff --git a/src/index.ts b/src/index.ts index aec77b2..325bce8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,12 @@ export { SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG, } from './modules/payload/index.js' +// Imported from the file, not the turnstile barrel — that one re-exports verify, +// which imports 'server-only'. +export { getTurnstileConfig } from './modules/turnstile/config.js' +export type { TurnstileConfig } from './modules/turnstile/config.js' +export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js' +export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js' export { composeTitle, diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index 165bc6a..45e647e 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -9,7 +9,11 @@ import { ROLE_HIERARCHY } from './types.js' * Builds the fixed `roles` field the plugin injects into the auth collection. * * Saved to the JWT so role checks avoid a database lookup. Only admins can - * change roles, preventing privilege escalation by lower-privilege users. + * set or change roles, preventing privilege escalation by lower-privilege + * users — including on create, so an open sign-up can't post roles: ['admin']. + * A non-admin's new account gets `defaultRole`. The first-user screen and + * Local API calls (seed scripts) run with overrideAccess, so they can still + * create the first admin. */ export function buildRolesField(defaultRole: Role = 'user'): Field { return { @@ -17,6 +21,7 @@ export function buildRolesField(defaultRole: Role = 'user'): Field { type: 'select', access: { // Only admins may assign or change roles + create: ({ req: { user } }) => isAdmin(user), update: ({ req: { user } }) => isAdmin(user), }, admin: { diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index d7692f9..26ba5cf 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -2,12 +2,16 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' -import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js' +import type { ClientIpOptions } from '../shared/rateLimit.js' + +import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { searchContent } from './searchContent.js' type CreateSearchRouteArgs = { /** Absolute origin to prefix result URLs with. */ baseUrl?: string + /** How to read the client IP for the rate limit — see clientIp(). */ + clientIp?: ClientIpOptions /** Pages collection. Default 'pages'. */ collection?: string config: I18nConfig @@ -17,7 +21,7 @@ type CreateSearchRouteArgs = { /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | string /** - * Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }. + * Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }. * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). */ rateLimit?: { max?: number; windowMs?: number } | false @@ -50,9 +54,9 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) = return async (req: Request) => { if (rl) { - const ip = clientIp(req) - if (!checkRateLimit({ key: ip, scope: 'search', ...rl })) { - return tooManyRequests(ip, 'search', { count: 0, error: 'Too many requests', query: '', results: [] }) + const limit = await consumeRateLimit({ key: clientIp(req, args.clientIp), scope: 'search', ...rl }) + if (!limit.ok) { + return tooManyRequests(limit.retryAfter, { count: 0, error: 'Too many requests', query: '', results: [] }) } } const url = new URL(req.url) diff --git a/src/modules/email/test/testEmailEndpoint.ts b/src/modules/email/test/testEmailEndpoint.ts index 26b298c..3998727 100644 --- a/src/modules/email/test/testEmailEndpoint.ts +++ b/src/modules/email/test/testEmailEndpoint.ts @@ -2,6 +2,8 @@ import type { Endpoint, PayloadRequest } from 'payload' import { addDataAndFileToRequest } from 'payload' +import { isAdmin } from '../../access/predicates.js' + /** * Custom endpoint: send a test email to a given address through whatever * transport is currently active (SMTP or Graph — mailAdapter reads the panel @@ -17,10 +19,14 @@ import { addDataAndFileToRequest } from 'payload' */ export const testEmailEndpoint: Endpoint = { handler: async (req: PayloadRequest) => { - // Auth: only signed-in admins may trigger a send. + // Auth: only admins may trigger a send — the same gate as the + // SiteIntegrations global that holds the transport settings. if (!req.user) { return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 }) } + if (!isAdmin(req.user)) { + return Response.json({ error: 'Forbidden', ok: false }, { status: 403 }) + } await addDataAndFileToRequest(req) const to = (req.data?.to as string | undefined)?.trim() diff --git a/src/modules/forms/rateLimit.ts b/src/modules/forms/rateLimit.ts index d29a07c..9ac2d97 100644 --- a/src/modules/forms/rateLimit.ts +++ b/src/modules/forms/rateLimit.ts @@ -1,3 +1,10 @@ // Moved to modules/shared/rateLimit.ts (shared with search and MCP routes). -export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js' -export type { RateLimitArgs } from '../shared/rateLimit.js' +export { + checkRateLimit, + clientIp, + consumeRateLimit, + retryAfterSeconds, + setRateLimitStore, + tooManyRequests, +} from '../shared/rateLimit.js' +export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js' diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index e91ccd0..45eb902 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -1,8 +1,9 @@ import 'server-only' import type { BasePayload } from 'payload' -import { verifyTurnstile } from '../turnstile/index.js' +import { getTurnstileConfig } from '../turnstile/config.js' +import { verifyTurnstile } from '../turnstile/verify.js' import { validateSubmission } from './validateSubmission.js' -import { checkRateLimit } from './rateLimit.js' +import { consumeRateLimit } from './rateLimit.js' export type SubmitFormArgs = { payload: BasePayload @@ -10,7 +11,11 @@ export type SubmitFormArgs = { formId: string /** Submitted field data — shape matches the form's fields. */ data: Record - /** Turnstile token; when present it is verified, when absent it is skipped. */ + /** + * Turnstile token. Required whenever Turnstile is configured (both keys — + * see getTurnstileConfig): a missing token is then rejected. Ignored when + * Turnstile is not configured. + */ turnstileToken?: string /** Client IP — used for Turnstile and rate limiting. */ ip?: string @@ -96,14 +101,18 @@ export async function submitForm({ }: SubmitFormArgs): Promise { // 1. Rate limit — cheapest gate, drops a flood before any real work. if (maxPerMinute > 0 && ip) { - if (!checkRateLimit({ key: ip, max: maxPerMinute })) { + if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) { return { success: false, reason: 'rate_limited' } } } - // 2. Turnstile — verify when a token is supplied; reject on failure. - if (turnstileToken !== undefined) { - const ok = await verifyTurnstile({ token: turnstileToken, payload, ip, onConfigError: turnstileOnConfigError }) + // 2. Turnstile — decided by the SERVER's config, never by whether the client + // sent a token: configured → a token is required and verified (a bot can't + // opt out by omitting it); not configured → skipped, the widget isn't shown. + if ((await getTurnstileConfig(payload)).enabled) { + const ok = + Boolean(turnstileToken) && + (await verifyTurnstile({ token: turnstileToken!, payload, ip, onConfigError: turnstileOnConfigError })) if (!ok) { return { success: false, reason: 'turnstile' } } diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 8cae5ca..42195d7 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -5,7 +5,9 @@ import type { I18nConfig } from '../i18n/index.js' import { createMarkdownRenderer, searchContent } from '../content/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js' -import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js' +import type { ClientIpOptions } from '../shared/rateLimit.js' + +import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' /** * A read-only MCP (Model Context Protocol) server for the client site, as a Next @@ -41,6 +43,8 @@ const DEFAULT_PROTOCOL = '2025-06-18' type CreateMcpRouteArgs = { /** Absolute origin for building result URLs. */ baseUrl?: string + /** How to read the client IP for the rate limit — see clientIp(). */ + clientIp?: ClientIpOptions /** Pages collection. Default 'pages'. */ collection?: string config: I18nConfig @@ -50,7 +54,7 @@ type CreateMcpRouteArgs = { /** Max messages in one JSON-RPC batch. Default 10. */ maxBatch?: number /** - * Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory, per instance). Default { max: 60, windowMs: 60_000 }. + * Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory per instance, or the store from setRateLimitStore). Default { max: 60, windowMs: 60_000 }. * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). */ rateLimit?: { max?: number; windowMs?: number } | false @@ -224,9 +228,9 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), { status: 400 }) } if (rl) { - const ip = clientIp(req) - if (!checkRateLimit({ cost: messages, key: ip, scope: 'mcp', ...rl })) { - return tooManyRequests(ip, 'mcp', rpcError(null, -32000, 'Too many requests')) + const limit = await consumeRateLimit({ cost: messages, key: clientIp(req, args.clientIp), scope: 'mcp', ...rl }) + if (!limit.ok) { + return tooManyRequests(limit.retryAfter, rpcError(null, -32000, 'Too many requests')) } } diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 6348ef0..85c271d 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -1,18 +1,19 @@ type Bucket = { count: number; resetAt: number } /** - * Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and + * Per-key fixed window. Shared by submitForm, createSearchRoute and * createMcpRoute — each uses its own `scope`, so a busy search box never eats * into the contact form's budget. * - * Deliberately simple: no Redis, no dependency. The trade-off is that the - * counter lives in one process — with several instances behind a load balancer - * each keeps its own, so the effective limit is per-instance, not global. For a + * By default the counters live in memory: no Redis, no dependency. The + * trade-off is that each process keeps its own, so with several instances + * behind a load balancer the effective limit is per-instance, not global. For a * contact form that's fine (it raises the cost of flooding without pretending - * to be airtight); a high-security form should put a real limiter in front. + * to be airtight). Multi-instance deployments can plug in a shared store with + * setRateLimitStore() (Redis, Upstash, …). * - * State is module-level, so it survives between requests but resets on redeploy - * — acceptable for abuse throttling. + * In-memory state is module-level, so it survives between requests but resets + * on redeploy — acceptable for abuse throttling. */ const buckets = new Map() @@ -28,6 +29,33 @@ function sweep(now: number) { } } +/** + * A shared counter backend. `hit` adds `cost` to the counter `id` — creating it + * with a `windowMs` TTL when absent or expired — and returns the new count and + * when the window resets (epoch ms). It must be atomic per id (e.g. Redis + * INCRBY + PEXPIRE NX in one MULTI). + * + * @example + * // Redis (ioredis) + * setRateLimitStore({ + * async hit(id, cost, windowMs) { + * const [[, count], , [, ttl]] = await redis + * .multi().incrby(id, cost).pexpire(id, windowMs, 'NX').pttl(id).exec() + * return { count: Number(count), resetAt: Date.now() + Number(ttl) } + * }, + * }) + */ +export type RateLimitStore = { + hit: (id: string, cost: number, windowMs: number) => Promise +} + +let store: null | RateLimitStore = null + +/** Use a shared store (Redis, …) for every limiter in the plugin. `null` = back to memory. */ +export function setRateLimitStore(next: null | RateLimitStore): void { + store = next +} + export type RateLimitArgs = { /** Identifier to limit on — typically the client IP. */ key: string @@ -39,59 +67,132 @@ export type RateLimitArgs = { windowMs?: number } +type CheckArgs = { cost?: number } & RateLimitArgs + +function hitMemory(id: string, cost: number, windowMs: number): Bucket { + const now = Date.now() + sweep(now) + const bucket = buckets.get(id) + if (!bucket || bucket.resetAt <= now) { + const fresh = { count: cost, resetAt: now + windowMs } + buckets.set(id, fresh) + return fresh + } + bucket.count += cost + return bucket +} + /** + * Synchronous, IN-MEMORY check — ignores setRateLimitStore. Kept for + * backwards compatibility; the plugin's own routes use consumeRateLimit. + * * Returns true when the request is within the limit, false when it should be * rejected. A missing key (no IP) is allowed through — better to accept a * submission than to block everyone behind a proxy that strips the header. */ -export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: { cost?: number } & RateLimitArgs): boolean { +export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean { if (!key) {return true} - - const now = Date.now() - sweep(now) - const id = `${scope}:${key}` - const bucket = buckets.get(id) - - if (!bucket || bucket.resetAt <= now) { - if (cost > max) {return false} - buckets.set(id, { count: cost, resetAt: now + windowMs }) - return true - } - - if (bucket.count + cost > max) { - return false - } - - bucket.count += cost + const current = buckets.get(id) + const used = current && current.resetAt > Date.now() ? current.count : 0 + if (used + cost > max) {return false} + hitMemory(id, cost, windowMs) return true } -/** Seconds until the key's window resets — for a Retry-After header. */ +/** + * Counts the request against the limit — in the shared store when one is set, + * in memory otherwise — and says whether it may proceed. A failing store lets + * the request through (logged): a Redis outage must not take the site's forms + * down with it. + */ +export async function consumeRateLimit({ + cost = 1, + key, + max = 5, + scope = 'form', + windowMs = 60_000, +}: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> { + if (!key) {return { ok: true, retryAfter: 0 }} + const id = `${scope}:${key}` + + let bucket: Bucket + if (store) { + try { + bucket = await store.hit(id, cost, windowMs) + } catch (err) { + console.warn('[ipal] rate limit store failed, allowing request:', err instanceof Error ? err.message : err) + return { ok: true, retryAfter: 0 } + } + } else { + bucket = hitMemory(id, cost, windowMs) + } + + const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) + return { ok: bucket.count <= max, retryAfter } +} + +/** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */ export function retryAfterSeconds(key: string, scope = 'form'): number { const bucket = buckets.get(`${scope}:${key}`) return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1 } +export type ClientIpOptions = { + /** + * Read the IP from this header only (e.g. 'cf-connecting-ip' behind + * Cloudflare, 'x-real-ip' behind nginx). Falls back to the IPAL_IP_HEADER env + * var. Pin it in production: without it the headers below are tried in turn, + * and a client that reaches the app directly could set any of them. + */ + header?: string + /** + * Trusted reverse proxies that APPEND to X-Forwarded-For (Traefik, nginx, a + * load balancer). The client IP is the entry this many hops from the right. + * Default 1 — one proxy in front, as with Coolify/Traefik. + */ + trustedProxies?: number +} + /** - * Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the - * edge, the real visitor), then the first `x-forwarded-for` hop, then - * `x-real-ip`. Empty string when none — the limiter then lets the request through. + * Client IP from a Request (route handlers) or Headers (server actions: + * `clientIp(await headers())`). + * + * Without `header`: Cloudflare's `cf-connecting-ip`, then `x-real-ip`, then + * X-Forwarded-For counted from the RIGHT. The leftmost XFF entry is whatever + * the client sent, so trusting it would let anyone pick a fresh IP per request + * and walk past the rate limit; each proxy appends the address it saw, so the + * rightmost entries are the trustworthy ones. + * + * Empty string when nothing usable is present — the limiter then lets the + * request through. */ -export function clientIp(req: Request): string { - const h = req.headers +export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string { + const h = source instanceof Headers ? source : source.headers + const pinned = options.header ?? process.env.IPAL_IP_HEADER + if (pinned) { + const value = h.get(pinned) + if (!value) {return ''} + return pinned.toLowerCase() === 'x-forwarded-for' ? fromForwardedFor(value, options.trustedProxies) : value.trim() + } + const forwarded = h.get('x-forwarded-for') return ( h.get('cf-connecting-ip')?.trim() || - h.get('x-forwarded-for')?.split(',')[0]?.trim() || h.get('x-real-ip')?.trim() || - '' + (forwarded ? fromForwardedFor(forwarded, options.trustedProxies) : '') ) } +function fromForwardedFor(value: string, trustedProxies = 1): string { + const hops = value.split(',').map((s) => s.trim()).filter(Boolean) + if (!hops.length) {return ''} + return hops[Math.max(0, hops.length - Math.max(1, trustedProxies))] +} + /** Standard 429 for route handlers. */ -export function tooManyRequests(key: string, scope: string, body: unknown): Response { +export function tooManyRequests(retryAfter: number, body: unknown): Response { return Response.json(body, { - headers: { 'cache-control': 'no-store', 'retry-after': String(retryAfterSeconds(key, scope)) }, + headers: { 'cache-control': 'no-store', 'retry-after': String(Math.max(1, retryAfter)) }, status: 429, }) } diff --git a/src/modules/turnstile/TurnstileProvider.tsx b/src/modules/turnstile/TurnstileProvider.tsx index 077662e..8ec7bad 100644 --- a/src/modules/turnstile/TurnstileProvider.tsx +++ b/src/modules/turnstile/TurnstileProvider.tsx @@ -21,11 +21,12 @@ const TurnstileContext = createContext(null) * * // layout.tsx (server) → read key, pass to provider * import { TurnstileProvider } from '@intecion/ipal-kit/client' - * const siteKey = await getTurnstileSiteKey() // your server helper + * import { getTurnstileConfig } from '@intecion/ipal-kit' + * const { siteKey } = await getTurnstileConfig(payload) // null unless both keys are set * {children} * * When siteKey is null (Turnstile not configured), widgets render nothing and - * token stays null — forms should treat "no Turnstile" as allowed in dev. + * token stays null — submitForm skips the check too, so the form just works. */ export function TurnstileProvider({ siteKey, diff --git a/src/modules/turnstile/config.ts b/src/modules/turnstile/config.ts new file mode 100644 index 0000000..81309c2 --- /dev/null +++ b/src/modules/turnstile/config.ts @@ -0,0 +1,57 @@ +import type { BasePayload } from 'payload' + +import { getSiteIntegrations } from '../payload/getSiteIntegrations.js' + +type IntegrationsWithTurnstileKeys = { + turnstileSecretKey?: null | string + turnstileSiteKey?: null | string +} + +/** Env fallbacks — the same names ipalEnvRules({ turnstile: true }) requires. */ +export const TURNSTILE_SITE_KEY_ENV = 'NEXT_PUBLIC_TURNSTILE_SITE_KEY' +export const TURNSTILE_SECRET_ENV = 'TURNSTILE_SECRET_KEY' + +export type TurnstileConfig = { + /** True when BOTH keys are set — the widget shows and submitForm requires a token. */ + enabled: boolean + /** Public site key for ; null when Turnstile is off. */ + siteKey: null | string +} + +let warnedPartial = false + +/** + * Whether Turnstile is on, and the public key to render it with. + * + * Turnstile is on only when BOTH keys are configured (SiteIntegrations → Turnstile + * in the panel, falling back to NEXT_PUBLIC_TURNSTILE_SITE_KEY / + * TURNSTILE_SECRET_KEY). Not configured → no widget and no check: the site works + * without it. Configured → the widget shows and submitForm REQUIRES a valid + * token, so a bot can't skip the check by leaving the token out. + * + * Half-configured (only one key) counts as off — a widget without a secret + * can't be verified, a secret without a widget would reject every visitor — + * and is logged once so it doesn't go unnoticed. + * + * // layout.tsx (server) + * const { siteKey } = await getTurnstileConfig(payload) + * … + * + * Returns only the public key — the secret never leaves the server. + */ +export async function getTurnstileConfig(payload: BasePayload): Promise { + const integrations = await getSiteIntegrations(payload) + const siteKey = integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || '' + const secret = integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || '' + + if (siteKey && secret) {return { enabled: true, siteKey }} + + if ((siteKey || secret) && !warnedPartial) { + warnedPartial = true + console.warn( + `[ipal] Turnstile is half-configured (${siteKey ? 'secret key' : 'site key'} missing) — ` + + 'treating it as off. Fill in both keys in Site Integrations → Turnstile.', + ) + } + return { enabled: false, siteKey: null } +} diff --git a/src/modules/turnstile/index.ts b/src/modules/turnstile/index.ts index 992cca5..72eaa21 100644 --- a/src/modules/turnstile/index.ts +++ b/src/modules/turnstile/index.ts @@ -2,4 +2,6 @@ // imported from a client component — use ./client for the widget instead. export { verifyTurnstile, checkTurnstile } from './verify.js' export type { TurnstileCheck, TurnstileOutcome } from './verify.js' +export { getTurnstileConfig } from './config.js' +export type { TurnstileConfig } from './config.js' export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js' diff --git a/src/modules/turnstile/verify.ts b/src/modules/turnstile/verify.ts index 7700186..6de4359 100644 --- a/src/modules/turnstile/verify.ts +++ b/src/modules/turnstile/verify.ts @@ -2,6 +2,7 @@ import 'server-only' import type { BasePayload } from 'payload' import { getSiteIntegrations } from '../payload/index.js' import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js' +import { TURNSTILE_SECRET_ENV as ENV_SECRET } from './config.js' type SiteverifyResponse = { success: boolean @@ -37,8 +38,6 @@ type VerifyTurnstileArgs = { onConfigError?: 'allow' | 'reject' } -/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */ -const ENV_SECRET = 'TURNSTILE_SECRET_KEY' const STATUS_FIELD = 'turnstileStatus' /** diff --git a/test/access.test.ts b/test/access.test.ts new file mode 100644 index 0000000..64e3b2d --- /dev/null +++ b/test/access.test.ts @@ -0,0 +1,75 @@ +import type { FieldAccess, PayloadRequest } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import { hasMinimumRole, isAdmin, isEditor } from '../src/modules/access/predicates.js' +import { buildRolesField } from '../src/modules/access/rolesField.js' +import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js' + +vi.mock('payload', () => ({ addDataAndFileToRequest: vi.fn(async () => {}) })) + +const admin = { id: 1, roles: ['admin'] } +const editor = { id: 2, roles: ['editor'] } +const user = { id: 3, roles: ['user'] } + +describe('role predicates', () => { + test('hierarchy admin > editor > user', () => { + expect(isAdmin(admin)).toBe(true) + expect(isAdmin(editor)).toBe(false) + expect(isEditor(admin)).toBe(true) + expect(isEditor(user)).toBe(false) + expect(hasMinimumRole(user, 'user')).toBe(true) + }) + + test('unknown roles and odd shapes grant nothing', () => { + expect(isAdmin({ roles: ['root'] })).toBe(false) + expect(isAdmin({ roles: 'admin' })).toBe(false) + expect(isAdmin(null)).toBe(false) + }) +}) + +describe('roles field', () => { + const field = buildRolesField() as { access: { create: FieldAccess; update: FieldAccess } } + const call = (fn: FieldAccess, u: unknown) => fn({ req: { user: u } } as never) + + test('only admins can set roles on create — no self-promotion via sign-up', () => { + expect(call(field.access.create, null)).toBe(false) + expect(call(field.access.create, user)).toBe(false) + expect(call(field.access.create, admin)).toBe(true) + }) + + test('only admins can change roles', () => { + expect(call(field.access.update, editor)).toBe(false) + expect(call(field.access.update, admin)).toBe(true) + }) +}) + +describe('test-email endpoint', () => { + const run = (u: unknown) => { + const sendEmail = vi.fn(async () => ({ sent: true })) + const req = { + data: { to: 'ops@example.com' }, + payload: { logger: { error: vi.fn() }, sendEmail }, + user: u, + } as unknown as PayloadRequest + return { response: testEmailEndpoint.handler(req), sendEmail } + } + + test('anonymous → 401', async () => { + const { response, sendEmail } = run(null) + expect((await response).status).toBe(401) + expect(sendEmail).not.toHaveBeenCalled() + }) + + test('logged-in non-admin → 403', async () => { + const { response, sendEmail } = run(editor) + expect((await response).status).toBe(403) + expect(sendEmail).not.toHaveBeenCalled() + }) + + test('admin → sends', async () => { + const { response, sendEmail } = run(admin) + expect((await response).status).toBe(200) + expect(sendEmail).toHaveBeenCalledOnce() + }) +}) diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..a0b3b75 --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,25 @@ +import type { BasePayload } from 'payload' + +import { vi } from 'vitest' + +type FakeOptions = { + forms?: Record[] }> + integrations?: Record +} + +/** The slice of the Local API the form/Turnstile code touches. */ +export function fakePayload({ forms = {}, integrations = {} }: FakeOptions = {}) { + const create = vi.fn(async () => ({ id: 'sub-1' })) + const payload = { + create, + findByID: vi.fn(async ({ id }: { id: string }) => { + const form = forms[id] + if (!form) {throw new Error('Not Found')} + return { id, ...form } + }), + findGlobal: vi.fn(async () => integrations), + logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() }, + updateGlobal: vi.fn(async () => integrations), + } + return { create, payload: payload as unknown as BasePayload } +} diff --git a/test/i18n.test.ts b/test/i18n.test.ts new file mode 100644 index 0000000..f6fc6f8 --- /dev/null +++ b/test/i18n.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, test } from 'vitest' + +import { buildLocalizedPath, switchLocalePath } from '../src/modules/i18n/localizedPath.js' +import { matchAcceptLanguage, negotiateLocale } from '../src/modules/i18n/negotiateLocale.js' +import { isHoneypotTripped } from '../src/modules/forms/honeypot.js' + +const config = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} +const single = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } + +describe('negotiateLocale', () => { + test('cookie → Accept-Language → default', () => { + expect(negotiateLocale({ acceptLanguage: 'en', config, cookieLocale: 'pl' })).toBe('pl') + expect(negotiateLocale({ acceptLanguage: 'de-DE,en-US;q=0.8', config })).toBe('en') + expect(negotiateLocale({ acceptLanguage: 'fr', config, cookieLocale: 'xx' })).toBe('pl') + }) + + test('respects q-values', () => { + expect(matchAcceptLanguage('en;q=0.5,pl;q=0.9', config)).toBe('pl') + expect(matchAcceptLanguage(null, config)).toBeUndefined() + }) +}) + +describe('buildLocalizedPath', () => { + const slugs = { en: 'about', pl: 'o-nas' } + + test('prefixes the locale', () => { + expect(buildLocalizedPath({ config, locale: 'en', slugs })).toBe('/en/about') + }) + + test('home collapses to the locale root, per-locale home slugs', () => { + const home = { en: 'home', pl: 'strona-glowna' } + expect(buildLocalizedPath({ config, homeSlug: home, locale: 'pl', slugs: home })).toBe('/pl') + expect(buildLocalizedPath({ config, homeSlug: home, locale: 'en', slugs: home })).toBe('/en') + }) + + test('single-locale sites drop the prefix', () => { + expect(buildLocalizedPath({ config: single, locale: 'pl', slugs })).toBe('/o-nas') + expect(buildLocalizedPath({ config: single, locale: 'pl', slugs: { pl: 'home' } })).toBe('/') + }) + + test('archive entries need a prefix in that locale', () => { + const prefix = { pl: 'artykuly' } + expect(buildLocalizedPath({ config, locale: 'pl', prefix, slugs })).toBe('/pl/artykuly/o-nas') + expect(buildLocalizedPath({ config, locale: 'en', prefix, slugs })).toBeUndefined() + }) + + test('unknown locale or missing slug → undefined', () => { + expect(buildLocalizedPath({ config, locale: 'de', slugs })).toBeUndefined() + expect(buildLocalizedPath({ config, locale: 'en', slugs: { pl: 'x' } })).toBeUndefined() + }) +}) + +describe('switchLocalePath', () => { + test('never dead-ends: falls back to archive, then locale root', () => { + expect(switchLocalePath({ config, slugs: { pl: 'post' }, targetLocale: 'en', prefix: { en: 'articles', pl: 'artykuly' } })).toBe( + '/en/articles', + ) + expect(switchLocalePath({ config, slugs: { pl: 'o-nas' }, targetLocale: 'en' })).toBe('/en') + }) +}) + +describe('honeypot', () => { + test('filled → tripped', () => { + expect(isHoneypotTripped({ company_url: 'http://spam' })).toBe(true) + expect(isHoneypotTripped({ company_url: ' ' })).toBe(false) + expect(isHoneypotTripped({})).toBe(false) + }) +}) diff --git a/test/plugin.test.ts b/test/plugin.test.ts new file mode 100644 index 0000000..dece15a --- /dev/null +++ b/test/plugin.test.ts @@ -0,0 +1,51 @@ +import type { Config } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import { ipalKit } from '../src/plugin.js' + +const i18n = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +const base = (): Config => + ({ + collections: [{ slug: 'users', auth: true, fields: [] }], + secret: 'test', + }) as unknown as Config + +describe('ipalKit — config transform', () => { + test('adds globals, endpoint, localization and roles', async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base()) + + expect(config.globals?.map((g) => g.slug)).toEqual( + expect.arrayContaining(['site-settings', 'site-integrations']), + ) + expect(config.endpoints?.some((e) => e.path === '/ipal/test-email')).toBe(true) + expect(config.localization && config.localization.defaultLocale).toBe('pl') + + const users = config.collections?.find((c) => c.slug === 'users') + expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true) + }) + + test('enforces 2FA unless explicitly disabled', async () => { + await expect(ipalKit({ i18n })(base())).rejects.toThrow(/twoFactor\.issuer is required/) + + const totp = vi.fn(() => (c: Config) => c) + await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base()) + expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } })) + }) + + test('enabled: false leaves the config untouched', async () => { + const config = base() + expect(await ipalKit({ enabled: false, i18n, twoFactor: false })(config)).toBe(config) + }) + + test('invalid i18n fails fast', () => { + expect(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow() + }) +}) diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts new file mode 100644 index 0000000..5aca9ed --- /dev/null +++ b/test/rateLimit.test.ts @@ -0,0 +1,97 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { + checkRateLimit, + clientIp, + consumeRateLimit, + setRateLimitStore, +} from '../src/modules/shared/rateLimit.js' + +const req = (headers: Record) => new Request('http://x/', { headers }) + +describe('clientIp', () => { + afterEach(() => { + vi.unstubAllEnvs() + }) + + test('prefers cf-connecting-ip, then x-real-ip', () => { + expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' }))).toBe('1.1.1.1') + expect(clientIp(req({ 'x-forwarded-for': '9.9.9.9', 'x-real-ip': '2.2.2.2' }))).toBe('2.2.2.2') + }) + + test('takes X-Forwarded-For from the right, so a spoofed left entry is ignored', () => { + const r = req({ 'x-forwarded-for': '6.6.6.6, 3.3.3.3' }) + expect(clientIp(r)).toBe('3.3.3.3') + expect(clientIp(r, { trustedProxies: 2 })).toBe('6.6.6.6') + expect(clientIp(r, { trustedProxies: 5 })).toBe('6.6.6.6') + }) + + test('a pinned header is the only one read', () => { + const r = req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' }) + expect(clientIp(r, { header: 'x-real-ip' })).toBe('2.2.2.2') + expect(clientIp(r, { header: 'x-client-ip' })).toBe('') + }) + + test('IPAL_IP_HEADER env pins the header', () => { + vi.stubEnv('IPAL_IP_HEADER', 'x-forwarded-for') + expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-forwarded-for': '6.6.6.6, 4.4.4.4' }))).toBe('4.4.4.4') + }) + + test('accepts Headers (server actions)', () => { + expect(clientIp(new Headers({ 'x-real-ip': '5.5.5.5' }))).toBe('5.5.5.5') + }) + + test('empty when nothing usable is present', () => { + expect(clientIp(req({}))).toBe('') + }) +}) + +describe('checkRateLimit (in memory)', () => { + test('allows up to max per window, then blocks', () => { + const key = `k-${Math.random()}` + for (let i = 0; i < 3; i++) {expect(checkRateLimit({ key, max: 3 })).toBe(true)} + expect(checkRateLimit({ key, max: 3 })).toBe(false) + }) + + test('scopes are independent', () => { + const key = `k-${Math.random()}` + expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(true) + expect(checkRateLimit({ key, max: 1, scope: 'b' })).toBe(true) + expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(false) + }) + + test('a cost above max is refused outright', () => { + expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false) + }) + + test('no key → allowed', () => { + expect(checkRateLimit({ key: '', max: 0 })).toBe(true) + }) +}) + +describe('consumeRateLimit', () => { + afterEach(() => setRateLimitStore(null)) + + test('in memory: blocks after max and reports Retry-After', async () => { + const key = `k-${Math.random()}` + expect((await consumeRateLimit({ key, max: 1, windowMs: 30_000 })).ok).toBe(true) + const blocked = await consumeRateLimit({ key, max: 1, windowMs: 30_000 }) + expect(blocked.ok).toBe(false) + expect(blocked.retryAfter).toBeGreaterThan(25) + }) + + test('uses the configured store', async () => { + const hit = vi.fn(async () => ({ count: 7, resetAt: Date.now() + 10_000 })) + setRateLimitStore({ hit }) + const result = await consumeRateLimit({ cost: 2, key: 'ip', max: 5, scope: 'mcp', windowMs: 10_000 }) + expect(hit).toHaveBeenCalledWith('mcp:ip', 2, 10_000) + expect(result.ok).toBe(false) + }) + + test('a failing store lets the request through', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + setRateLimitStore({ hit: () => Promise.reject(new Error('redis down')) }) + expect((await consumeRateLimit({ key: 'ip', max: 0 })).ok).toBe(true) + warn.mockRestore() + }) +}) diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts new file mode 100644 index 0000000..d8d51db --- /dev/null +++ b/test/submitForm.test.ts @@ -0,0 +1,159 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +import { submitForm } from '../src/modules/forms/submitForm.js' +import { fakePayload } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const forms = { + contact: { + fields: [ + { name: 'name', blockType: 'text', required: true }, + { name: 'consent', blockType: 'checkbox' }, + { blockType: 'message' }, + ], + }, +} +const data = { consent: true, name: 'Ala' } +const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } + +let ipCounter = 0 +const nextIp = () => `10.0.0.${++ipCounter}` + +function mockSiteverify(body: unknown, status = 200) { + return vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(body, { status })) +} + +describe('submitForm — Turnstile', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + }) + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + }) + + test('not configured → no check, the submission is stored', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch') + const { create, payload } = fakePayload({ forms }) + const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload }) + expect(result).toEqual({ submissionId: 'sub-1', success: true }) + expect(create).toHaveBeenCalledOnce() + expect(fetchSpy).not.toHaveBeenCalled() + }) + + test('half-configured (site key only) counts as off', async () => { + const { payload } = fakePayload({ forms, integrations: { turnstileSiteKey: 'site' } }) + expect((await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).success).toBe(true) + }) + + test('configured → a MISSING token is rejected (no opting out by omission)', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch') + const { create, payload } = fakePayload({ forms, integrations: keys }) + const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload }) + expect(result).toEqual({ reason: 'turnstile', success: false }) + expect(create).not.toHaveBeenCalled() + expect(fetchSpy).not.toHaveBeenCalled() + }) + + test('configured from env vars counts too', async () => { + vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'site') + vi.stubEnv('TURNSTILE_SECRET_KEY', 'secret') + const { payload } = fakePayload({ forms }) + expect(await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).toEqual({ + reason: 'turnstile', + success: false, + }) + }) + + test('configured + valid token → stored', async () => { + mockSiteverify({ success: true }) + const { create, payload } = fakePayload({ forms, integrations: keys }) + const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'tok' }) + expect(result.success).toBe(true) + expect(create).toHaveBeenCalledOnce() + }) + + test('configured + bad token → rejected', async () => { + mockSiteverify({ 'error-codes': ['invalid-input-response'], success: false }) + const { create, payload } = fakePayload({ forms, integrations: keys }) + const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'bad' }) + expect(result).toEqual({ reason: 'turnstile', success: false }) + expect(create).not.toHaveBeenCalled() + }) + + test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => { + mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false }) + const { payload } = fakePayload({ forms, integrations: keys }) + const base = { data, formId: 'contact', payload, turnstileToken: 'tok' } + expect((await submitForm({ ...base, ip: nextIp() })).success).toBe(true) + expect(await submitForm({ ...base, ip: nextIp(), turnstileOnConfigError: 'reject' })).toEqual({ + reason: 'turnstile', + success: false, + }) + }) +}) + +describe('submitForm — other gates', () => { + afterEach(() => vi.restoreAllMocks()) + + test('rate limit per IP', async () => { + const { payload } = fakePayload({ forms }) + const ip = nextIp() + for (let i = 0; i < 2; i++) { + expect((await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).success).toBe(true) + } + expect(await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).toEqual({ + reason: 'rate_limited', + success: false, + }) + }) + + test('consent must be checked', async () => { + const { payload } = fakePayload({ forms }) + expect(await submitForm({ data: { ...data, consent: false }, formId: 'contact', ip: nextIp(), payload })).toEqual({ + field: 'consent', + reason: 'consent', + success: false, + }) + }) + + test('required field, unknown keys, unknown form', async () => { + const { payload } = fakePayload({ forms }) + const ip = nextIp() + expect(await submitForm({ data: { consent: true }, formId: 'contact', ip, maxPerMinute: 0, payload })).toEqual({ + field: 'name', + kind: 'required', + reason: 'validation', + success: false, + }) + expect( + await submitForm({ data: { ...data, admin: 1 }, formId: 'contact', ip, maxPerMinute: 0, payload }), + ).toEqual({ kind: 'unknown_fields', reason: 'validation', success: false }) + expect(await submitForm({ data, formId: 'nope', ip, maxPerMinute: 0, payload })).toEqual({ + reason: 'not_found', + success: false, + }) + }) + + test('the captcha field injected by the widget is not an unknown key', async () => { + const { create, payload } = fakePayload({ forms }) + const result = await submitForm({ + data: { ...data, 'cf-turnstile-response': 'x' }, + formId: 'contact', + ip: nextIp(), + payload, + }) + expect(result.success).toBe(true) + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + submissionData: [ + { field: 'name', value: 'Ala' }, + { field: 'consent', value: 'true' }, + ], + }), + }), + ) + }) +}) diff --git a/vitest.config.js b/vitest.config.js index 8d54148..93c4415 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -18,6 +18,7 @@ export default defineConfig(() => { ], test: { environment: 'node', + include: ['test/**/*.test.ts'], hookTimeout: 30_000, testTimeout: 30_000, },