PROGRAMISTA §6 rows 83–87 now 1.18.0 (1.17.2 was never released alone) and new rows 88–94; iapl-upgrade blocks for speed and growth and for drafts in related documents, the 1.17.2 blocks as "→ 1.18.0 (from 1.17.2)"; every "since 1.17.2" in docs, comments and tests reads 1.18.0; reference skills, AGENTS.md and the reference index on 1.18.0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
370 lines
15 KiB
TypeScript
370 lines
15 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)
|
||
}
|
||
|
||
/**
|
||
* IPv6 is counted per network, not per address (1.18.0, IAWL idea 9). A host with IPv6 gets a whole /64
|
||
* (2^64 addresses) — every home connection and every server does — so counting per address gave one visitor
|
||
* as many budgets as it has addresses. Every limiter of the plugin (forms, search, MCP, consent log, stats,
|
||
* doctor, the mail service's confirm route and account-mail limit) counts a /64 as one client. One home network
|
||
* shares the budget then, as an IPv4 home behind one router always did.
|
||
*
|
||
* Optionally a second, roomier counter per wider network (`wide: 48`, `wideFactor` × the limit): one hosting
|
||
* customer often holds a /48 (65,536 /64s). Off by default — mobile carriers can put many phones in one /48.
|
||
*/
|
||
export type Ipv6Grouping = {
|
||
/** Prefix length one client is counted by. Default 64; 128 = per address (as before 1.18.0). 1–128. */
|
||
prefix?: number
|
||
/** A second counter per this wider prefix (e.g. 48), at `wideFactor` × the limit. Default: none. */
|
||
wide?: false | number
|
||
/** Multiplier for the wide counter's limit. Default 10. */
|
||
wideFactor?: number
|
||
}
|
||
|
||
let ipv6 = { prefix: 64, wide: 0, wideFactor: 10 }
|
||
|
||
/** How every limiter of the plugin counts IPv6 clients (call once at start). `setIpv6Grouping({ prefix: 128 })` = per address. */
|
||
export function setIpv6Grouping(next: Ipv6Grouping = {}): void {
|
||
const prefix = next.prefix ?? 64
|
||
const wide = next.wide === false || next.wide === undefined ? 0 : next.wide
|
||
const wideFactor = next.wideFactor ?? 10
|
||
for (const [name, value, min] of [['prefix', prefix, 1], ['wide', wide, 0], ['wideFactor', wideFactor, 1]] as const) {
|
||
if (!Number.isInteger(value) || value < min || value > (name === 'wideFactor' ? 1e6 : 128)) {
|
||
throw new Error(`[iapl] setIpv6Grouping: ${name} must be a whole number from ${min}${name === 'wideFactor' ? '' : ' to 128'} (received ${JSON.stringify(value)}).`)
|
||
}
|
||
}
|
||
if (wide && wide >= prefix) {throw new Error(`[iapl] setIpv6Grouping: wide (${wide}) must be a shorter prefix than prefix (${prefix}).`)}
|
||
ipv6 = { prefix, wide, wideFactor }
|
||
}
|
||
|
||
/** A dotted IPv4 address (no `node:net`: this module also reaches bundles that are not Node's). */
|
||
function isIPv4(value: string): boolean {
|
||
const parts = value.split('.')
|
||
return parts.length === 4 && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)
|
||
}
|
||
|
||
/** The 8 groups of an IPv6 address as numbers (brackets and a zone id allowed), or null when it is not one. */
|
||
function ipv6Groups(address: string): null | number[] {
|
||
let text = address.replace(/^\[|\]$/g, '').split('%')[0]
|
||
if (!text.includes(':') || !/^[0-9a-f:.]+$/i.test(text) || text.split('::').length > 2) {return null}
|
||
const v4 = /(?:^|:)(\d+\.\d+\.\d+\.\d+)$/.exec(text)
|
||
if (v4) {
|
||
if (!isIPv4(v4[1])) {return null}
|
||
const [a, b, c, d] = v4[1].split('.').map(Number)
|
||
text = text.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`
|
||
} else if (text.includes('.')) {return null}
|
||
const compressed = text.includes('::')
|
||
const [head, tail = ''] = compressed ? text.split('::') : [text]
|
||
const left = head ? head.split(':') : []
|
||
const right = tail ? tail.split(':') : []
|
||
if ([...left, ...right].some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) {return null}
|
||
const missing = 8 - left.length - right.length
|
||
if (compressed ? missing < 1 : missing !== 0) {return null}
|
||
return [...left, ...Array(compressed ? missing : 0).fill('0'), ...right].map((g) => parseInt(g, 16))
|
||
}
|
||
|
||
/** `2001:db8:1:2::/64` for any address of that network (`bits` = prefix length). */
|
||
function ipv6Network(groups: number[], bits: number): string {
|
||
const out = groups.map((g, i) => {
|
||
const start = i * 16
|
||
if (start >= bits) {return 0}
|
||
const keep = Math.min(16, bits - start)
|
||
return keep === 16 ? g : g & ((0xffff << (16 - keep)) & 0xffff)
|
||
})
|
||
return `${out.map((g) => g.toString(16)).join(':')}/${bits}`
|
||
}
|
||
|
||
/**
|
||
* The key one client is counted by: an IPv4 address as it is, an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`) as
|
||
* its IPv4, an IPv6 address as its network (`setIpv6Grouping`, default /64). Anything else is returned unchanged.
|
||
* Use it for a limiter of your own keyed by `clientIp()`.
|
||
*/
|
||
export function ipRateKey(ip: string): string {
|
||
const value = ip.trim()
|
||
if (!value || isIPv4(value)) {return value}
|
||
const groups = ipv6Groups(value)
|
||
if (!groups) {return value}
|
||
const mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff
|
||
if (mapped) {return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`}
|
||
return ipv6Network(groups, ipv6.prefix)
|
||
}
|
||
|
||
/** The wide network of an IPv6 key, when the wide counter is on; null otherwise. */
|
||
function wideKeyOf(ip: string): null | string {
|
||
if (!ipv6.wide) {return null}
|
||
const groups = ipv6Groups(ip.trim())
|
||
if (!groups || (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff)) {return null}
|
||
return ipv6Network(groups, ipv6.wide)
|
||
}
|
||
|
||
function resolveKey(key: string, max: number): { key: string; max: number } | null {
|
||
if (key) {return { key: ipRateKey(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 wide = wideKeyOf(rawKey)
|
||
const wideId = wide ? `${scope}:${wide}` : null
|
||
const used = (bucketId: string) => {
|
||
const current = buckets.get(bucketId)
|
||
return current && current.resetAt > Date.now() ? current.count : 0
|
||
}
|
||
if (used(id) + cost > max) {return false}
|
||
if (wideId && used(wideId) + cost > max * ipv6.wideFactor) {return false}
|
||
hitMemory(id, cost, windowMs)
|
||
if (wideId) {hitMemory(wideId, 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}`
|
||
const wide = wideKeyOf(rawKey)
|
||
|
||
const hit = async (bucketId: string): Promise<Bucket | null> => {
|
||
if (!store) {return hitMemory(bucketId, cost, windowMs)}
|
||
try {
|
||
return await store.hit(bucketId, cost, windowMs)
|
||
} catch (err) {
|
||
console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err)
|
||
return null
|
||
}
|
||
}
|
||
const bucket = await hit(id)
|
||
if (!bucket) {return { ok: true, retryAfter: 0 }}
|
||
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
|
||
|
||
const over = [bucket.count > max ? bucket : null, wideBucket && wideBucket.count > max * ipv6.wideFactor ? wideBucket : null].filter((b): b is Bucket => b !== null)
|
||
const later = over.reduce((at, b) => Math.max(at, b.resetAt), bucket.resetAt)
|
||
const retryAfter = Math.max(1, Math.ceil(((over.length ? later : bucket.resetAt) - Date.now()) / 1000))
|
||
return { ok: over.length === 0, retryAfter }
|
||
}
|
||
|
||
/**
|
||
* Gives back one place that `consumeRateLimit` took (`cost` 1) — for a limiter that counts only failures: it takes
|
||
* a place before it compares (a burst cannot slip under the limit) and gives it back when the attempt was right.
|
||
* Never below zero in memory; with a shared store, `hit(id, -cost)` (a store that cannot take a negative cost
|
||
* simply keeps the place: fewer attempts, never more).
|
||
*/
|
||
export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): Promise<void> {
|
||
const resolved = resolveKey(rawKey, rawMax)
|
||
if (!resolved) {return}
|
||
const id = `${scope}:${resolved.key}`
|
||
if (store) {
|
||
try {
|
||
await store.hit(id, -cost, windowMs)
|
||
} catch {
|
||
// the place stays taken until the window ends
|
||
}
|
||
return
|
||
}
|
||
const bucket = buckets.get(id)
|
||
if (bucket && bucket.resetAt > Date.now()) {bucket.count = Math.max(0, bucket.count - cost)}
|
||
}
|
||
|
||
/** 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 ? ipRateKey(key) : UNKNOWN_IP_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,
|
||
})
|
||
}
|