- exports: ipalKit, IpalOptions, ipalEnvRules, IpalEnvFeatures, ipalT, ipalVar, IPAL_TOKENS, IPAL_BREAKPOINTS, IpalTokenName, IpalGlobalSlug are aliases of the iapl names - env: IAPL_* is read first, IPAL_* as fallback (readEnv; EnvRule.aliases for assertEnv); the crawler service reads IPAL_CRAWLER_SITES too - doctor: reads ipal-doctor.json when it is the only one, the old pointer block, ipal-audit-skip and old skill folders; new rule legacy-names (info) and storage-names (warning) - iapl-skills: installs iapl-*, removes the 16 old folders by exact name, rewrites the old pointer block in place; a project's own ipal-* skill stays - storageNames: 'ipal' (default) | 'iapl': the cookie the scanner declares and the 2FA counter's kv prefix; <PageStats visitorCookie>, IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix - test/legacyNames.test.ts: 24 tests for all of the above Co-Authored-By: Claude Fable 5.2 <[email protected]>
243 lines
8.9 KiB
TypeScript
243 lines
8.9 KiB
TypeScript
import { readEnv } from './envName.js'
|
||
|
||
type Bucket = { count: number; resetAt: number }
|
||
|
||
/**
|
||
* 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.
|
||
*
|
||
* 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). Multi-instance deployments can plug in a shared store with
|
||
* setRateLimitStore() (Redis, Upstash, …).
|
||
*
|
||
* 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>()
|
||
|
||
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */
|
||
let lastSweep = Date.now()
|
||
const SWEEP_INTERVAL = 60_000
|
||
|
||
function sweep(now: number) {
|
||
if (now - lastSweep < SWEEP_INTERVAL) {return}
|
||
lastSweep = now
|
||
for (const [key, bucket] of buckets) {
|
||
if (bucket.resetAt <= now) {buckets.delete(key)}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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
|
||
/** Max submissions allowed per window. Defaults to 5. */
|
||
max?: number
|
||
/** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */
|
||
scope?: string
|
||
/** Window length in ms. Defaults to 60_000 (one minute). */
|
||
windowMs?: number
|
||
}
|
||
|
||
type CheckArgs = { cost?: number } & RateLimitArgs
|
||
|
||
/**
|
||
* Requests with no usable client IP (a proxy that strips the header, a
|
||
* misconfigured IAPL_IP_HEADER) share one bucket with a roomier limit. Letting
|
||
* them through unlimited meant a client that simply omits the header walked
|
||
* past every limiter; one shared bucket keeps real visitors flowing while
|
||
* capping the flood.
|
||
*/
|
||
export const UNKNOWN_IP_KEY = 'unknown-ip'
|
||
/** Default multiplier for the shared no-IP bucket. */
|
||
export const UNKNOWN_IP_FACTOR = 20
|
||
|
||
let unknownIpFactor = UNKNOWN_IP_FACTOR
|
||
|
||
/**
|
||
* How requests with no client IP are limited, for every limiter in the plugin:
|
||
* the shared bucket's limit is `factor` × max. `0` = let them through
|
||
* unlimited (the behaviour before 1.13 — only when a limiter in front, e.g.
|
||
* Cloudflare, already covers them). Default UNKNOWN_IP_FACTOR.
|
||
*/
|
||
export function setUnknownIpFactor(factor: number): void {
|
||
unknownIpFactor = Math.max(0, factor)
|
||
}
|
||
|
||
function resolveKey(key: string, max: number): { key: string; max: number } | null {
|
||
if (key) {return { key, max }}
|
||
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
|
||
}
|
||
|
||
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) counts against one shared bucket with
|
||
* UNKNOWN_IP_FACTOR × max (setUnknownIpFactor).
|
||
*/
|
||
export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean {
|
||
const resolved = resolveKey(rawKey, rawMax)
|
||
if (!resolved) {return true}
|
||
const { key, max } = resolved
|
||
const id = `${scope}:${key}`
|
||
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
|
||
}
|
||
|
||
/**
|
||
* 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: rawKey,
|
||
max: rawMax = 5,
|
||
scope = 'form',
|
||
windowMs = 60_000,
|
||
}: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> {
|
||
const resolved = resolveKey(rawKey, rawMax)
|
||
if (!resolved) {return { ok: true, retryAfter: 0 }}
|
||
const { key, max } = resolved
|
||
const id = `${scope}:${key}`
|
||
|
||
let bucket: Bucket
|
||
if (store) {
|
||
try {
|
||
bucket = await store.hit(id, cost, windowMs)
|
||
} catch (err) {
|
||
console.warn('[iapl] 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 IAPL_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 (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 counts it in
|
||
* the shared UNKNOWN_IP_KEY bucket.
|
||
*/
|
||
let warnedUnpinned = false
|
||
|
||
export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string {
|
||
const h = source instanceof Headers ? source : source.headers
|
||
const pinned = options.header ?? readEnv('IAPL_IP_HEADER')
|
||
if (!pinned && !warnedUnpinned && process.env.NODE_ENV === 'production') {
|
||
warnedUnpinned = true
|
||
console.warn(
|
||
'[iapl] IAPL_IP_HEADER is not set — the rate limit trusts whichever IP header a request carries, ' +
|
||
'so a client reaching the app directly can spoof it. Set IAPL_IP_HEADER=cf-connecting-ip ' +
|
||
'(behind Cloudflare) or x-forwarded-for (behind Traefik/nginx only).',
|
||
)
|
||
}
|
||
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-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(retryAfter: number, body: unknown): Response {
|
||
return Response.json(body, {
|
||
headers: { 'cache-control': 'no-store', 'retry-after': String(Math.max(1, retryAfter)) },
|
||
status: 429,
|
||
})
|
||
}
|