2FA verify limit: a right code gives its place back; exempt by an admin-only field, not e-mail (docs)

The verify limit took a place for every attempt and kept it, so the sixth
correct login of one account within 10 minutes was refused (IAWL idea 27).
Now an attempt takes its place before the compare (a parallel burst still
cannot slip under the limit), a right code gives it back, an attempt refused
without a compare gives it back at once, and a new attempt held out only by
attempts still being checked gets 429 + Retry-After: 2 "try again in a
moment". buildVerifyLimit returns limit.settle(req, correct); the plugin's
guard calls it with the package's answer. No schema change: payload-kv keeps
{ count, resetAt }.

Docs: the exempt example keyed on e-mail, which every account may change
itself (shown over REST and GraphQL): now an admin-only checkbox, with a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 20:15:51 +01:00
co-authored by Claude Opus 5.5
parent e821d52d19
commit 91770ec17f
15 changed files with 384 additions and 25 deletions
+2
View File
@@ -9,6 +9,7 @@ export const securityTexts = defineTexts({
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorBusy: 'Another code for this account is being checked right now. Try again in a moment.',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
@@ -33,6 +34,7 @@ export const securityTexts = defineTexts({
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorBusy: 'Właśnie sprawdzamy inny kod dla tego konta. Spróbuj ponownie za chwilę.',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
+15
View File
@@ -382,6 +382,11 @@ export type TotpEndpointGuards = {
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
/**
* Called after a verify attempt that `limitVerify` let through: `correct` is true when the package
* answered `{ ok: true }`. The plugin's limit gives a right code's place back (buildVerifyLimit `settle`).
*/
settleVerify?: (req: never, correct: boolean) => Promise<void> | void
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
onSetupClosed?: (req: never) => Response
/**
@@ -413,6 +418,16 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
const limited = await guards.limitVerify(req as never)
if (limited) {return limited}
if (guards.settleVerify) {
let correct = false
try {
const res = await handler(req)
correct = res.status === 200 && ((await res.clone().json().catch(() => null)) as { ok?: unknown } | null)?.ok === true
return res
} finally {
await guards.settleVerify(req as never, correct)
}
}
}
return handler(req)
}) as unknown as T['handler'],
+85 -7
View File
@@ -8,10 +8,16 @@ import { serverText } from '../../integrations/texts.js'
* answers in a million, so whoever holds the password could simply try.
*
* Counted per ACCOUNT, not per IP (an attacker changes addresses; the account
* is what is being guessed). Every attempt counts, right or wrong — nobody
* needs more than a handful of logins in the window. Only a session that
* already passed the password reaches the endpoint, so someone without the
* password cannot use the limit to lock an account's owner out.
* is what is being guessed). An attempt takes its place BEFORE the code is
* compared (a burst of parallel guesses cannot slip under the limit), and gives
* it back when the code was right (`settle`): only wrong codes stay counted.
* Since 1.17.1 — before, every attempt stayed counted, so the sixth correct
* login of one account in the window (an office sharing a login, several devices)
* was refused. A place taken by an attempt still being checked refuses a new one
* with "try again in a moment" (`Retry-After: 2`), not with the long wait; an
* attempt never settled counts as wrong. Only a session that already passed the
* password reaches the endpoint, so someone without the password cannot use the
* limit to lock an account's owner out.
*
* Counted twice, and the higher count decides:
* - **in memory**, per server instance — exact also for a burst of parallel requests
@@ -44,10 +50,31 @@ export type VerifyLimitOptions = {
type Bucket = { count: number; resetAt: number }
const buckets = new Map<string, Bucket>()
/** Attempts let through and not settled yet, per bucket key: when each started. Older than IN_FLIGHT_MS = wrong. */
const inFlight = new Map<string, number[]>()
/** An attempt that has not said how it ended after this long counts as a wrong code. */
const IN_FLIGHT_MS = 30_000
/** Who took which place, so that `settle` gives back exactly that one. */
type Place = { collection: string; id: string; key: string; keyPrefix: string; startedAt: number; stored: boolean }
const pending = new WeakMap<object, Place>()
/** For tests. */
export function clearVerifyLimits(): void {
buckets.clear()
inFlight.clear()
}
const youngInFlight = (key: string, now: number): number[] => {
const kept = (inFlight.get(key) ?? []).filter((at) => now - at < IN_FLIGHT_MS)
if (kept.length) {inFlight.set(key, kept)} else {inFlight.delete(key)}
return kept
}
const dropInFlight = (key: string, startedAt: number): void => {
const list = inFlight.get(key)
if (!list) {return}
const i = list.indexOf(startedAt)
if (i >= 0) {list.splice(i, 1)}
if (!list.length) {inFlight.delete(key)}
}
type KV = { get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
@@ -75,13 +102,47 @@ async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) =
}
}
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) {
/** Takes one counted attempt back, in memory and in the database (a right code, or an attempt that was refused without a compare). */
async function giveBack(payload: { kv?: unknown }, place: Place, now: number): Promise<void> {
const bucket = buckets.get(place.key)
if (bucket && bucket.resetAt > now && bucket.count > 0) {bucket.count -= 1}
if (!place.stored) {return}
const kv = payload.kv as KV | undefined
if (typeof kv?.get !== 'function' || typeof kv?.set !== 'function') {return}
try {
const key = verifyLimitKey(place.collection, place.id, place.keyPrefix)
const current = (await kv.get(key)) as Bucket | null
if (current && typeof current.count === 'number' && typeof current.resetAt === 'number' && current.resetAt > now && current.count > 0) {
await kv.set(key, { count: current.count - 1, resetAt: current.resetAt })
}
} catch {
// the place stays taken until the window ends: never more attempts than the limit, only fewer
}
}
/**
* Says how a verify attempt that the limit let through ended. `correct: true` gives its place back
* (only wrong codes stay counted); `false` keeps it. An attempt never settled counts as wrong.
* `guardTotpEndpoint` calls it with the package's answer (`{ ok: true }`); a project that calls
* `buildVerifyLimit` itself calls `limit.settle(req, correct)` after its own check.
*/
export type SettleVerifyAttempt = (req: PayloadRequest, correct: boolean) => Promise<void>
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}): ((req: PayloadRequest) => Promise<null | Response>) & { settle: SettleVerifyAttempt } {
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'
const keyPrefix = typeof options.keyPrefix === 'string' && options.keyPrefix.trim() ? options.keyPrefix.trim() : 'ipal'
return async (req: PayloadRequest): Promise<null | Response> => {
const settle: SettleVerifyAttempt = async (req, correct) => {
const place = pending.get(req as object)
if (!place) {return}
pending.delete(req as object)
dropInFlight(place.key, place.startedAt)
if (correct) {await giveBack(req.payload as never, place, Date.now())}
}
const limit = 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".
@@ -95,6 +156,8 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
}
}
const key = `${collection}:${id}`
// attempts of this account being checked right now (taken before this one's own place)
const busy = youngInFlight(key, now).length
const current = buckets.get(key)
const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs }
bucket.count += 1
@@ -104,7 +167,21 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
// …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, keyPrefix), windowMs, now) : null
const worst = kept && kept.count > mine.count ? kept : mine
if (worst.count <= max) {return null}
const place: Place = { id, collection, key, keyPrefix, startedAt: now, stored: stored && kept !== null }
if (worst.count <= max) {
pending.set(req as object, place)
inFlight.set(key, [...(inFlight.get(key) ?? []), now])
return null
}
// Refused without a compare: this attempt gives its place back at once.
await giveBack(req.payload as never, place, now)
// Full only because of attempts still being checked (six right codes at the same moment): "try again", no long wait.
if (busy > 0 && worst.count - 1 - busy < max) {
return Response.json(
{ message: serverText(req.i18n as never, 'twoFactorBusy'), ok: false },
{ headers: { 'Retry-After': '2' }, status: 429 },
)
}
const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000))
req.payload.logger.warn(`[iapl] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`)
return Response.json(
@@ -112,4 +189,5 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
{ headers: { 'Retry-After': String(retryAfter) }, status: 429 },
)
}
return Object.assign(limit, { settle })
}
+1 -1
View File
@@ -320,7 +320,7 @@ export const iapl = (options: IaplOptions): Plugin => {
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, { ...tf.verifyLimit, keyPrefix: (typeof tf.verifyLimit?.keyPrefix === 'string' && tf.verifyLimit.keyPrefix.trim()) || (options.storageNames === 'iapl' ? 'iapl' : 'ipal') })
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req), settleVerify: (req: PayloadRequest, correct: boolean) => limitVerify.settle(req, correct) } : {}),
...(tf.sameOrigin === false
? {}
: {