import type { PayloadRequest } from 'payload' import { serverText } from '../../integrations/texts.js' /** * A limit on TOTP verify attempts. The 2FA package checks the code and never * counts tries: a six-digit code with a ±1 step window has about three right * 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. * * In memory, per server instance, and always enforced (no "allow when the * store fails" path): with several instances the limit is per instance. */ export type VerifyLimitOptions = { /** Attempts per account in the window. Default 5. */ max?: number /** Window in minutes; a refused account waits until it ends. Default 10. */ windowMinutes?: number } type Bucket = { count: number; resetAt: number } const buckets = new Map() /** For tests. */ export function clearVerifyLimits(): void { buckets.clear() } 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 return (req: PayloadRequest): 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". const raw = (req.user as { id?: unknown }).id const id = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : JSON.stringify(raw ?? null) const now = Date.now() // keep the map small: forget windows that are over if (buckets.size > 5000) { for (const [key, bucket] of buckets) { if (bucket.resetAt <= now) {buckets.delete(key)} } } const key = `${collection}:${id}` const current = buckets.get(key) 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)) 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 }, { headers: { 'Retry-After': String(retryAfter) }, status: 429 }, ) } }