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
+6 -1
View File
@@ -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: {
+9 -5
View File
@@ -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, string> | 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)
+7 -1
View File
@@ -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()
+9 -2
View File
@@ -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'
+16 -7
View File
@@ -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<string, unknown>
/** 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<SubmitFormResult> {
// 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' }
}
+9 -5
View File
@@ -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'))
}
}
+136 -35
View File
@@ -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<string, Bucket>()
@@ -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<Bucket>
}
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,
})
}
+3 -2
View File
@@ -21,11 +21,12 @@ const TurnstileContext = createContext<TurnstileContextValue | null>(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
* <TurnstileProvider siteKey={siteKey}>{children}</TurnstileProvider>
*
* 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,
+57
View File
@@ -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 <TurnstileProvider siteKey>; 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)
* <TurnstileProvider siteKey={siteKey}>…</TurnstileProvider>
*
* Returns only the public key — the secret never leaves the server.
*/
export async function getTurnstileConfig(payload: BasePayload): Promise<TurnstileConfig> {
const integrations = await getSiteIntegrations<IntegrationsWithTurnstileKeys>(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 }
}
+2
View File
@@ -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'
+1 -2
View File
@@ -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'
/**