M1 (8): 2FA attempts only from the own origin; the verify count is stored
R3-2. (b) POST /api/verify-totp and /api/setup-totp refuse a request that a browser marks as coming from another origin (Origin, Sec-Fetch-Site) — before it is counted, so another page (a sibling subdomain included) cannot burn an account's attempts and lock its owner out. Own origins: the request's host, serverURL, Payload's csrf / cors lists, twoFactor.sameOrigin.origins; requests without those headers pass. twoFactor.sameOrigin: false turns it off. (a) The verify count is kept in memory (exact for parallel bursts) and in Payload's key-value store (payload.kv, no new collection), so a restart or a second instance does not reset it; the higher count decides, and a failing store never opens the gate. verifyLimit.store: 'memory' = this instance only. Doctor: csrf-empty (static, warning) when neither serverURL nor csrf is set. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0b4c4e8295
commit
f7296edc71
@@ -157,6 +157,19 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// 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.
|
||||
id: 'csrf-empty',
|
||||
check: (ctx) => {
|
||||
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' }]
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
|
||||
id: 'open-signup',
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 2FA verify and setup attempts only from the site's own origin.
|
||||
*
|
||||
* The verify limit counts every attempt of an account. A page on another origin that the
|
||||
* browser still sends the login cookie to — a sibling subdomain is "same site", so
|
||||
* `SameSite=Lax` does not stop it, and Payload's own `csrf` list is empty unless `serverURL`
|
||||
* or `csrf` is set — could post wrong codes in the owner's name: no password needed, the
|
||||
* owner's five attempts burnt, the owner locked out for the window. So a request that a
|
||||
* browser marks as coming from elsewhere is refused BEFORE it is counted.
|
||||
*
|
||||
* What counts as the site's own origin: the host the request came in on (`Host`,
|
||||
* `X-Forwarded-Host`, the request URL), `serverURL`, Payload's `csrf` and `cors` lists, and
|
||||
* `twoFactor.sameOrigin.origins`. A request with neither `Origin` nor `Sec-Fetch-Site` is not
|
||||
* a browser's cross-site request (a script, `curl`, a server) and passes: it cannot ride on
|
||||
* somebody's cookie.
|
||||
*/
|
||||
type RequestLike = { headers?: { get(name: string): null | string }; payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown } }; url?: null | string }
|
||||
|
||||
const originOf = (value: unknown): null | string => {
|
||||
if (typeof value !== 'string' || !value) {return null}
|
||||
try {
|
||||
return new URL(value).origin
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Origins and hosts this request may come from. */
|
||||
export function ownOrigins(req: RequestLike, extra: string[] = []): { hosts: Set<string>; origins: Set<string> } {
|
||||
const config = req.payload?.config
|
||||
const cors = config?.cors
|
||||
const listed = [
|
||||
config?.serverURL,
|
||||
...(Array.isArray(config?.csrf) ? (config.csrf as unknown[]) : []),
|
||||
...(Array.isArray(cors) ? (cors as unknown[]) : Array.isArray((cors as { origins?: unknown } | undefined)?.origins) ? ((cors as { origins: unknown[] }).origins) : []),
|
||||
...extra,
|
||||
]
|
||||
const origins = new Set(listed.map(originOf).filter((o): o is string => o !== null))
|
||||
const hosts = new Set<string>()
|
||||
for (const name of ['host', 'x-forwarded-host']) {
|
||||
// a proxy may list several; the first is the one the browser asked for
|
||||
const value = req.headers?.get(name)?.split(',')[0]?.trim().toLowerCase()
|
||||
if (value) {hosts.add(value)}
|
||||
}
|
||||
const fromUrl = originOf(req.url)
|
||||
if (fromUrl) {hosts.add(new URL(fromUrl).host)}
|
||||
return { hosts, origins }
|
||||
}
|
||||
|
||||
/** False when a browser says the request comes from another origin (see the top of the file). */
|
||||
export function requestFromOwnOrigin(req: RequestLike, extra: string[] = []): boolean {
|
||||
const origin = req.headers?.get('origin')
|
||||
if (origin) {
|
||||
const parsed = originOf(origin)
|
||||
if (!parsed) {return false} // "null" (a sandboxed page, a redirect chain) or garbage
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
return origins.has(parsed) || hosts.has(new URL(parsed).host.toLowerCase())
|
||||
}
|
||||
const site = req.headers?.get('sec-fetch-site')
|
||||
if (site) {return site === 'same-origin' || site === 'none'}
|
||||
return true
|
||||
}
|
||||
@@ -380,6 +380,11 @@ export type TotpEndpointGuards = {
|
||||
limitVerify?: (req: never) => null | Promise<null | Response> | Response
|
||||
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
|
||||
onSetupClosed?: (req: never) => Response
|
||||
/**
|
||||
* Whether a verify / setup attempt may come from where the browser says it comes from
|
||||
* (sameOrigin.ts). False = refused, and NOT counted against the verify limit.
|
||||
*/
|
||||
ownOrigin?: (req: never) => boolean
|
||||
}
|
||||
|
||||
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
|
||||
@@ -395,6 +400,11 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
|
||||
if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') {
|
||||
return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused()
|
||||
}
|
||||
// An attempt a browser marks as coming from another origin is refused before it is counted:
|
||||
// otherwise another page could burn the owner's attempts and lock them out, without the password.
|
||||
if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) {
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
// The code has about three right answers in a million and the package never counts tries.
|
||||
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
|
||||
const limited = await guards.limitVerify(req as never)
|
||||
|
||||
@@ -13,12 +13,24 @@ import { serverText } from '../../integrations/texts.js'
|
||||
* already passed the password reaches the endpoint, so someone without the
|
||||
* password cannot use the limit to lock an account's owner out.
|
||||
*
|
||||
* In memory, per server instance, and always enforced (no "allow when the
|
||||
* store fails" path): with several instances the limit is per instance.
|
||||
* Counted twice, and the higher count decides:
|
||||
* - **in memory**, per server instance — exact also for a burst of parallel requests
|
||||
* (the count is taken before anything is awaited);
|
||||
* - **in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
|
||||
* collection Payload itself adds; no new collection, no migration of ours), so the count
|
||||
* survives a restart or redeploy and is shared between instances. `store: 'memory'`
|
||||
* leaves this part out.
|
||||
* Always enforced: when the database part fails, the memory count still decides — there is
|
||||
* no "allow when the store fails" path. Two instances can each let a few attempts through
|
||||
* before the other's write lands; the bound is then "max per instance", never "no limit".
|
||||
*
|
||||
* Requests a browser marks as coming from another origin never get here (sameOrigin.ts).
|
||||
*/
|
||||
export type VerifyLimitOptions = {
|
||||
/** Attempts per account in the window. Default 5. */
|
||||
max?: number
|
||||
/** Where the count is kept besides the instance's memory. Default `'database'`; `'memory'` = this instance only. */
|
||||
store?: 'database' | 'memory'
|
||||
/** Window in minutes; a refused account waits until it ends. Default 10. */
|
||||
windowMinutes?: number
|
||||
}
|
||||
@@ -31,11 +43,37 @@ export function clearVerifyLimits(): void {
|
||||
buckets.clear()
|
||||
}
|
||||
|
||||
type KV = { get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
let warnedStore = false
|
||||
|
||||
/** Key of an account's stored count in `payload.kv`. */
|
||||
export const verifyLimitKey = (collection: string, id: string) => `ipal:2fa-verify:${collection}:${id}`
|
||||
|
||||
/** Counts one attempt in the database and returns the stored bucket; null when there is no store or it fails. */
|
||||
async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) => void } }, key: string, windowMs: number, now: number): Promise<Bucket | null> {
|
||||
const kv = payload.kv as KV | undefined
|
||||
if (typeof kv?.get !== 'function' || typeof kv?.set !== 'function') {return null}
|
||||
try {
|
||||
const current = (await kv.get(key)) as Bucket | null
|
||||
const valid = current && typeof current.count === 'number' && typeof current.resetAt === 'number' && current.resetAt > now
|
||||
const next: Bucket = valid ? { count: current.count + 1, resetAt: current.resetAt } : { count: 1, resetAt: now + windowMs }
|
||||
await kv.set(key, next)
|
||||
return next
|
||||
} catch (err) {
|
||||
if (!warnedStore) {
|
||||
warnedStore = true
|
||||
payload.logger?.warn(`[ipal] 2FA: the verify limit could not be stored (${err instanceof Error ? err.message : String(err)}); counting in memory only.`)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) {
|
||||
const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5
|
||||
const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000
|
||||
const stored = options.store !== 'memory'
|
||||
|
||||
return (req: PayloadRequest): null | Response => {
|
||||
return async (req: PayloadRequest): Promise<null | Response> => {
|
||||
// No session: the package refuses by itself, and there is no account to count against.
|
||||
if (!req.user) {return null}
|
||||
// Whatever the id looks like, it is one bucket per value — never "no limit".
|
||||
@@ -53,8 +91,13 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
|
||||
const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs }
|
||||
bucket.count += 1
|
||||
buckets.set(key, bucket)
|
||||
if (bucket.count <= max) {return null}
|
||||
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))
|
||||
// This attempt's own number, taken now: the bucket is shared and keeps growing while we wait below.
|
||||
const mine: Bucket = { count: bucket.count, resetAt: bucket.resetAt }
|
||||
// …and in the database, so a restart or another instance does not start from zero. The higher count decides.
|
||||
const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id), windowMs, now) : null
|
||||
const worst = kept && kept.count > mine.count ? kept : mine
|
||||
if (worst.count <= max) {return null}
|
||||
const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000))
|
||||
req.payload.logger.warn(`[ipal] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`)
|
||||
return Response.json(
|
||||
{ message: serverText(req.i18n as never, 'twoFactorTooManyAttempts', { minutes: Math.ceil(retryAfter / 60) }), ok: false },
|
||||
|
||||
Reference in New Issue
Block a user