Merge local main (1.17.2) into security-a-118

Conflicts resolved by keeping both sides: lockedAnswer + sign-in rules in plugin.ts and switches.ts, IPv6 grouping in the
mail service's new per-visitor address count, both built-site specs in e2e:built, docs and skills (reference copies
synced). The lockedAnswer suite and the sign-in-answers spec now reach Payload's lock the 1.18.0 way: a spray from
50 IPs, one failure each (one IP alone gets 429 after five).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 12:57:52 +01:00
co-authored by Claude Opus 5.5
113 changed files with 3468 additions and 317 deletions
+118 -13
View File
@@ -94,8 +94,103 @@ 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 }
}
/** 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, max }}
if (key) {return { key: ipRateKey(key), max }}
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
}
@@ -125,10 +220,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,21 +250,25 @@ 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 }
}
/**
@@ -190,7 +295,7 @@ export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5,
/** 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
}