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:
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* The answer of a project's access callback (`cookieScanner.access`, the doctor's `access`), read the same way
|
||||
* everywhere (owner's decision Q4, 1.18.0).
|
||||
*
|
||||
* Today any truthy answer lets the request in, as before: `({ req }) => req.user` returns an account object, and
|
||||
* a function that returns `'no'` or `{}` lets the request in too. From the next minor version only `true` will
|
||||
* allow. Until then the first answer that is not a boolean is reported once per option in the server log, so a
|
||||
* project sees it before the change. (A callback needs a request to be asked, so this cannot be checked at start:
|
||||
* the warning comes with the first call.)
|
||||
*/
|
||||
const warned = new Set<string>()
|
||||
|
||||
export type AccessAnswerOptions = {
|
||||
/** Where to report (default `console.warn`). */
|
||||
warn?: (message: string) => void
|
||||
}
|
||||
|
||||
/** True when the request may pass; warns once per `option` when the answer is not a boolean. */
|
||||
export function accessAllowed(option: string, answer: unknown, { warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean {
|
||||
if (typeof answer !== 'boolean' && !warned.has(option)) {
|
||||
warned.add(option)
|
||||
const kind = answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer === 'object' ? 'an object' : `a ${typeof answer}`
|
||||
warn(
|
||||
`[iapl] ${option} returned ${kind}, not true or false. It is still read as ${answer ? 'allowed' : 'refused'}; from the next minor version only \`true\` allows. Return a boolean, e.g. \`({ req }) => Boolean(req.user)\` (docs/security.md "Access callbacks").`,
|
||||
)
|
||||
}
|
||||
return Boolean(answer)
|
||||
}
|
||||
|
||||
/** For tests: forget which options were reported. */
|
||||
export function resetAccessWarnings(): void {
|
||||
warned.clear()
|
||||
}
|
||||
+118
-13
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -50,9 +50,11 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
|
||||
// the password rule, the closed first-user route).
|
||||
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
|
||||
// 1.17.2: only 'payload' brings Payload's "locked" answer back (it tells which addresses have an account).
|
||||
// 1.18.0: the sign-in rules. `signInLimit: 0` / `'false'` must not read as off; a limit of 0 never refuses.
|
||||
const accounts = bag(options.accounts)
|
||||
if (accounts) {
|
||||
assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])
|
||||
assertBooleanSwitch('accounts.confirmOwnChanges', accounts.confirmOwnChanges)
|
||||
assertSwitchOrObject('accounts.signInLimit', accounts.signInLimit, { allowTrue: false })
|
||||
const limit = bag(accounts.signInLimit)
|
||||
@@ -78,6 +80,12 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
assertSwitchOrObject(name, options[name])
|
||||
}
|
||||
assertBooleanSwitch('indexNow', options.indexNow)
|
||||
// 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions)
|
||||
assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin)
|
||||
const adminSameOrigin = bag(options.adminSameOrigin)
|
||||
if (adminSameOrigin && adminSameOrigin.origins !== undefined && !(Array.isArray(adminSameOrigin.origins) && adminSameOrigin.origins.every((o) => typeof o === 'string'))) {
|
||||
throw new Error(`${where('adminSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(adminSameOrigin.origins)}).`)
|
||||
}
|
||||
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
|
||||
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
|
||||
assertBooleanSwitch('lightbox', options.lightbox)
|
||||
|
||||
Reference in New Issue
Block a user