Every plugin limiter counts IPv6 per /64 (setIpv6Grouping)
clientIp() returns the whole IPv6 address and every limiter keyed on it, so
one host with a /64 had 2^64 budgets: 50 addresses of one /64 against a
limit of 5 all passed (IAWL idea 9, owner's Q4). consumeRateLimit and
checkRateLimit now count an IPv6 key by its /64 (an IPv4-mapped address by
its IPv4); the mail service's per-visitor account-mail key too. A second
counter per /48 at 10x the limit is available and off by default
(setIpv6Grouping({ wide: 48 })); setIpv6Grouping({ prefix: 128 }) counts
per address as before. ipRateKey(ip) is exported for own limiters.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
15b5c6258d
commit
97c62f21f0
+112
-13
@@ -1,3 +1,5 @@
|
||||
import { isIPv4, isIPv6 } from 'node:net'
|
||||
|
||||
import { readEnv } from './envName.js'
|
||||
|
||||
type Bucket = { count: number; resetAt: number }
|
||||
@@ -94,8 +96,95 @@ export function setUnknownIpFactor(factor: number): void {
|
||||
unknownIpFactor = Math.max(0, factor)
|
||||
}
|
||||
|
||||
/**
|
||||
* IPv6 is counted per network, not per address (1.17.2, 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.17.2). 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 }
|
||||
}
|
||||
|
||||
/** The 8 groups of an IPv6 address as numbers, or null. */
|
||||
function ipv6Groups(address: string): null | number[] {
|
||||
const bare = address.replace(/^\[|\]$/g, '').split('%')[0]
|
||||
if (!isIPv6(bare)) {return null}
|
||||
let text = bare
|
||||
const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text)
|
||||
if (v4) {
|
||||
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)}`
|
||||
}
|
||||
const [head, tail] = text.includes('::') ? text.split('::') : [text, undefined]
|
||||
const left = head ? head.split(':') : []
|
||||
const right = tail ? tail.split(':') : []
|
||||
const fill = tail === undefined ? [] : Array(8 - left.length - right.length).fill('0')
|
||||
const groups = [...left, ...fill, ...right].map((g) => parseInt(g, 16))
|
||||
return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null
|
||||
}
|
||||
|
||||
/** `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, max }}
|
||||
if (key) {return { key: ipRateKey(key), max }}
|
||||
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
|
||||
}
|
||||
|
||||
@@ -125,10 +214,16 @@ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope =
|
||||
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}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -149,26 +244,30 @@ export async function consumeRateLimit({
|
||||
if (!resolved) {return { ok: true, retryAfter: 0 }}
|
||||
const { key, max } = resolved
|
||||
const id = `${scope}:${key}`
|
||||
const wide = wideKeyOf(rawKey)
|
||||
|
||||
let bucket: Bucket
|
||||
if (store) {
|
||||
const hit = async (bucketId: string): Promise<Bucket | null> => {
|
||||
if (!store) {return hitMemory(bucketId, cost, windowMs)}
|
||||
try {
|
||||
bucket = await store.hit(id, cost, windowMs)
|
||||
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 { ok: true, retryAfter: 0 }
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
bucket = hitMemory(id, cost, windowMs)
|
||||
}
|
||||
const bucket = await hit(id)
|
||||
if (!bucket) {return { ok: true, retryAfter: 0 }}
|
||||
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
|
||||
|
||||
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000))
|
||||
return { ok: bucket.count <= max, retryAfter }
|
||||
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 }
|
||||
}
|
||||
|
||||
/** 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}`)
|
||||
const bucket = buckets.get(`${scope}:${key ? ipRateKey(key) : UNKNOWN_IP_KEY}`)
|
||||
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user