Merge claude/security-a-1172: a locked staff account answers like a wrong password, IPv6 counted per /64, panel actions only from the site's own origin
plugin.ts import conflict: withVersionReadRules (readPublished fix) and withLockedAnswer both kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import type { AfterErrorHook, Config, SanitizedCollectionConfig } from 'payload'
|
||||
|
||||
import { AuthenticationError, formatNames, toWords } from 'payload'
|
||||
|
||||
import { staffCollectionSlugs } from './predicates.js'
|
||||
|
||||
/**
|
||||
* A locked staff account answers its login exactly like a wrong password (`accounts.lockedAnswer`, 1.17.2).
|
||||
*
|
||||
* Payload checks the lock BEFORE the password: after five wrong passwords for `owner@site` any password gets
|
||||
* `401 "This user is locked due to having too many failed login attempts."` (GraphQL: `LockedAuth`), while an
|
||||
* address that has no account always gets `401 "The email or password provided is incorrect."`. Anybody could
|
||||
* tell which addresses have a staff account with no password at all (IAWL idea 6). This hook turns Payload's
|
||||
* `LockedAuth` on a staff collection's login into the `AuthenticationError` answer — same status, same body, same
|
||||
* GraphQL `extensions.name`. The price: the owner, while locked, is told "wrong e-mail or password" too.
|
||||
*
|
||||
* The lock itself is not touched (it still holds for `lockTime`). `accounts: { lockedAnswer: 'payload' }` keeps
|
||||
* Payload's message. The error is recognised by its `name` (`'LockedAuth'`, a string Payload sets — not a function
|
||||
* name, so a minified bundle keeps it) and by the collection: a staff collection only.
|
||||
*/
|
||||
export type LockedAnswerOption = 'payload' | 'wrong'
|
||||
|
||||
const isLocked = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'LockedAuth'
|
||||
|
||||
/** The GraphQL login mutation's name of a collection, as @payloadcms/graphql builds it (`login${singularName}`). */
|
||||
export function graphqlLoginName(collection: Pick<SanitizedCollectionConfig, 'graphQL' | 'slug'>): null | string {
|
||||
const graphQL = collection.graphQL as { singularName?: string } | false | undefined
|
||||
if (graphQL === false) {return null}
|
||||
const singular = graphQL?.singularName ? toWords(graphQL.singularName, true) : formatNames(collection.slug).singular
|
||||
return `login${singular}`
|
||||
}
|
||||
|
||||
type T = ConstructorParameters<typeof AuthenticationError>[0]
|
||||
|
||||
/** The config-level `afterError` hook (REST and GraphQL). */
|
||||
export const lockedLooksWrong: AfterErrorHook = (args) => {
|
||||
const { collection, error, req } = args as { error: unknown; graphqlResult?: Record<string, unknown> } & Parameters<AfterErrorHook>[0]
|
||||
const payload = req?.payload
|
||||
if (!payload) {return}
|
||||
const staff = staffCollectionSlugs(payload)
|
||||
const wrong = new AuthenticationError(req.t as T)
|
||||
// GraphQL: the error is wrapped (`originalError`), the collection only shows in the mutation's name.
|
||||
const graphqlResult = (args as { graphqlResult?: { extensions?: Record<string, unknown>; path?: unknown[] } }).graphqlResult
|
||||
if (graphqlResult) {
|
||||
const original = (error as { originalError?: unknown }).originalError
|
||||
if (!isLocked(original)) {return}
|
||||
const field = Array.isArray(graphqlResult.path) ? graphqlResult.path[0] : undefined
|
||||
const names = new Set((payload.config.collections ?? []).filter((c) => staff.includes(c.slug)).map(graphqlLoginName))
|
||||
if (typeof field !== 'string' || !names.has(field)) {return}
|
||||
return {
|
||||
graphqlResult: {
|
||||
...graphqlResult,
|
||||
extensions: { ...graphqlResult.extensions, name: wrong.name, statusCode: wrong.status },
|
||||
message: wrong.message,
|
||||
},
|
||||
} as never
|
||||
}
|
||||
if (!isLocked(error) || !collection || !staff.includes(collection.slug)) {return}
|
||||
return { response: { errors: [{ message: wrong.message }] }, status: wrong.status } as never
|
||||
}
|
||||
|
||||
/** Adds the hook to a config (idempotent). */
|
||||
export function withLockedAnswer(config: Config): Config {
|
||||
const own = config.hooks?.afterError ?? []
|
||||
if (own.includes(lockedLooksWrong)) {return config}
|
||||
return { ...config, hooks: { ...config.hooks, afterError: [...own, lockedLooksWrong] } }
|
||||
}
|
||||
@@ -49,6 +49,13 @@ export type AccountsOptions = {
|
||||
* whose own `create` rule allows an anonymous request keeps its route.
|
||||
*/
|
||||
firstUserRoute?: 'all' | 'panel' | string[]
|
||||
/**
|
||||
* What a staff account that Payload has locked (too many wrong passwords) is told when it logs in.
|
||||
* Default (1.17.2): exactly what a wrong password gets — same status, message and GraphQL error name — so
|
||||
* nobody can find out which addresses have a staff account by locking them. The lock itself is unchanged.
|
||||
* `'wrong'` = the default, said out loud. `'payload'` = Payload's own "This user is locked due to having too many failed login attempts."
|
||||
*/
|
||||
lockedAnswer?: 'payload' | 'wrong'
|
||||
/**
|
||||
* The lowest role that may open the admin panel. Default `'editor'`: an
|
||||
* account that holds only `user` (the default role of a new account) sees
|
||||
|
||||
@@ -202,11 +202,19 @@ export const securityRules: DoctorRule[] = [
|
||||
{
|
||||
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
|
||||
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
|
||||
// The plugin's own-origin checks (2FA verify / setup / reset, the panel actions — 1.17.2) then know the site
|
||||
// only from the request's Host: behind a proxy that rewrites it, the site's own panel would be refused.
|
||||
id: 'csrf-empty',
|
||||
check: (ctx) => {
|
||||
const fix = "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only; the plugin's own-origin checks know the site's address), or csrf: ['https://<site>']"
|
||||
const why = 'Payload accepts the login cookie from any origin (a risk when other applications share the domain), and behind a proxy that rewrites Host the plugin cannot tell the panel\'s own requests (2FA, panel actions) from foreign ones'
|
||||
// deep (the running config) wins over reading the file: serverURL may come from a spread or a helper
|
||||
if (ctx.deep && typeof ctx.deep.originKnown === 'boolean') {
|
||||
return ctx.deep.originKnown ? [] : [{ fix, message: `the running config has neither \`serverURL\` nor \`csrf\`: ${why}`, severity: 'warning' }]
|
||||
}
|
||||
const code = cfg(ctx)
|
||||
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
|
||||
@@ -111,7 +111,9 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
} catch {
|
||||
staffOnOwnRoles = null
|
||||
}
|
||||
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -99,6 +99,11 @@ export type DoctorStatus = {
|
||||
node?: string
|
||||
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
|
||||
openSignUp?: null | string[]
|
||||
/**
|
||||
* The running config has a `serverURL` (1.17.2), or a non-empty `csrf` list. Without either Payload takes the
|
||||
* login cookie from any origin, and the plugin's own-origin checks know the site only from the request's host.
|
||||
*/
|
||||
originKnown?: boolean
|
||||
pendingCookies?: null | number
|
||||
plugin?: string
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
@@ -136,7 +136,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
|
||||
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
|
||||
const checks = [
|
||||
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
|
||||
]
|
||||
for (const check of checks) {
|
||||
|
||||
@@ -3,9 +3,11 @@ export {
|
||||
checkRateLimit,
|
||||
clientIp,
|
||||
consumeRateLimit,
|
||||
ipRateKey,
|
||||
retryAfterSeconds,
|
||||
setIpv6Grouping,
|
||||
setRateLimitStore,
|
||||
setUnknownIpFactor,
|
||||
tooManyRequests,
|
||||
} from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, Ipv6Grouping, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Config, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { COOKIE_APPROVAL_PATH } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_CRAWL_PATH } from '../consent/scanner/crawl/config.js'
|
||||
import { COOKIE_SCAN_PATH } from '../consent/scanner/endpoint.js'
|
||||
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH } from '../email/relay/constants.js'
|
||||
import { reportRefusedOrigin, requestFromOwnOrigin } from './totp/sameOrigin.js'
|
||||
|
||||
/**
|
||||
* The plugin's panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2; IAWL idea 7, owner's Q6).
|
||||
*
|
||||
* These endpoints act with the panel's login cookie and read a body whatever its `Content-Type` says — a
|
||||
* `text/plain` POST, which another origin can send without a CORS preflight. A page on a sibling subdomain is
|
||||
* "same site", so the browser sends the `SameSite=Lax` cookie along, and Payload's own CSRF list is empty unless
|
||||
* `serverURL` or `csrf` is set. Such a page could make a signed-in administrator disconnect the mail service,
|
||||
* connect it again, send test mails, run cookie scans and crawls, or approve every waiting cookie. The rule is the
|
||||
* one 2FA verify / setup / reset use (sameOrigin.ts): a request the browser marks as coming from elsewhere
|
||||
* (`Origin`, else `Sec-Fetch-Site`) gets `403` before anything is read; a request with neither header (a script,
|
||||
* `curl`) passes — it rides on nobody's cookie. Refusals are logged once per origin with the ways to allow it.
|
||||
*/
|
||||
export type AdminSameOriginOption = {
|
||||
/** More origins that may call these endpoints (a panel on another domain). */
|
||||
origins?: string[]
|
||||
} | boolean
|
||||
|
||||
/** The panel actions the rule covers: method and path (relative to the API route). */
|
||||
export const ADMIN_POST_ENDPOINTS: ReadonlyArray<readonly ['post', string]> = [
|
||||
['post', RELAY_CONNECT_PATH],
|
||||
['post', RELAY_DISCONNECT_PATH],
|
||||
['post', '/ipal/test-email'],
|
||||
['post', COOKIE_SCAN_PATH],
|
||||
['post', COOKIE_APPROVAL_PATH],
|
||||
['post', COOKIE_CRAWL_PATH],
|
||||
]
|
||||
|
||||
const ADMIN_REFUSAL = {
|
||||
docs: 'docs/security.md "Panel actions only from the site\'s own origin"',
|
||||
option: 'iapl({ adminSameOrigin',
|
||||
what: 'a panel action',
|
||||
}
|
||||
|
||||
const covered = (endpoint: Pick<Endpoint, 'method' | 'path'>): boolean =>
|
||||
ADMIN_POST_ENDPOINTS.some(([method, path]) => endpoint.method === method && endpoint.path === path)
|
||||
|
||||
/** Wraps one endpoint: `403` for a request from another origin, the endpoint's own answer otherwise. */
|
||||
export function requireOwnOrigin<T extends Pick<Endpoint, 'handler'>>(endpoint: T, origins: string[] = []): T {
|
||||
const handler = endpoint.handler as (req: PayloadRequest) => Promise<Response> | Response
|
||||
return {
|
||||
...endpoint,
|
||||
handler: (async (req: PayloadRequest) => {
|
||||
if (!requestFromOwnOrigin(req as never, origins)) {
|
||||
reportRefusedOrigin(req as never, origins, ADMIN_REFUSAL)
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
return handler(req)
|
||||
}) as T['handler'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the rule to the covered endpoints the plugin added (`ownEndpoints`: those not in the project's config
|
||||
* before iapl ran) — a project's own endpoint on the same path is left as it is.
|
||||
*/
|
||||
export function guardAdminEndpoints(config: Config, before: ReadonlySet<unknown>, option: AdminSameOriginOption | undefined): Config {
|
||||
if (option === false) {return config}
|
||||
const origins = typeof option === 'object' ? (option.origins ?? []) : []
|
||||
return {
|
||||
...config,
|
||||
endpoints: (config.endpoints ?? []).map((e) => (!before.has(e) && covered(e) ? requireOwnOrigin(e, origins) : e)),
|
||||
}
|
||||
}
|
||||
@@ -89,21 +89,29 @@ const MAX_REPORTED = 50
|
||||
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
|
||||
* enter and a silent log. Returns true when a line was written.
|
||||
*/
|
||||
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
|
||||
/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */
|
||||
export type RefusalContext = { docs: string; option: string; what: string }
|
||||
const TWO_FACTOR_REFUSAL: RefusalContext = {
|
||||
docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"',
|
||||
option: 'twoFactor: { sameOrigin',
|
||||
what: '2FA: a code',
|
||||
}
|
||||
|
||||
export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean {
|
||||
const origin = req.headers?.get('origin')
|
||||
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
|
||||
const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}`
|
||||
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
|
||||
reported.add(key)
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
|
||||
const how = originOf(origin)
|
||||
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
|
||||
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
`or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
: 'The browser did not name an origin this site knows. '
|
||||
req.payload?.logger?.warn(
|
||||
`[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
|
||||
`[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` +
|
||||
how +
|
||||
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
|
||||
`If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`,
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
+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,26 +250,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
|
||||
}
|
||||
|
||||
|
||||
@@ -50,12 +50,21 @@ 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).
|
||||
const accounts = bag(options.accounts)
|
||||
if (accounts) {assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])}
|
||||
|
||||
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
|
||||
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
|
||||
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