"use strict"; // adpanel:detector-cluster-shared — source + behavior pins for the // cluster-shared counters behind BOTH /login defense-in-depth mechanisms // (the attack detector's ≥100-unique-source arming map + armed-mode per-source // brake, and the pre-auth captcha-gate IP latch). // // Constraint under test: these layers must not silently fragment across PM2 // cluster workers. Per-process Maps made each worker see ~1/N of the traffic, // so the ≥100-unique-source arming bar rose ~N×, the 25-hit/3s brake // threshold effectively multiplied per worker, and the captcha latch armed on // only the workers that saw the failures (~1/N captcha enforcement). The // counters are mirrored into the session Redis store // (utils/login-attack-redis.js — one key namespace per mechanism, short-TTL // atomic ops) with UNCHANGED thresholds/env knobs, hold behavior, captcha // check order and primary Redis budgets. Fail posture is pinned too: every // shared op is best-effort (readiness-gated, hard-timeout-bounded, never // rejecting) and with Redis down the per-process Maps remain the sole // mechanism — the exact pre-fix behavior, still FIFO-capped. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const MODULE_JS = path.join(ROOT, "utils", "login-attack-redis.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const moduleSource = fs.readFileSync(MODULE_JS, "utf8"); const { createLoginSharedCounters } = require(MODULE_JS); const { LOGIN_ATTACK_ARM_KEY_PREFIX, LOGIN_ATTACK_BRAKE_KEY_PREFIX, LOGIN_CAPTCHA_LATCH_KEY_PREFIX, LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA, LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA, } = require(MODULE_JS); function indexOfOrThrow(needle, from = 0) { const idx = indexSource.indexOf(needle, from); assert.ok(idx >= 0, `expected source pin not found: ${needle}`); return idx; } // Extract a full top-level function declaration by brace matching (skipping // line/block comments and string literals), so behavior pins evaluate the // SHIPPED source rather than a re-typed copy of it. The `async` modifier is // part of the match: the detector functions became async with the // detector-cluster-shared mirror, and slicing from `function name(` alone // would drop the modifier while keeping the body's awaits (a syntax error). function extractFunction(name) { let start = indexSource.indexOf(`async function ${name}(`); if (start < 0) start = indexOfOrThrow(`function ${name}(`); let i = indexSource.indexOf("{", start); let depth = 0; let inLine = false; let inBlock = false; let quote = null; for (; i < indexSource.length; i++) { const c = indexSource[i]; const n = indexSource[i + 1]; if (inLine) { if (c === "\n") inLine = false; continue; } if (inBlock) { if (c === "*" && n === "/") { inBlock = false; i++; } continue; } if (quote) { if (c === "\\") { i++; continue; } if (c === quote) quote = null; continue; } if (c === "/" && n === "/") { inLine = true; i++; continue; } if (c === "/" && n === "*") { inBlock = true; i++; continue; } if (c === "'" || c === '"' || c === "`") { quote = c; continue; } if (c === "{") depth++; else if (c === "}") { depth--; if (depth === 0) return indexSource.slice(start, i + 1); } } throw new Error(`unbalanced braces while extracting ${name}`); } const markLoginTrafficSource = extractFunction("markLoginTraffic"); const isLoginUnderAttackSource = extractFunction("isLoginUnderAttack"); const isAggressiveLoginIpSource = extractFunction("isAggressiveLoginIp"); const middlewareSource = extractFunction("loginAttackMiddleware"); const challengeSource = extractFunction("buildPendingLoginCaptchaChallenge"); const gateRequestReaderSource = extractFunction("isLoginCaptchaGateArmedForRequest"); const gateSetSource = extractFunction("setLoginCaptchaGateForIp"); const gateClearSource = extractFunction("clearLoginCaptchaGateForIp"); // --------------------------------------------------------------------------- // Section A — index.js source pins: the counters ride the session Redis // client, every decision threshold stays in this file, the maps stay as the // fallback, and the middleware's mount scope is /login only. // --------------------------------------------------------------------------- test("wiring: the shared counters ride the session Redis client and its readiness flag", () => { assert.ok(indexSource.includes('const { createLoginSharedCounters } = require("./utils/login-attack-redis");'), "index.js must require the ONE shared-counter module"); const wiringIdx = indexOfOrThrow("const loginSharedCounters = createLoginSharedCounters({"); const wiring = indexSource.slice(wiringIdx, indexSource.indexOf("});", wiringIdx)); assert.ok(wiring.includes("clientOf: () => redisClient,"), "the client is the SAME session Redis client the throttles ride"); assert.ok(wiring.includes("readyOf: () => redisSessionReady,"), "readiness gates every op (file-store deployments have redisClient = null)"); assert.ok(indexSource.includes("// adpanel:detector-cluster-shared —"), "the constraint is documented with the adpanel tag in index.js"); assert.ok(moduleSource.includes("adpanel:detector-cluster-shared"), "and in utils/login-attack-redis.js"); }); test("arming: exact unique counting via HSETNX/HLEN over a per-window bucket with window+1s TTL; thresholds and hold untouched", () => { assert.ok(markLoginTrafficSource.includes("await loginSharedCounters.armWindowBucket("), "the arming decision mirrors the source into the shared window hash"); assert.ok(markLoginTrafficSource.includes("Math.floor(now / LOGIN_ATTACK_WINDOW_MS),"), "each LOGIN_ATTACK_WINDOW_MS wall-clock window is its own hash key (floor(now / window) bucketing)"); assert.ok(markLoginTrafficSource.includes("Math.ceil(LOGIN_ATTACK_WINDOW_MS / 1000) + 1"), "the bucket TTL is window seconds + 1s of read slack (2s for the 1s default)"); assert.ok(markLoginTrafficSource.includes("if (Math.max(loginAttackIps.size, sharedSources) >= LOGIN_ATTACK_UNIQUE_IPS) {"), "the arm decision is the UNION of the local and shared unique counts under the SAME threshold"); assert.ok(markLoginTrafficSource.includes("loginUnderAttackUntil = Math.max(loginUnderAttackUntil, now + LOGIN_ATTACK_HOLD_MS);"), "the armed-mode hold behavior is byte-identical"); assert.ok(markLoginTrafficSource.includes("if (!loginAttackIps.has(ip) && loginAttackIps.size >= LOGIN_MAP_MAX_SIZE) {"), "the local arming map stays FIFO-capped (the Redis-down fallback must not grow without bound)"); // The env knobs keep their exact defaults — resolved through the ONE // clamped-int helper (adpanel:env-int-clamp) so a misconfigured value can // tune but never silently disable the arming layer; the consumer lines // above are untouched. assert.ok(indexSource.includes('const LOGIN_ATTACK_WINDOW_MS = resolveClampedInt(process.env, "LOGIN_ATTACK_WINDOW_MS", { fallback: 1000, min: 250, max: 10000 });')); assert.ok(indexSource.includes('const LOGIN_ATTACK_UNIQUE_IPS = resolveClampedInt(process.env, "LOGIN_ATTACK_UNIQUE_IPS", { fallback: 100, min: 10, max: 10000 });')); assert.ok(indexSource.includes('const LOGIN_ATTACK_HOLD_MS = resolveClampedInt(process.env, "LOGIN_ATTACK_HOLD_MS", { fallback: 60000, min: 10000, max: 600000 });')); }); test("brake: shared INCR+EXPIRE over the same threshold, verdict is the union, the sliding-window map stays the fallback", () => { assert.ok(isAggressiveLoginIpSource.includes("await loginSharedCounters.brakeHit(ip, Math.ceil(LOGIN_ATTACK_IP_WINDOW_MS / 1000));"), "the brake hit count is shared with a window-seconds TTL (3s for the 3s default)"); assert.ok(isAggressiveLoginIpSource.includes("return arr.length > LOGIN_ATTACK_IP_MAX || sharedHits > LOGIN_ATTACK_IP_MAX;"), "aggressive = local hits > LOGIN_ATTACK_IP_MAX OR shared hits > LOGIN_ATTACK_IP_MAX (one threshold, cluster-wide)"); assert.ok(isAggressiveLoginIpSource.includes("arr = arr.filter(ts => now - ts <= LOGIN_ATTACK_IP_WINDOW_MS);"), "the local sliding-window prune is unchanged (the Redis-down fallback)"); assert.ok(isAggressiveLoginIpSource.includes("if (!loginAttackIpHits.has(ip) && loginAttackIpHits.size >= LOGIN_MAP_MAX_SIZE) {"), "the local brake map stays FIFO-capped"); assert.ok(indexSource.includes('const LOGIN_ATTACK_IP_WINDOW_MS = resolveClampedInt(process.env, "LOGIN_ATTACK_IP_WINDOW_MS", { fallback: 3000, min: 250, max: 10000 });')); assert.ok(indexSource.includes('const LOGIN_ATTACK_IP_MAX = resolveClampedInt(process.env, "LOGIN_ATTACK_IP_MAX", { fallback: 25, min: 5, max: 1000 });')); }); test("middleware: async orchestration preserves the check order, resolves the gate verdict once, and never rejects past Express 4", () => { const at = (needle) => middlewareSource.indexOf(needle); const deriveIdx = at('const ip = ipKeyGenerator(String(getRequestIp(req) || "unknown"));'); const markIdx = at("await markLoginTraffic(ip);"); const stashIdx = at("req.loginCaptchaGateSharedVerdict = await isLoginCaptchaGateArmedForIpShared(ip);"); const underAttackIdx = at("const underAttack = isLoginUnderAttack();"); const brakeIdx = at("aggressive = await isAggressiveLoginIp(ip);"); assert.ok(deriveIdx >= 0 && markIdx > deriveIdx, "the middleware awaits the arming mirror (the arm includes the shared count before any read)"); assert.ok(stashIdx > markIdx, "the shared gate verdict is resolved once per request, after arming"); assert.ok(underAttackIdx > stashIdx, "the armed-mode read follows"); assert.ok(brakeIdx > underAttackIdx, "the brake is consulted only after the armed-mode read"); const brakeGuard = middlewareSource.slice(underAttackIdx, brakeIdx); assert.ok(brakeGuard.includes("if (underAttack) {"), "the brake (and its Redis ops) run ONLY while attack mode is armed — never in the steady state"); // adpanel:login-retry-after — conscious pin update (the brake's Retry-After // now DERIVES from its actual window): the hard-coded literal 5 became // Math.ceil(LOGIN_ATTACK_IP_WINDOW_MS / 1000) — the same window-seconds // derivation the shared brake's EXPIRE math uses — so the header tracks an // env-tuned window instead of a hard-coded 5 s that overstated the shipped // 3000 ms window (the default header changes 5→3: today it overstates, // after the fix it is honest, and it stays correct across the whole // 250..10000 clamp band). The refusal still routes through the ONE // responder. assert.ok(middlewareSource.includes("return sendLoginRateLimited(req, res, securityLog, \"Login attack-mode rate limit exceeded\", Math.ceil(LOGIN_ATTACK_IP_WINDOW_MS / 1000));"), "the refusal still goes through the ONE content-negotiated 429 responder, carrying a Retry-After derived from the brake's actual LOGIN_ATTACK_IP_WINDOW_MS"); assert.ok(middlewareSource.includes("return next(err);"), "the whole body is wrapped: an unexpected throw surfaces through next(err) exactly as the sync throw did pre-fix (Express 4 does not catch async rejections)"); assert.ok(middlewareSource.includes("if (ANY_CAPTCHA_ENABLED) {"), "the shared verdict resolution is skipped while captcha is disabled (zero extra ops)"); }); test("mount scope: the detector runs on /login only — the shared-counter ops never reach a hot non-login path", () => { assert.strictEqual((indexSource.match(/app\.use\("\/login", loginAttackMiddleware\);/g) || []).length, 1, "exactly one mount, scoped to /login"); assert.ok(!indexSource.includes("app.use(loginAttackMiddleware)"), "no unscoped mount may exist (it would put the Redis ops on every request)"); }); test("gate reads: the sync readers go through the per-request reader; the verify unlock reads the shared latch directly", () => { assert.ok(challengeSource.includes("isLoginCaptchaGateArmedForRequest(req, loginThrottle.ipKey(getRequestIp(req)))"), "the challenge builder (GET /login, sendError, sendCaptchaChallenge) consults the per-request verdict"); assert.ok(indexSource.includes("const ipGateArmed = !!(isLoginCaptchaGateArmedForRequest(req, throttleIpKey) && !req.session.loginCaptchaPassed);"), "POST /login's enforcement gate consults the per-request verdict, check order unchanged"); assert.ok(indexSource.includes("await isLoginCaptchaGateArmedForIpShared(loginThrottle.ipKey(clientIp))"), "/api/captcha/verify sits outside the /login middleware scope and resolves the shared verdict itself"); assert.ok(gateRequestReaderSource.includes("if (isLoginCaptchaGateArmedForIp(ipKey)) return true;"), "the reader answers from the local map first (zero Redis when this worker armed the latch)"); assert.ok(gateRequestReaderSource.includes("return req?.loginCaptchaGateSharedVerdict === true;"), "then the middleware's pre-resolved shared verdict"); assert.ok(!gateRequestReaderSource.includes("await"), "the reader stays sync (it feeds sync decision paths)"); assert.ok(!indexSource.includes("req.loginCaptchaGateSharedVerdict = await isLoginCaptchaGateArmedForIp(ipKey)"), "the stash is the SHARED resolver's verdict, not a re-read of the local map"); }); test("latch: the mirror keeps the SAME TTL as the local map, and clear spans the cluster", () => { assert.ok(indexSource.includes("const LOGIN_CAPTCHA_GATE_TTL_MS = 10 * 60 * 1000;"), "the local latch TTL is untouched"); assert.ok(indexSource.includes("const LOGIN_CAPTCHA_GATE_TTL_SECONDS = Math.max(1, Math.ceil(LOGIN_CAPTCHA_GATE_TTL_MS / 1000));"), "the shared TTL derives from the same constant (mirrored exactly)"); assert.ok(gateSetSource.includes("loginSharedCounters.latchSet(ipKey, LOGIN_CAPTCHA_GATE_TTL_SECONDS);"), "arming mirrors the latch into the shared store"); assert.ok(gateSetSource.includes("loginCaptchaGates.set(ipKey, Date.now());"), "and still writes the local map (write-through fallback)"); assert.ok(gateClearSource.includes("loginSharedCounters.latchDel(ipKey);"), "the clear spans the cluster (a captcha solved against one worker must not leave others gating the source)"); assert.ok(indexSource.includes("loginSharedCounters.latchClearAll();"), "the live-disable sweep clears the shared latches too"); }); test("primary budgets untouched: the login throttle's shared-store wiring is exactly as before", () => { // adpanel:store-fallback-valid-hits — conscious pin update: the factory // gained the explicit (client, fallbackHits=0) args. The brute-force bound // is unchanged — the counters still ride the ONE shared Redis wrapper with // the same prefixes and windows; fallbackHits=0 only preserves the // reservation's fail-closed error sentinel (bump() == 0 on a store error), // which a default-of-1 fallback would have silently disarmed. assert.ok(indexSource.includes("const loginThrottleStoreFactory = redisClient ? (prefix, windowMs) => buildSharedRateLimitRedisStore(prefix, windowMs, redisClient, 0) : null;"), "the throttle's Redis-shared store factory is unchanged apart from the explicit fallbackHits=0 sentinel (primary brute-force bound)"); }); // --------------------------------------------------------------------------- // Section B — module source pins: distinct prefixes, atomic short-TTL ops, // and the never-reject fail posture. // --------------------------------------------------------------------------- test("module: one key namespace per mechanism, distinct from each other and from every other Redis consumer", () => { assert.ok(moduleSource.includes('const LOGIN_ATTACK_ARM_KEY_PREFIX = "adpanel:attack-arm:";')); assert.ok(moduleSource.includes('const LOGIN_ATTACK_BRAKE_KEY_PREFIX = "adpanel:attack-brake:";')); assert.ok(moduleSource.includes('const LOGIN_CAPTCHA_LATCH_KEY_PREFIX = "adpanel:login-captcha-latch:";')); const prefixes = [LOGIN_ATTACK_ARM_KEY_PREFIX, LOGIN_ATTACK_BRAKE_KEY_PREFIX, LOGIN_CAPTCHA_LATCH_KEY_PREFIX]; assert.strictEqual(new Set(prefixes).size, 3, "the three namespaces are pairwise distinct"); for (const foreign of ["rate-limit-redis", "adpanel:sess:", "arl:"]) { for (const prefix of prefixes) { assert.ok(!prefix.startsWith(foreign) && !foreign.startsWith(prefix), `the ${prefix} namespace must not collide with ${foreign}`); } } }); test("module: atomic counting ops with short TTLs — ONE atomic arm EVAL + HLEN, ONE atomic brake EVAL, SET...EX, GET, DEL, SCAN sweep", () => { // Arming: ONE atomic EVAL (script, numkeys=1, key, sourceKey, ttl) — never // the pre-fix two-command HSETNX/EXPIRE shape, whose lost-EXPIRE round-trip // gap stranded a TTL-less arm hash forever (harmless by construction — new // bucket keys derive per window — but unbounded slow growth with no sweep). const armFn = moduleSource.slice( moduleSource.indexOf("async function armWindowBucket("), moduleSource.indexOf("// Armed-mode brake:") ); assert.ok(armFn.includes('"EVAL"') && armFn.includes("LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA") && armFn.includes('"1"'), "armWindowBucket issues ONE EVAL carrying the shipped script, one key, the source field and the TTL"); assert.ok(!moduleSource.includes('send(["HSETNX"') && !moduleSource.includes('send(["EXPIRE"'), "no separate HSETNX/EXPIRE round trips may remain anywhere in the module (the lost-EXPIRE gap is the residue class the atomic script removes)"); const armScriptAt = moduleSource.indexOf("const LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA = ["); assert.ok(armScriptAt >= 0, "the arm script ships as a module constant"); const armScript = moduleSource.slice(armScriptAt, moduleSource.indexOf("function normalizeTtlSeconds(")); assert.ok(armScript.includes("local added = redis.call('HSETNX', KEYS[1], ARGV[1], '1')"), "the arm script HSETNXes first — the first-insert verdict is authoritative"); const armPttlAt = armScript.indexOf("if redis.call('PTTL', KEYS[1]) < 0 then"); const armExpireAt = armScript.indexOf("redis.call('EXPIRE', KEYS[1], ARGV[2])"); assert.ok(armPttlAt >= 0 && armExpireAt > armPttlAt && armScript.includes("return added"), "the arm script's EXPIRE sits inside its PTTL<0 branch — a live TTL is never refreshed, a lost TTL self-heals on the next first-insert, and the caller's added===1/0 semantics are preserved"); assert.ok(moduleSource.includes('send(["HLEN", key]);'), "arming: HLEN is the cluster-wide unique count"); // Brake: ONE atomic EVAL (script, numkeys=1, key, ttl) — never the pre-fix // two-command INCR/EXPIRE shape, whose lost-EXPIRE round-trip gap left a // TTL-less key that self-stuck "aggressive" forever. const brakeFn = moduleSource.slice(moduleSource.indexOf("async function brakeHit("), moduleSource.indexOf("// Captcha-gate latch")); assert.ok(brakeFn.includes('"EVAL"') && brakeFn.includes("LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA") && brakeFn.includes('"1"'), "brakeHit issues ONE EVAL carrying the shipped script, one key and the TTL"); assert.ok(!brakeFn.includes('send(["INCR"') && !brakeFn.includes('send(["EXPIRE"'), "no separate INCR/EXPIRE round trips may return (the lost-EXPIRE gap IS the bug)"); assert.ok(moduleSource.includes("local v = redis.call('INCR', KEYS[1])"), "the script INCRs first — the count is authoritative"); const pttlAt = moduleSource.indexOf("if redis.call('PTTL', KEYS[1]) < 0 then"); const expireAt = moduleSource.indexOf("redis.call('EXPIRE', KEYS[1], ARGV[1])"); assert.ok(pttlAt >= 0 && expireAt > pttlAt, "the EXPIRE sits inside the PTTL<0 branch — a live TTL is never refreshed (fixed-window semantics preserved), a lost TTL re-arms"); assert.ok(moduleSource.includes('send(["SET", key, "1", "EX", String(normalizeTtlSeconds(ttlSeconds))]);'), "latch: SET with the mirrored EX TTL"); assert.ok(moduleSource.includes('send(["GET", key]);'), "latch read: GET"); assert.ok(moduleSource.includes('send(["DEL", key]);'), "latch clear: DEL"); assert.ok(moduleSource.includes('send(["SCAN", cursor, "MATCH", `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}*`, "COUNT", "500"]);'), "live-disable sweep: best-effort SCAN+DEL"); }); test("module: fail posture — readiness-gated, hard-timeout-bounded, never rejecting, null means fall back", () => { assert.ok(moduleSource.includes('if (!client || typeof client.sendCommand !== "function" || !readyOf()) return null;'), "no client / wrong shape / not ready resolves to the fallback signal, never throws"); assert.ok(moduleSource.includes("op.catch(() => {});"), "the raced promise pre-attaches a rejection handler (a late connection error is never unhandled)"); assert.ok(moduleSource.includes("setTimeout(() => resolve(null), opTimeoutMs)"), "a hard per-op timeout bounds every dial"); const sendFn = moduleSource.slice(moduleSource.indexOf("async function send("), moduleSource.indexOf("async function armWindowBucket(")); assert.ok(sendFn.includes("} catch (err) {") && sendFn.includes("return null;"), "send never rejects: any failure resolves to null (the caller's fall-back-to-local-map signal)"); }); // --------------------------------------------------------------------------- // Section C — module behavior pins against a fake Redis (multi-worker // semantics, TTLs, namespaces, and the down/not-ready/timeout postures). // --------------------------------------------------------------------------- // A minimal fake node-redis client: sendCommand over hashes/strings (plus // EVAL, honored for exactly the shipped arm + brake scripts) with a // controllable clock, a command log, and injectable failure modes. function createFakeRedis({ fail = false, hang = false } = {}) { const hashes = new Map(); // key -> { fields: Map, expireAt: number|null } const strings = new Map(); // key -> { value, expireAt: number|null } const log = []; let clock = 1_000_000; const client = { ready: true, log, advance: (ms) => { clock += ms; }, // Simulates the lost-TTL state the atomic brake script heals: the INCR // executed server-side but its EXPIRE never landed (connection drop in // the round-trip gap) — the key persists with a count and NO expiry, // which under Redis persistence survives restarts. stripTtl: (key) => { const entry = hashes.get(key) || strings.get(key); if (entry) entry.expireAt = null; }, expireAtOf: (key) => { const entry = hashes.get(key) || strings.get(key); return entry ? entry.expireAt : null; }, sendCommand: (args) => { const parts = args.map(String); log.push(parts); if (hang) return new Promise(() => {}); const run = async () => { if (fail) throw new Error("redis down"); const cmd = parts[0].toUpperCase(); const key = parts[1]; const alive = (entry) => !entry.expireAt || clock < entry.expireAt; switch (cmd) { case "HSETNX": { let entry = hashes.get(key); if (entry && !alive(entry)) hashes.delete(key); if (!hashes.has(key)) hashes.set(key, { fields: new Map(), expireAt: null }); entry = hashes.get(key); const field = parts[2]; if (entry.fields.has(field)) return 0; entry.fields.set(field, parts[3]); return 1; } case "HLEN": { const entry = hashes.get(key); return entry && alive(entry) ? entry.fields.size : 0; } case "EXPIRE": { const entry = hashes.get(key) || strings.get(key); if (!entry || !alive(entry)) return 0; entry.expireAt = clock + Number(parts[2]) * 1000; return 1; } case "INCR": { let entry = strings.get(key); if (entry && !alive(entry)) strings.delete(key); if (!strings.has(key)) strings.set(key, { value: "0", expireAt: null }); entry = strings.get(key); entry.value = String(Number(entry.value) + 1); return Number(entry.value); } case "SET": { let entry = strings.get(key); if (!entry) { entry = { value: "", expireAt: null }; strings.set(key, entry); } entry.value = parts[2]; entry.expireAt = null; if (parts[3]?.toUpperCase() === "EX") entry.expireAt = clock + Number(parts[4]) * 1000; return "OK"; } case "GET": { const entry = strings.get(key); if (!entry || !alive(entry)) { if (entry) strings.delete(key); return null; } return entry.value; } case "DEL": { let n = 0; for (const k of parts.slice(1)) { if (hashes.delete(k)) n++; else if (strings.delete(k)) n++; } return n; } case "SCAN": { const match = parts[3]; const prefix = match.slice(0, match.indexOf("*")); const keys = [...strings.keys()].filter((k) => k.startsWith(prefix)); return ["0", keys]; } case "EVAL": { // Honor the TWO scripts the module ships: exact match against the // exported constants, so an edited script fails the tests loudly // and must be mirrored consciously. parts: EVAL, script, // numkeys, KEYS[1], ARGV[1..2]. if (parts[2] !== "1") throw new Error("fake client: EVAL numkeys must be 1"); const evalKey = parts[3]; if (parts[1] === LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA) { const ttlSeconds = Number(parts[4]); // Line-for-line mirror of the shipped Lua against the string store. let entry = strings.get(evalKey); if (entry && !alive(entry)) strings.delete(evalKey); if (!strings.has(evalKey)) strings.set(evalKey, { value: "0", expireAt: null }); entry = strings.get(evalKey); entry.value = String(Number(entry.value) + 1); // local v = redis.call('INCR', KEYS[1]) const count = Number(entry.value); const pttl = entry.expireAt ? entry.expireAt - clock : -1; // redis.call('PTTL', KEYS[1]) if (pttl < 0) entry.expireAt = clock + ttlSeconds * 1000; // redis.call('EXPIRE', KEYS[1], ARGV[1]) when missing return count; // return v } if (parts[1] === LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA) { const field = parts[4]; const ttlSeconds = Number(parts[5]); // Line-for-line mirror of the shipped Lua against the hash store. let entry = hashes.get(evalKey); if (entry && !alive(entry)) hashes.delete(evalKey); if (!hashes.has(evalKey)) hashes.set(evalKey, { fields: new Map(), expireAt: null }); entry = hashes.get(evalKey); const added = entry.fields.has(field) ? 0 : 1; // local added = redis.call('HSETNX', KEYS[1], ARGV[1], '1') if (added === 1) { entry.fields.set(field, "1"); // (the value '1' is baked into the script) const pttl = entry.expireAt ? entry.expireAt - clock : -1; // redis.call('PTTL', KEYS[1]) if (pttl < 0) entry.expireAt = clock + ttlSeconds * 1000; // redis.call('EXPIRE', KEYS[1], ARGV[2]) when missing } return added; // return added } throw new Error("fake client: unsupported EVAL script"); } case "PING": return "PONG"; default: throw new Error(`fake client: unsupported command ${cmd}`); } }; return run(); }, }; return client; } test("arming: HLEN counts DISTINCT sources across simulated workers and crosses the bar cluster-wide", async () => { const redis = createFakeRedis(); const workerA = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); const workerB = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); // 50 distinct sources land on worker A in the same 1s window. for (let i = 0; i < 50; i++) { const res = await workerA.armWindowBucket(1234, `192.0.2.${i}`, 2); assert.strictEqual(res.sharedAvailable, true); assert.strictEqual(res.uniqueSources, i + 1, "HLEN grows by exactly one per DISTINCT source (repeat hits do not inflate it)"); } // The same source hitting worker A repeatedly must not inflate the count. const repeat = await workerA.armWindowBucket(1234, "192.0.2.0", 2); assert.strictEqual(repeat.uniqueSources, 50, "exact unique counting: a repeat source is not counted twice"); // 50 more distinct sources land on worker B. for (let i = 0; i < 50; i++) { await workerB.armWindowBucket(1234, `198.51.100.${i}`, 2); } const fromA = await workerA.armWindowBucket(1234, "192.0.2.0", 2); const fromB = await workerB.armWindowBucket(1234, "192.0.2.0", 2); assert.strictEqual(fromA.uniqueSources, 100, "worker A sees the cluster-wide unique count"); assert.strictEqual(fromB.uniqueSources, 100, "worker B sees the same count — the arming bar is cluster-wide again"); // A different window bucket is a different hash. const nextWindow = await workerA.armWindowBucket(1235, "192.0.2.0", 2); assert.strictEqual(nextWindow.uniqueSources, 1, "each 1s window starts its own hash"); }); test("arming: the atomic EVAL arms the bucket TTL on each source's first insert, with the window+1s TTL", async () => { const redis = createFakeRedis(); const counters = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); for (let i = 0; i < 5; i++) await counters.armWindowBucket(777, `192.0.2.${i}`, 2); const armKey = `${LOGIN_ATTACK_ARM_KEY_PREFIX}777`; const evals = redis.log.filter((cmd) => cmd[0] === "EVAL" && cmd[3] === armKey); assert.strictEqual(evals.length, 5, "one atomic EVAL per arming hit — no separate HSETNX/EXPIRE round trips"); evals.forEach((cmd, i) => { assert.deepStrictEqual([cmd[1], cmd[2], cmd[4], cmd[5]], [LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA, "1", `192.0.2.${i}`, "2"], "every EVAL targets the arm namespace carrying the shipped script, numkeys=1, the source field and the window+1s TTL"); }); assert.strictEqual(redis.expireAtOf(armKey), 1_000_000 + 2_000, "the first insert armed the TTL through the atomic script (window+1s, no sweep)"); // A repeat source (field already present) must NOT re-arm the TTL: its // EVAL still runs (HSETNX answers 0 server-side) but the PTTL<0 branch is // behind the first-insert check. const logLen = redis.log.length; const repeat = await counters.armWindowBucket(777, "192.0.2.0", 2); assert.strictEqual(repeat.uniqueSources, 5, "exact unique counting is unchanged: a repeat source is not counted twice"); assert.strictEqual(redis.log.slice(logLen).filter((cmd) => cmd[0] === "EVAL" && cmd[3] === armKey).length, 1, "repeat hits from an already-counted source issue exactly ONE EVAL + the HLEN read"); redis.advance(500); await counters.armWindowBucket(777, "192.0.2.0", 2); assert.strictEqual(redis.expireAtOf(armKey), 1_000_000 + 2_000, "a live TTL is never refreshed by a repeat source (the re-arm is conditional, anchored to the first insert)"); }); test("arming self-healing: a bucket whose EXPIRE was lost re-arms its TTL on the next FIRST insert, keeping the count (the pre-fix hole is closed)", async () => { const redis = createFakeRedis(); const counters = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); const key = `${LOGIN_ATTACK_ARM_KEY_PREFIX}888`; await counters.armWindowBucket(888, "192.0.2.1", 2); assert.strictEqual(redis.expireAtOf(key), 1_000_000 + 2_000, "sanity: the first insert arms the TTL"); redis.advance(500); // The pre-fix bug state: the HSETNX landed server-side but its EXPIRE was // lost to a connection drop in the round-trip gap — the hash persists with // its fields and NO TTL (surviving Redis restarts under persistence), and // nothing ever re-sent EXPIRE, so the bucket grew without bound (harmless // to read — future requests derive NEW bucket keys — but never swept). redis.stripTtl(key); assert.strictEqual(redis.expireAtOf(key), null, "simulated: HSETNX landed, EXPIRE lost — no TTL"); // A repeat source does NOT heal (added === 0 skips the PTTL check — a live // TTL must never be refreshed) and preserves the unique count. const repeat = await counters.armWindowBucket(888, "192.0.2.1", 2); assert.strictEqual(repeat.uniqueSources, 1); assert.strictEqual(redis.expireAtOf(key), null, "a repeat source cannot re-arm (the PTTL<0 guard sits behind the first-insert branch)"); const healed = await counters.armWindowBucket(888, "192.0.2.2", 2); assert.strictEqual(healed.uniqueSources, 2, "the count is preserved — the heal re-arms the TTL, it does not reset the bucket"); assert.strictEqual(redis.expireAtOf(key), 1_000_500 + 2_000, "the next FIRST insert re-arms the missing TTL — a lost TTL self-heals instead of sticking forever"); }); test("brake: ONE atomic EVAL accumulates across simulated workers; the window-seconds TTL arms on the first hit and is never refreshed; namespaces distinct", async () => { const redis = createFakeRedis(); const workerA = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); const workerB = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); // Worker A records 25 hits from one source in armed mode. for (let i = 1; i <= 25; i++) { const res = await workerA.brakeHit("203.0.113.7", 3); assert.strictEqual(res.hits, i); } // Worker B (fresh process) records the 26th. const b = await workerB.brakeHit("203.0.113.7", 3); assert.strictEqual(b.hits, 26, "the cluster-wide count is what the threshold compares against"); const brakeKey = `${LOGIN_ATTACK_BRAKE_KEY_PREFIX}203.0.113.7`; const evals = redis.log.filter((cmd) => cmd[0] === "EVAL" && cmd[3] === brakeKey); assert.strictEqual(evals.length, 26, "every hit is exactly ONE EVAL against the brake key (no separate INCR/EXPIRE round trips)"); for (const cmd of evals) { assert.deepStrictEqual([cmd[1], cmd[2], cmd[4]], [LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA, "1", "3"], "each EVAL carries the shipped script, numkeys=1 and the 3s window TTL"); } assert.strictEqual(redis.expireAtOf(brakeKey), 1_000_000 + 3_000, "the first hit armed the TTL (window seconds) and the later hits did NOT refresh it — the fixed window stays anchored to the first hit"); }); test("brake self-healing: a key whose EXPIRE was lost re-arms its TTL on the next hit, keeping the count (the pre-fix hole is closed)", async () => { const redis = createFakeRedis(); const counters = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); const key = `${LOGIN_ATTACK_BRAKE_KEY_PREFIX}2001:db8::/56`; await counters.brakeHit("2001:db8::/56", 3); assert.strictEqual(redis.expireAtOf(key), 1_000_000 + 3_000, "sanity: the first hit arms the TTL"); redis.advance(500); // The pre-fix bug state: the INCR landed server-side but its EXPIRE was // lost to a connection drop in the round-trip gap — the key persists with // a count and NO TTL (surviving Redis restarts under persistence), and the // count>1 branch never re-sent EXPIRE, so the /56 stayed "aggressive" in // every future armed window. redis.stripTtl(key); assert.strictEqual(redis.expireAtOf(key), null, "simulated: INCR landed, EXPIRE lost — no TTL"); const healed = await counters.brakeHit("2001:db8::/56", 3); assert.strictEqual(healed.hits, 2, "the count is preserved — the heal re-arms the TTL, it does not reset the window"); assert.strictEqual(redis.expireAtOf(key), 1_000_500 + 3_000, "the next hit re-arms the missing TTL — a lost TTL self-heals instead of sticking forever"); // A STILL-LIVE TTL is never refreshed: the re-arm condition is PTTL < 0 // only, so the fixed window stays anchored to the first hit. redis.advance(1000); const live = await counters.brakeHit("2001:db8::/56", 3); assert.strictEqual(live.hits, 3); assert.strictEqual(redis.expireAtOf(key), 1_000_500 + 3_000, "a live TTL is not refreshed on later hits (the re-arm is conditional, not a sliding window)"); }); test("latch: SET...EX mirrors the TTL, any worker's GET sees it, expiry and DEL clear it cluster-wide, sweep empties it", async () => { const redis = createFakeRedis(); const workerA = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); const workerB = createLoginSharedCounters({ clientOf: () => redis, readyOf: () => redis.ready }); assert.strictEqual(await workerA.latchSet("2001:db8::/56", 600), true); const setCmd = redis.log.find((cmd) => cmd[0] === "SET"); assert.deepStrictEqual(setCmd, ["SET", `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}2001:db8::/56`, "1", "EX", "600"], "the latch is a short-TTL SET under its own namespace, TTL mirrored from the caller"); assert.strictEqual(redis.expireAtOf(`${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}2001:db8::/56`), 1_000_000 + 600_000); const seenByB = await workerB.latchGet("2001:db8::/56"); assert.deepStrictEqual(seenByB, { sharedAvailable: true, armed: true }, "a worker that never armed the latch sees it cluster-wide"); redis.advance(601_000); const expired = await workerB.latchGet("2001:db8::/56"); assert.strictEqual(expired.armed, false, "the latch expires with the mirrored TTL (the local map's TTL behavior)"); await workerA.latchSet("2001:db8::/56", 600); await workerA.latchDel("2001:db8::/56"); const cleared = await workerB.latchGet("2001:db8::/56"); assert.strictEqual(cleared.armed, false, "DEL spans the cluster (solve/success clears everywhere)"); await workerA.latchSet("k1", 600); await workerB.latchSet("k2", 600); assert.strictEqual(await workerA.latchClearAll(), true); assert.strictEqual((await workerA.latchGet("k1")).armed, false); assert.strictEqual((await workerB.latchGet("k2")).armed, false, "the live-disable sweep empties the namespace"); }); test("fail posture: Redis down / client absent / not ready → best-effort unavailable, never a rejection; the latch sweeps refuse too", async () => { const down = createLoginSharedCounters({ clientOf: () => createFakeRedis({ fail: true }), readyOf: () => true }); const arm = await down.armWindowBucket(1, "192.0.2.1", 2); assert.deepStrictEqual(arm, { sharedAvailable: false, uniqueSources: 0 }); const brake = await down.brakeHit("192.0.2.1", 3); assert.deepStrictEqual(brake, { sharedAvailable: false, hits: 0 }); assert.strictEqual(await down.latchSet("k", 600), false); assert.deepStrictEqual(await down.latchGet("k"), { sharedAvailable: false, armed: false }); assert.strictEqual(await down.latchClearAll(), false); const absent = createLoginSharedCounters({ clientOf: () => null, readyOf: () => false }); assert.deepStrictEqual(await absent.armWindowBucket(1, "k", 2), { sharedAvailable: false, uniqueSources: 0 }); assert.deepStrictEqual(await absent.latchGet("k"), { sharedAvailable: false, armed: false }); const throwingClientOf = createLoginSharedCounters({ clientOf: () => { throw new Error("boom"); }, readyOf: () => true }); await assert.doesNotReject(() => throwingClientOf.latchGet("k")); assert.deepStrictEqual(await throwingClientOf.latchGet("k"), { sharedAvailable: false, armed: false }); const notReady = createLoginSharedCounters({ clientOf: () => createFakeRedis(), readyOf: () => false }); assert.deepStrictEqual(await notReady.brakeHit("k", 3), { sharedAvailable: false, hits: 0 }); }); test("fail posture: a hung Redis dial is bounded by the hard op timeout and resolves to the fallback signal", async () => { const hung = createLoginSharedCounters({ clientOf: () => createFakeRedis({ hang: true }), readyOf: () => true, opTimeoutMs: 25, }); const started = Date.now(); const res = await hung.armWindowBucket(1, "192.0.2.1", 2); assert.deepStrictEqual(res, { sharedAvailable: false, uniqueSources: 0 }, "the pre-auth path cannot hang on Redis"); assert.ok(Date.now() - started < 2000, "the timeout is hard, not the server's own dial timeout"); }); // --------------------------------------------------------------------------- // Section D — behavior pins on the SHIPPED index.js function bodies: the // union semantics across simulated workers, and the Redis-down fallback // posture (byte-for-byte the pre-fix behavior). // --------------------------------------------------------------------------- // Build one simulated worker from the shipped markLoginTraffic / // isLoginUnderAttack / isAggressiveLoginIp bodies, backed by a real // createLoginSharedCounters over the given (fake) client. function buildDetectorWorker({ client, ready = true, uniqueIps, ipMax, holdMs = 60000, windowMs = 1000, ipWindowMs = 3000, mapMax = 10000 }) { let clock = 1_000_000; const Date = { now: () => clock }; const loginAttackIps = new Map(); const loginAttackIpHits = new Map(); const factory = new Function( "loginAttackIps", "LOGIN_ATTACK_WINDOW_MS", "LOGIN_MAP_MAX_SIZE", "LOGIN_ATTACK_UNIQUE_IPS", "LOGIN_ATTACK_HOLD_MS", "loginAttackIpHits", "LOGIN_ATTACK_IP_WINDOW_MS", "LOGIN_ATTACK_IP_MAX", "Date", "loginSharedCounters", `let loginUnderAttackUntil = 0; ${markLoginTrafficSource} ${isLoginUnderAttackSource} ${isAggressiveLoginIpSource} return { markLoginTraffic, isLoginUnderAttack, isAggressiveLoginIp };` ); const harness = factory( loginAttackIps, windowMs, mapMax, uniqueIps, holdMs, loginAttackIpHits, ipWindowMs, ipMax, Date, createLoginSharedCounters({ clientOf: () => client, readyOf: () => ready }) ); return { ...harness, localArmingMap: loginAttackIps, advance: (ms) => { clock += ms; }, }; } test("arming crosses workers: 50 sources on EACH of two workers arm global attack mode on both (the ~N× bar is undone)", async () => { const redis = createFakeRedis(); const workerA = buildDetectorWorker({ client: redis, uniqueIps: 100 }); const workerB = buildDetectorWorker({ client: redis, uniqueIps: 100 }); for (let i = 0; i < 50; i++) await workerA.markLoginTraffic(`192.0.2.${i}`); for (let i = 0; i < 50; i++) await workerB.markLoginTraffic(`198.51.100.${i}`); assert.strictEqual(workerA.localArmingMap.size, 50, "each worker's local map holds only its own share"); // B's 50th source crosses the cluster-wide bar during B's own call. assert.ok(workerB.isLoginUnderAttack(), "worker B arms: union(local 50, cluster-wide 100) >= 100, seen live"); // Worker A's last call predated the crossing; the middleware re-runs the // detector on EVERY request, so A's very next request re-evaluates against // the shared count and arms. A repeat source keeps the unique count at 100. await workerA.markLoginTraffic("192.0.2.0"); assert.ok(workerA.isLoginUnderAttack(), "worker A arms on its next request from the shared count alone"); assert.ok(workerA.localArmingMap.size < 100, "the LOCAL map alone never reached the bar — pre-fix this never armed"); }); test("arming fail posture: with Redis down the same 50/50 split must NOT arm (the pre-fix local-only behavior)", async () => { const redis = createFakeRedis({ fail: true }); const workerA = buildDetectorWorker({ client: redis, uniqueIps: 100 }); const workerB = buildDetectorWorker({ client: redis, uniqueIps: 100 }); for (let i = 0; i < 50; i++) await workerA.markLoginTraffic(`192.0.2.${i}`); for (let i = 0; i < 50; i++) await workerB.markLoginTraffic(`198.51.100.${i}`); assert.ok(!workerA.isLoginUnderAttack(), "Redis down: only local counts count, exactly as before the mirror"); assert.ok(!workerB.isLoginUnderAttack()); }); test("arming fail posture: with Redis down a single worker arming locally still works (threshold semantics unchanged)", async () => { const redis = createFakeRedis({ fail: true }); const worker = buildDetectorWorker({ client: redis, uniqueIps: 3 }); await worker.markLoginTraffic("192.0.2.1"); await worker.markLoginTraffic("192.0.2.99"); assert.ok(!worker.isLoginUnderAttack(), "two sources stay under the bar of 3"); await worker.markLoginTraffic("192.0.2.200"); assert.ok(worker.isLoginUnderAttack(), "the local map alone arms at the threshold — the fallback is the sole mechanism"); }); test("brake crosses workers: the 26th cluster-wide hit trips a worker that saw ONE local hit (per-worker thresholds no longer multiply)", async () => { const redis = createFakeRedis(); const workerA = buildDetectorWorker({ client: redis, uniqueIps: 100, ipMax: 25 }); const workerB = buildDetectorWorker({ client: redis, uniqueIps: 100, ipMax: 25 }); // Worker A absorbs 25 hits from one source (all under the brake). for (let i = 1; i <= 25; i++) { assert.ok(!(await workerA.isAggressiveLoginIp("203.0.113.7")), `worker A hit ${i} stays under`); } // Worker B has an empty local map but shares the cluster-wide counter. assert.ok(await workerB.isAggressiveLoginIp("203.0.113.7"), "worker B refuses: union(local 1, shared 26) > 25 — pre-fix this passed on ~1/N of workers"); }); test("brake fail posture: with Redis down the local sliding window is the sole mechanism (25 under, 26th trips)", async () => { const redis = createFakeRedis({ fail: true }); const worker = buildDetectorWorker({ client: redis, uniqueIps: 100, ipMax: 25 }); for (let i = 1; i <= 25; i++) { assert.ok(!(await worker.isAggressiveLoginIp("203.0.113.7")), `hit ${i} stays under (local only)`); } assert.ok(await worker.isAggressiveLoginIp("203.0.113.7"), "the 26th local hit trips exactly as pre-fix"); }); test("gate reader: local map first (the fallback verdict), then the stashed shared verdict; undefined stash degrades to local-only", () => { const factory = new Function( "isLoginCaptchaGateArmedForIp", `${gateRequestReaderSource} return isLoginCaptchaGateArmedForRequest;` ); const localArmed = new Map([["203.0.113.7", Date.now()]]); const reader = factory((ipKey) => localArmed.has(ipKey)); const req = { loginCaptchaGateSharedVerdict: true }; assert.strictEqual(reader(req, "203.0.113.7"), true, "local hit answers true without the stash"); assert.strictEqual(reader(req, "203.0.113.9"), true, "local miss + stashed shared verdict true"); assert.strictEqual(reader({}, "203.0.113.10"), false, "local miss + stash false"); assert.strictEqual(reader({ loginCaptchaGateSharedVerdict: false }, "203.0.113.7"), true, "the local verdict wins even when the stash says false"); assert.strictEqual(reader({}, "203.0.113.11"), false, "an UNDEFINED stash (middleware skipped it) degrades to the local-only verdict"); assert.strictEqual(reader({ loginCaptchaGateSharedVerdict: true }, ""), false, "an empty key never arms"); }); // --------------------------------------------------------------------------- // Section E — middleware behavior pins: the stash contract, the refusal // shape, and the Express-4 async rejection contract. // --------------------------------------------------------------------------- function buildMiddlewareHarnessForShared({ armed = false, captchaEnabled = false, sharedVerdict = async () => false, markTraffic = async () => {}, isAggressive = async () => false, ipWindowMs = 3000, }) { return new Function( "ipKeyGenerator", "getRequestIp", "markLoginTraffic", "isLoginUnderAttack", "isAggressiveLoginIp", "sendLoginRateLimited", "securityLog", "ANY_CAPTCHA_ENABLED", "isLoginCaptchaGateArmedForIpShared", "LOGIN_ATTACK_IP_WINDOW_MS", "revalidateCaptchaConfigFromDisk", `${middlewareSource} return loginAttackMiddleware;` )( (ip) => ip, // keys are pre-derived by the caller (req) => req.sourceIp, markTraffic, () => armed, isAggressive, // adpanel:login-retry-after — the Retry-After header moved INTO the shared // responder (no parallel setHeader in the middleware), so this stub // mirrors the real responder's header contract: it sets Retry-After from // the responder's explicit argument. The Retry-After assertions below now // pin that the middleware passes its brake window through — an argument // DERIVED from the injected LOGIN_ATTACK_IP_WINDOW_MS inside the shipped // body (conscious pin update: the hard-coded 5 became // Math.ceil(window/1000), so the default header changes 5→3 — today it // overstates; after the fix it is honest). (req, res, log, reason, retryAfterSeconds) => { res.refusedReason = reason; res.setHeader("Retry-After", String(retryAfterSeconds)); }, () => {}, captchaEnabled, sharedVerdict, ipWindowMs, // adpanel:config-stat-revalidation — conscious harness update (additive): // the shipped body revalidates the hot-swapped captcha config from .env // at the top of its try block; a no-op is injected (the revalidation's // own behavior is pinned in tests/config-stat-revalidation-consumers.test.js). () => {} ); } test("middleware: the shared gate verdict is stashed once per request for the sync readers", async () => { let sharedReads = 0; const middleware = buildMiddlewareHarnessForShared({ captchaEnabled: true, sharedVerdict: async () => { sharedReads += 1; return true; }, }); const req = { sourceIp: "192.0.2.5" }; const res = { locals: {}, setHeader() {} }; await middleware(req, res, () => {}); assert.strictEqual(req.loginCaptchaGateSharedVerdict, true, "the stash carries the shared verdict"); assert.strictEqual(sharedReads, 1, "exactly ONE shared resolution per request (the readers re-read the stash, not Redis)"); }); test("middleware: with captcha disabled the stash is never resolved (zero extra ops on the disabled surface)", async () => { let sharedReads = 0; const middleware = buildMiddlewareHarnessForShared({ captchaEnabled: false, sharedVerdict: async () => { sharedReads += 1; return true; }, }); const req = { sourceIp: "192.0.2.5" }; const res = { locals: {}, setHeader() {} }; await middleware(req, res, () => {}); assert.strictEqual(req.loginCaptchaGateSharedVerdict, undefined, "the sync readers degrade to the local verdict"); assert.strictEqual(sharedReads, 0); }); test("middleware: disarmed mode never refuses even when the shared brake would trip (brake consulted only under attack)", async () => { let brakeCalls = 0; const middleware = buildMiddlewareHarnessForShared({ armed: false, isAggressive: async () => { brakeCalls += 1; return true; }, }); const res = { locals: {}, setHeader() {} }; let passed = 0; await middleware({ sourceIp: "192.0.2.5" }, res, () => { passed += 1; }); assert.strictEqual(passed, 1, "disarmed mode passes"); assert.strictEqual(brakeCalls, 0, "the brake (and its Redis ops) never run outside attack mode"); }); test("middleware: armed mode refuses through the shared responder with the Retry-After header (shape unchanged)", async () => { const middleware = buildMiddlewareHarnessForShared({ armed: true, isAggressive: async () => true, }); const res = { locals: {}, setHeader(name, value) { this.headers = this.headers || {}; this.headers[name] = value; } }; let passed = 0; await middleware({ sourceIp: "192.0.2.5" }, res, () => { passed += 1; }); assert.strictEqual(passed, 0, "the aggressive source is refused"); assert.strictEqual(res.refusedReason, "Login attack-mode rate limit exceeded"); // adpanel:login-retry-after — conscious pin update: the middleware derives // its Retry-After argument from LOGIN_ATTACK_IP_WINDOW_MS (shipped default // 3000 ms → 3 s); the old hard-coded 5 overstated the window the brake // actually enforces. The derivation itself is pinned by the tuned-window // case below. assert.strictEqual(res.headers["Retry-After"], "3"); }); test("middleware: the brake's Retry-After derives from the tuned window, not a hard-coded value", async () => { const middleware = buildMiddlewareHarnessForShared({ armed: true, isAggressive: async () => true, ipWindowMs: 10000, }); const res = { locals: {}, setHeader(name, value) { this.headers = this.headers || {}; this.headers[name] = value; } }; await middleware({ sourceIp: "192.0.2.5" }, res, () => {}); assert.strictEqual(res.headers["Retry-After"], "10", "an env-tuned LOGIN_ATTACK_IP_WINDOW_MS must travel as the Retry-After (Math.ceil(window/1000)) — the header tracks the window the brake enforces"); }); test("middleware: an unexpected async failure surfaces through next(err) — Express 4 must never see a rejection", async () => { const middleware = buildMiddlewareHarnessForShared({ markTraffic: async () => { throw new Error("boom"); }, }); let forwarded = null; let passed = 0; await middleware({ sourceIp: "192.0.2.5" }, { locals: {}, setHeader() {} }, (err) => { if (err) forwarded = err; else passed += 1; }); assert.ok(forwarded instanceof Error, "the throw is forwarded to the error handler, not leaked as a rejection"); assert.strictEqual(forwarded.message, "boom"); });