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:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent 0b4c4e8295
commit f7296edc71
10 changed files with 318 additions and 13 deletions
+2
View File
@@ -348,6 +348,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { ownOrigins, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
@@ -364,6 +365,7 @@ export {
} from './modules/security/totp/setupRequired.js'
export type { RequireSetupOptions, TwoFactorResetOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from './modules/security/totp/verifyLimit.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
+13
View File
@@ -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',
+62
View File
@@ -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
}
+10
View File
@@ -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)
+48 -5
View File
@@ -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 },
+3
View File
@@ -40,6 +40,7 @@ import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
@@ -273,8 +274,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
...(tf.sameOrigin === false ? {} : { ownOrigin: (req: PayloadRequest) => requestFromOwnOrigin(req as never, extraOrigins) }),
onSetupClosed: (req: PayloadRequest) =>
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
}
+15 -1
View File
@@ -329,6 +329,17 @@ export type IpalOptions = {
* package's views as they are. Run generate:importmap. docs/security.md.
*/
safeBack?: false | SafeBackRule
/**
* 2FA verify and setup attempts (`POST /api/verify-totp`, `/api/setup-totp`)
* are accepted only from the site's own origin: a request that a browser
* marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) is refused
* with 403 and not counted — so another page, a sibling subdomain included,
* cannot burn an account's verify attempts and lock its owner out. Own
* origins: the request's host, `serverURL`, Payload's `csrf` / `cors`
* lists, and `{ origins: ['https://app.example.com'] }` here. Requests
* without those headers (scripts, servers) pass. `false` = off.
*/
sameOrigin?: { origins?: string[] } | false
/**
* Texts of the 2FA screens and user field. Default: ipal-kit's English and
* Polish (`TOTP_TEXTS`), merged over the package's; your own
@@ -340,7 +351,10 @@ export type IpalOptions = {
* 2FA package never counts tries, and a six-digit code can be guessed by
* whoever holds the password. Default `{ max: 5, windowMinutes: 10 }`: the
* sixth attempt in ten minutes, right or wrong, is refused (429) until the
* window ends. `false` = no limit (a limiter in front of the site).
* window ends. The count is kept in memory and in the database (Payload's
* `payload.kv`), so a restart or a second instance does not reset it;
* `{ store: 'memory' }` = this instance only. `false` = no limit (a limiter
* in front of the site).
*/
verifyLimit?: false | VerifyLimitOptions
}