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
+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,
})
}