Files
Kelx/utils/login-throttle.js
2026-11-30 16:32:37 +00:00

493 lines
30 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
const crypto = require("node:crypto");
const { resolveClampedInt } = require("./clamped-int");
// adpanel:login-request-limit — GET and POST /login are pre-auth surfaces
// (session writes, CSRF/bot-proof minting, DB-backed lookups) that nothing
// else throttles by default, so they take an always-on per-source request
// budget that runs BEFORE the handlers: a blocked request writes no session
// and consumes no CSRF token. Keyed by the bucketed IP (ipKeyGenerator,
// IPv6 /56) so one host cannot mint fresh buckets, and satisfied by
// express-rate-limit's ERR_ERL_KEY_GEN_IPV6 source check. This is an abuse
// brake, not an auth control, so store errors fail open
// (passOnStoreError) and trusted subnets are NOT exempted. Trade-off:
// many users behind one NAT share a single budget; adjust via
// LOGIN_REQUEST_RATE_LIMIT_PER_MIN.
// adpanel:env-int-clamp — every env knob below resolves through the ONE
// shared clamped-int helper (floor policy, the helper's default): a parsed
// "0" or negative is nonsense for a budget/window/count and clamps to the
// documented floor — it can never disable a control.
// adpanel:login-rate-limit-shape — ONE content negotiation for the whole
// login surface. wantsJsonLoginResponse is the single JSON-wants predicate
// consumed by BOTH the 429 responder below and the POST /login handler's
// error/success bodies, so a client cannot get JSON from one login response
// and plain text from another. It is the superset of the historical legs
// (Accept: application/json OR X-Requested-With: XMLHttpRequest OR
// Content-Type: application/json) — before the unification the Content-Type
// leg existed only in the handler's inline copy, so a client POSTing JSON
// with no Accept header got JSON from handler errors but text from limiter
// 429s. The shipped login.ejs fetch always sends Accept AND
// X-Requested-With (with a form-urlencoded Content-Type), so browser
// behavior at the UI level is unchanged.
function wantsJsonLoginResponse(request) {
return String(request.get("accept") || "").includes("application/json")
|| String(request.get("content-type") || "").includes("application/json")
|| String(request.get("x-requested-with") || "") === "XMLHttpRequest";
}
// adpanel:login-retry-after — the always-on request limiter's fixed window
// (60 s). The responder's fallback Retry-After and the limiter handler's
// explicit value both derive from this ONE constant so they cannot drift.
const LOGIN_REQUEST_LIMIT_WINDOW_SECONDS = 60;
// adpanel:login-retry-after — every login-surface 429 carries an advisory
// Retry-After. Every budget on this surface is a FIXED-WINDOW counter (the
// window opens at the first hit and its start is not stored), so the exact
// remaining seconds are unknowable without persisting new counter state; a
// full-window value is the standard fixed-window approximation (RFC 9110
// delay-seconds; the header is advisory — an attacker can probe it, a
// legitimate client merely backs off for at most one window). This maps a
// refusal reason to the window of the budget that refused: "source" → the
// per-source failure window, "account" → the per-account failure window,
// "totp" → the TOTP window. The reservation's "store" reason (and any
// unknown reason) refuses because the shared store read failed — no budget
// window exists — so it carries the LARGER of the two failure windows as a
// fixed advisory upper bound, keeping every 429 on the surface uniform.
function loginRetryAfterSeconds(config, reason) {
const sourceSec = Math.ceil(Number(config?.ip?.windowMs || 0) / 1000);
const accountSec = Math.ceil(Number(config?.account?.windowMs || 0) / 1000);
if (reason === "source" && sourceSec > 0) return sourceSec;
if (reason === "account" && accountSec > 0) return accountSec;
if (reason === "totp" && Number(config?.totpSource?.windowMs) > 0) {
return Math.ceil(Number(config.totpSource.windowMs) / 1000);
}
const upperBound = Math.max(sourceSec, accountSec);
return upperBound > 0 ? upperBound : LOGIN_REQUEST_LIMIT_WINDOW_SECONDS;
}
// adpanel:login-rate-limit-shape — ONE content-negotiated 429 responder for
// every login-surface rate-limit refusal (the always-on request limiter and
// the attack detector's per-IP refusal): fetch clients get JSON the login
// page's fetch handler can toast (it parses non-JSON bodies to {} and falls
// back to the misleading "Invalid credentials"), browsers get plain text,
// and every response carries Cache-Control: no-store. Both refusal sites
// must route through this helper — divergent 429 shapes on the same surface
// are exactly the copy-drift AGENTS.md forbids.
// adpanel:login-retry-after — the Retry-After header also lives HERE so no
// login-surface 429 can ship without it. Callers pass their own fixed
// window (the request limiter its 60 s budget, the attack detector its
// LOGIN_ATTACK_IP_WINDOW_MS brake — the detector derives the header's
// seconds from that constant, so it tracks an env-tuned window); an omitted
// or unusable value falls back to the limiter's window — this responder's
// original caller — so a future caller can never regress to a headerless
// 429 by forgetting the argument.
function sendLoginRateLimited(request, response, securityLog, reason, retryAfterSeconds = LOGIN_REQUEST_LIMIT_WINDOW_SECONDS) {
if (typeof securityLog === "function") securityLog(reason, request);
response.setHeader("Cache-Control", "no-store");
const retryAfter = Number.isFinite(Number(retryAfterSeconds)) && Number(retryAfterSeconds) > 0
? Math.ceil(Number(retryAfterSeconds))
: LOGIN_REQUEST_LIMIT_WINDOW_SECONDS;
response.setHeader("Retry-After", String(retryAfter));
if (wantsJsonLoginResponse(request)) return response.status(429).json({ ok: false, error: "Too many requests. Try again later." });
return response.status(429).type("text/plain").send("Too many requests. Try again later.");
}
function createLoginRequestLimiter({ rateLimit, buildStore, ipKeyGenerator, getRequestIp, securityLog, env = process.env }) {
const windowMs = LOGIN_REQUEST_LIMIT_WINDOW_SECONDS * 1000;
const max = resolveClampedInt(env, "LOGIN_REQUEST_RATE_LIMIT_PER_MIN", { fallback: 60, min: 10, max: 10000 });
return rateLimit({
windowMs,
max,
standardHeaders: true,
legacyHeaders: false,
store: buildStore ? buildStore("login-req:", windowMs) : undefined,
passOnStoreError: true, // abuse brake, not an auth control
keyGenerator: (request) => `login-req:${ipKeyGenerator(String(getRequestIp(request) || "unknown"))}`,
handler: (request, response) => {
// adpanel:login-rate-limit-shape — the body/negotiation/no-store live in
// the ONE shared responder so the attack detector's 429 cannot drift.
// adpanel:login-retry-after — the limiter's own fixed window is the
// honest Retry-After (full-window approximation, see the responder).
sendLoginRateLimited(request, response, securityLog, "Login request rate limit exceeded", LOGIN_REQUEST_LIMIT_WINDOW_SECONDS);
},
});
}
// adpanel:login-failure-throttle — online password guessing is bounded per
// source AND per account. Counters live in the shared Redis rate-limit store
// (one store instance + distinct prefix per counter) so every PM2 worker sees
// the same totals; without Redis the express-rate-limit MemoryStore is the
// fallback. Only credential failures count, and success never resets the
// source/account counters: reset-on-success let anyone holding one valid
// account wipe their source's budget between guesses. IPv6 sources are
// bucketed (/56) so one host cannot mint fresh buckets. Store errors fail
// open: Redis down means the session store is down, so no login completes.
// Trade-offs: the account counter lets an attacker lock an account's password
// login for up to one window (20 failures). One source bucket can hold at
// most LOGIN_IP_MAX_FAILURES STANDING failures per its own window — the
// reserve-then-finalize/refund reservation (adpanel:login-bcrypt-admission
// below) refunds every over-max admission before any compare runs — so a
// single-host burst can no longer land more than source-max failures into
// the account budget (the pre-fix read-then-arm record let one bucket land
// 60 in seconds): filling the 20-failure account budget inside one account
// window needs at least 2 IP buckets probing in parallel, or one bucket
// sustaining probing across >= 2 of its own windows (~10 minutes). Audit-
// quantified lockout ceiling of the restored property (at the default
// budgets): a single /64 VPS sits inside ONE /56 → one bucket, so its
// sustained probing yields a ~50% DUTY-CYCLE lock, not a continuous one —
// the source budget (10 per 10 min) versus the account budget (20 per
// 15 min) means one source can hold the account blocked roughly half the
// time; an INDEFINITE lockout requires >= 2 /56 allocations or 2+ hosts
// probing in parallel. Variant addressing does not hand the attacker a
// cheaper path: `+tag` email variants (victim+tag@…) do NOT hit the
// victim's account budget at all — they fold to a DISTINCT bucket and never
// resolve to the victim's row (so no id key either) — correcting an earlier
// reviewer claim that they did; Unicode/accent variants DO hit it, because
// the DB collation resolves them to the victim's row and the post-lookup id
// layer enforces there (adpanel:account-throttle-collation-parity below).
// Users holding a valid remember-me cookie never reach /login, so they are
// not affected; NATed offices share the per-source budget.
// adpanel:account-throttle-collation-parity — the per-account budget must be
// enforced on an identity the DB collation cannot diverge from. The account
// lookup matches on `WHERE LOWER(email) = LOWER(?)` over a utf8mb4_unicode_ci
// column (live-verified against the production MySQL with the app's own
// mysql2 driver), so Unicode variants of one address — fullwidth
// victim@example.com, jose@… vs a stored josé@…, strasse@… vs a stored
// straße@… — MATCH the victim's row but keyed to DISTINCT
// sha256(trim().toLowerCase()) buckets: every variant minted a fresh
// 20-failure budget and the aggregate per-account spray control did not bind.
// Two layers close it:
// 1. foldAccountEmail — NFKC → NFD → strip \p{M} marks (Mn+Mc+Me, not
// just Mn — the broader class is load-bearing: the documented
// Devanagari over-merge below folds only because U+093F is Mc) →
// toLowerCase → ß/ẞ → "ss" → trim: the cheap JS-side approximation of
// the collation, applied inside hashAccount to every pre-lookup key
// (no DB round-trip). Live probe: the fullwidth, accent, eszett and
// ligature classes all fold into one bucket, agreeing with the
// collation's equality facts.
// 2. The resolved user id — sha256("acct-id:" + user.id) — the POST-lookup
// enforcement key (accountIdKey below): an identity no collation can
// reinterpret. JS folding is only an approximation of
// utf8mb4_unicode_ci (a MySQL UCA change could re-split classes), and
// it approximates in BOTH directions (live-probed on the production
// 8.0.46). Agreement: the ß → "ss" mapping matches the collation —
// ß=ss compares equal under utf8mb4_unicode_ci (verified live) — so
// the earlier note here that called the eszett fold an over-collision
// was wrong for ß. ẞ is id-enforced too — and on the WIRE, not via
// LOWER: both producers of the lookup input (POST /login and the
// captcha-completion path) JS-lowercase the submitted email (ẞ → ß)
// BEFORE the DB query, so the `?` side of the app's
// LOWER(email) = LOWER(?) shape can never carry U+1E9E — the DB sees
// the wire-transformed ß form, which resolves the row (live-verified
// on the production 8.0.46 utf8mb4_unicode_ci). The SQL-isolated fact
// that LOWER leaves U+1E9E unchanged on both sides is true in
// isolation but unreachable on the wire — an earlier residual
// paragraph here leaned on it to claim a ẞ probe resolves no ß/ss
// row; a data-flow trace proved that false, and a capital-ẞ probe is
// ID-ENFORCED (safer than documented). What survives of the ẞ
// residual is the fold-bucket over-fill in the residual direction
// below only: the fold's toLowerCase maps ẞ onto the ß/ss bucket, so
// a ẞ probe fills the account's shared fold bucket — the documented
// one-window lockout direction — while the resolved row's id key is
// enforced normally.
// Fold-miss (the SAFE direction): the collation equates ς=σ (final
// sigma; lunate ϲ NFKC-maps onto ς and shares its fold bucket) and
// œ=oe (verified live) while the fold keeps ς and œ distinct, so those
// variant probes resolve to the row and spend the id-key budget — any
// character class the fold misses is still enforced for RESOLVED
// accounts by the id layer (the bypass-closure test pins this
// hand-off). The collation does NOT equate æ=ae nor ł=l (verified
// live; those equalities hold under utf8mb4_0900_ai_ci, not the
// utf8mb4_unicode_ci the column uses) and the fold keeps them distinct
// too — both layers agree those classes are separate, so neither is a
// fold-miss (an earlier version of this comment credited the collation
// with the æ/ł equalities, and a later audit claimed NFKC merges æ;
// both are wrong — æ has no compatibility decomposition).
// Over-merge (the residual): the mark-strip (needed for
// é→e, which the collation equates) also merges script classes whose
// combining marks carry primary collation weight — Devanagari कि vs क
// and Thai กั vs ก compare DISTINCT under utf8mb4_unicode_ci (verified
// live) while the fold maps both sides to one bucket, so the fold
// bucket is an approximation shared across such variants. Probing a
// nonexistent exotic-script variant of an account fills that account's
// fold bucket, and the PRE-lookup fold check can 429 the account's
// logins before the id-key layer can run — the same documented,
// accepted one-window lockout trade-off as direct probing, extended to
// cross-account variant probing (the id layer and the DB lookup are
// unaffected; a resolved account's failures still accumulate on the id
// key for the post-lookup check). Unknown-email probes were never the
// protected asset — no account exists to lock — so fold-key-only
// counting for them is the documented residual.
// The DB lookup input itself is deliberately NOT folded in JS: JS folding
// could change WHICH row matches for exotic character classes (e.g. dotless-ı
// pairs), a login-behavior change out of scope — and unnecessary once the id
// layer enforces the budget on the resolved identity.
function foldAccountEmail(email) {
const s = String(email || "");
if (!s) return "";
return s
.normalize("NFKC")
.normalize("NFD")
.replace(/\p{M}/gu, "") // strip \p{M} marks (Mn+Mc+Me, not just Mn — the Devanagari over-merge below needs the Mc members): é, fi-style compat forms arrive via NFKC/NFD
.toLowerCase()
.replace(/\u00df/g, "ss") // ß → ss; ẞ lowercases to ß first, so one mapping covers both cases
.trim();
}
function hashAccount(email) {
return crypto.createHash("sha256").update(foldAccountEmail(email)).digest("hex");
}
// adpanel:account-throttle-collation-parity — the id-keyed account budget
// shares the SAME store instance, prefix ("login-fail-acct:") and window as
// the email-keyed one (one store per counter is preserved); the "acct-id:"
// domain tag inside the digest can never collide with a folded-email digest.
function accountIdKey(userId) {
return crypto.createHash("sha256").update(`acct-id:${String(userId)}`).digest("hex");
}
// adpanel:account-verification-budget - remember restoration rotates the SID,
// so session-only limits cannot bound a stolen credential's guessing budget.
// Account ID is stable across restores and email changes; legacy sessions use
// the same folded email key as login. Each tier owns a distinct Redis store.
// adpanel:recovery-account-budget - an authenticated verification budget must
// survive source-IP rotation and remembered login's fresh session identifier.
function createAccountOperationLimiter({ rateLimit, buildStore, prefix, windowMs, sessionMax, accountMax = sessionMax * 3, handler, sessionKey }) {
const accountKey = (req) => Number.isSafeInteger(req.session?.accountId) && req.session.accountId > 0
? accountIdKey(req.session.accountId)
: hashAccount(req.session?.user);
const options = {
windowMs,
standardHeaders: true,
legacyHeaders: false,
passOnStoreError: true,
skip: (req) => !req.session?.user,
handler,
};
const accountLimiter = rateLimit({
...options,
max: accountMax,
store: buildStore ? buildStore(`${prefix}account:`, windowMs) : undefined,
keyGenerator: accountKey,
});
const sessionLimiter = rateLimit({
...options,
max: sessionMax,
store: buildStore ? buildStore(prefix, windowMs) : undefined,
keyGenerator: sessionKey || ((req) => `${accountKey(req)}:${String(req.sessionID || "no-session")}`),
});
return function accountOperationLimiter(req, res, next) {
return accountLimiter(req, res, (err) => err ? next(err) : sessionLimiter(req, res, next));
};
}
function createAccountVerificationLimiter({ rateLimit, buildStore, kind, securityLog, getRequestIp }) {
if (!["credential", "totp"].includes(kind)) throw new TypeError("invalid verification limiter kind");
return createAccountOperationLimiter({
rateLimit,
buildStore: buildStore ? (prefix, windowMs) => buildStore(prefix.replace(":account:", "-account:"), windowMs) : undefined,
prefix: `account-${kind}:`,
windowMs: 10 * 60 * 1000,
sessionMax: 10,
accountMax: 30,
sessionKey: (req) => `account-${kind === "totp" ? "totp" : "cred-verify"}:${String(req.session?.user || "anon").trim().toLowerCase()}:${String(req.sessionID || "no-session")}`,
handler: (req, res) => {
securityLog(`Account ${kind === "totp" ? "2FA" : "credential"} verification rate limit exceeded`, req);
res.status(429).json({ error: "Too many verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" });
},
});
}
function createLoginThrottle({ buildStore, MemoryStore, ipKeyGenerator, env = process.env, logger = console }) {
const MIN = 60 * 1000, DAY = 24 * 60 * 60 * 1000;
const cfg = {
ip: {
windowMs: resolveClampedInt(env, "LOGIN_IP_FAILURE_WINDOW_MS", { fallback: 10 * MIN, min: MIN, max: DAY }),
max: resolveClampedInt(env, "LOGIN_IP_MAX_FAILURES", { fallback: 10, min: 3, max: 1000 }),
},
account: {
windowMs: resolveClampedInt(env, "LOGIN_ACCOUNT_FAILURE_WINDOW_MS", { fallback: 15 * MIN, min: MIN, max: DAY }),
max: resolveClampedInt(env, "LOGIN_ACCOUNT_MAX_FAILURES", { fallback: 20, min: 5, max: 10000 }),
},
totpSource: {
windowMs: Math.max(
resolveClampedInt(env, "TOTP_ATTEMPT_WINDOW_MS", { fallback: 5 * MIN, min: MIN, max: DAY }),
resolveClampedInt(env, "TOTP_ATTEMPT_BLOCK_MS", { fallback: 15 * MIN, min: MIN, max: DAY })
),
max: resolveClampedInt(env, "TOTP_ATTEMPT_MAX", { fallback: 5, min: 1, max: 100 }),
},
};
const makeStore = (prefix, windowMs) => {
const store = buildStore ? buildStore(prefix, windowMs) : new MemoryStore();
store.init({ windowMs }); // standalone use: express-rate-limit is not calling init for us
return store;
};
const stores = {
ip: makeStore("login-fail-ip:", cfg.ip.windowMs),
account: makeStore("login-fail-acct:", cfg.account.windowMs),
totpSource: makeStore("login-totp-src:", cfg.totpSource.windowMs),
};
let lastLog = 0;
// posture names the direction the caller degrades in: "open" for the read
// checks (a lost read reads as not blocked), "closed" for the reservation
// (a lost increment refuses admission — Redis down means the session store
// is down and logins fail anyway, so a refused admission degrades nothing).
const logErr = (op, err, posture = "open") => { const t = Date.now(); if (t - lastLog > 60000) { lastLog = t; logger.warn(`[login-throttle] ${op} failed (failing ${posture}):`, err?.message || err); } };
const hits = async (s, k) => { try { const n = Number((await s.get(k))?.totalHits); return Number.isFinite(n) && n > 0 ? n : 0; } catch (e) { logErr("get", e); return 0; } };
const bump = async (s, k) => { try { return Number((await s.increment(k))?.totalHits) || 0; } catch (e) { logErr("increment", e); return 0; } };
const clear = async (s, k) => { try { await s.resetKey(k); } catch (e) { logErr("resetKey", e); } };
// adpanel:login-bcrypt-admission — the refund primitive: decrement ONE
// counter, floored at zero. The pre-read guards it (a decrement may only
// follow a standing increment): the MemoryStore floors natively, but the
// Redis store's DECR would drive an expired/missing key to -1 WITHOUT a
// TTL (DECR creates the key) — a phantom counter that never decays and
// silently widens the budget forever. A lost refund (store error) leaves a
// phantom failure standing: the fail-closed direction — one admission slot
// fewer until the window decays. Residual: two concurrent refunds whose
// pre-reads interleave at a window boundary can still pair up on one
// standing increment (bounded magnitude 1, self-heals at the key's TTL).
const refundOne = async (s, k) => {
try {
const current = Number((await s.get(k))?.totalHits);
if (!Number.isFinite(current) || current <= 0) return; // nothing standing to refund
await s.decrement(k);
} catch (e) { logErr("refund", e); }
};
const refundKeys = (src, accountKeys) =>
Promise.all([refundOne(stores.ip, src), ...accountKeys.map((k) => refundOne(stores.account, k))]);
const ipKey = (ip) => ipKeyGenerator(String(ip || "unknown"));
// adpanel:account-throttle-collation-parity — the TOTP key takes an
// account-level key (folded-email digest or id digest) plus the source;
// the per-account component switches from the submitted email's fold key
// to the resolved user's id key wherever the user is resolved.
const totpKey = (accountKey, src) => `${accountKey}|${src}`;
// The id key exists only when a RESOLVED user is in hand; both record and
// reset treat it as an optional second layer over the fold key.
const idKeysOf = (resolvedUser) =>
resolvedUser && resolvedUser.id != null && String(resolvedUser.id) !== "" ? accountIdKey(resolvedUser.id) : null;
return {
config: cfg,
ipKey,
async isIpBlocked(src) { return (await hits(stores.ip, src)) >= cfg.ip.max; },
async isAccountBlocked(email) { return (await hits(stores.account, hashAccount(email))) >= cfg.account.max; },
// adpanel:account-throttle-collation-parity — post-lookup enforcement on
// the resolved identity: the check the login handler runs once
// findUserByEmail has resolved the row, before any credential compare.
async isAccountBlockedById(userId) { return (await hits(stores.account, accountIdKey(userId))) >= cfg.account.max; },
// adpanel:login-bcrypt-admission — reserve-then-finalize/refund. The
// pre-fix flow READ the budgets at request entry but only ARMED them in
// the failure path (recordCredentialFailure, after bcrypt completed), so
// a parallel burst of 60 POSTs all read pre-burst counters, all paid
// their 2^FLOOR compare, and all recorded: the budgets overshot ~6x and
// the threadpool saturated. The reservation inverts the order: the
// increments happen at admission (the store's INCR is atomic per key;
// the pair is made all-or-nothing by the refund — any over-max or failed
// leg refunds every leg), the admission check reads the standing totals
// back, and only ADMITTED attempts reach a compare. The increments STAND
// as the failure record until the request settles:
// - confirmed failure -> the handler's finalizeCredentialFailure keeps
// them (side effects only — captcha arming + crossing logs; NO
// re-increment, that would double-count);
// - any other outcome -> refundCredentialAttempt decrements both
// counters (floored at 0), so the net recorded failures stay exactly
// the CONFIRMED ones — success, the 2FA challenge, the captcha
// challenge, suspension and unexpected errors consume no budget.
// Keys: the fold key always (unknown emails included — the account
// budget must not leak account validity); the id key additionally when
// the resolved user is threaded in (adpanel:account-throttle-collation-
// parity dual key, identical to the removed recordCredentialFailure).
// Admission refuses when EITHER counter would exceed its max: over-source
// and over-account both refund EVERYTHING, so a refused request records
// nothing — exactly the old blocked-at-entry semantics, now enforced
// atomically against the burst. The crossing flags report the bump that
// landed exactly on a max (the same condition recordCredentialFailure
// logged); a refund discards them, so only confirmed crossings log — a
// refund-then-refill inside one window can log a second crossing, which
// is the more accurate telemetry.
// Documented residuals: a reservation whose store op fails fails CLOSED
// (reason "store" — during a Redis outage logins are failing anyway via
// the shared session store); a process crash mid-request leaves its
// admitted increments standing until the window decays (a phantom
// failure, bounded by the window); a crash between the ip and account
// increments leaves one phantom leg (same bound).
async reserveCredentialAttempt(src, email, resolvedUser) {
const accountKeys = [hashAccount(email)];
const idKey = idKeysOf(resolvedUser);
if (idKey) accountKeys.push(idKey);
const landed = await Promise.all([bump(stores.ip, src), ...accountKeys.map((k) => bump(stores.account, k))]);
// Admission binds on the STANDING total read back after the
// increments, not on the increment's return value: the shared Redis
// store's INCR reports the atomic landing count, but express-rate-
// limit's MemoryStore returns a LIVE client object whose totalHits is
// only read after the await — under a parallel burst every caller
// would then see the FINAL counter instead of its own landing. The
// read-back is store-agnostic and keeps the invariant that matters in
// both stores: at most max standing reservations. On the non-Redis
// fallback a fully-parallel burst therefore reads the post-burst
// total and is refused IN FULL (every increment refunded) — strictly
// safer than admitting max; sequential traffic is unaffected.
const [ipHits, ...accountHits] = await Promise.all([hits(stores.ip, src), ...accountKeys.map((k) => hits(stores.account, k))]);
// A failed increment (bump() returns 0 only on a store error — a
// successful INCR is always >= 1) or a read-back that cannot see its
// own increment refuses admission: the reservation is the
// authoritative budget and must fail CLOSED. (During a Redis outage
// logins fail anyway through the shared session store.) Refund
// whatever landed so a refused request records nothing.
if (landed.some((n) => n < 1) || ipHits < 1 || accountHits.some((n) => n < 1)) {
await refundKeys(src, accountKeys);
return { admitted: false, reason: "store", ipThresholdReached: false, accountThresholdReached: false };
}
if (ipHits > cfg.ip.max) {
await refundKeys(src, accountKeys);
return { admitted: false, reason: "source", ipThresholdReached: false, accountThresholdReached: false };
}
// The per-account budget binds through EITHER enforcement key — one
// semantic budget, two keys (the fold key gates pre-lookup and
// unknown-email probes, the id key the resolved identity).
if (accountHits.some((n) => n > cfg.account.max)) {
await refundKeys(src, accountKeys);
return { admitted: false, reason: "account", ipThresholdReached: false, accountThresholdReached: false };
}
return {
admitted: true,
reason: null,
ipThresholdReached: ipHits === cfg.ip.max,
accountThresholdReached: accountHits.some((n) => n === cfg.account.max),
};
},
// adpanel:login-bcrypt-admission — release a still-outstanding admitted
// reservation: decrement the source counter and every account key the
// reservation incremented (floored at 0). Called on every non-failure
// exit after admission; keys derive from the same (email, resolvedUser)
// the reservation used, so the refund is exactly balanced with the
// increments.
async refundCredentialAttempt(src, email, resolvedUser) {
const accountKeys = [hashAccount(email)];
const idKey = idKeysOf(resolvedUser);
if (idKey) accountKeys.push(idKey);
await refundKeys(src, accountKeys);
},
async isTotpBlocked(email, src) { return (await hits(stores.totpSource, totpKey(hashAccount(email), src))) >= cfg.totpSource.max; },
async isTotpBlockedById(userId, src) { return (await hits(stores.totpSource, totpKey(accountIdKey(userId), src))) >= cfg.totpSource.max; },
async recordTotpAttempt(email, src) { return bump(stores.totpSource, totpKey(hashAccount(email), src)); },
async recordTotpAttemptById(userId, src) { return bump(stores.totpSource, totpKey(accountIdKey(userId), src)); },
async resetTotpSource(email, src, resolvedUser) {
// A successful login proves the code, so BOTH keys the attempts were
// recorded under clear: the fold key of the submitted email and — when
// the user is resolved — the id key (without it, an id budget filled by
// variant submissions would lock the next legitimate login).
const keys = [totpKey(hashAccount(email), src)];
const idKey = idKeysOf(resolvedUser);
if (idKey) keys.push(totpKey(idKey, src));
for (const k of keys) await clear(stores.totpSource, k);
},
};
}
module.exports = { createLoginThrottle, createLoginRequestLimiter, createAccountVerificationLimiter, createAccountOperationLimiter, sendLoginRateLimited, wantsJsonLoginResponse, foldAccountEmail, loginRetryAfterSeconds };