258 lines
12 KiB
JavaScript
258 lines
12 KiB
JavaScript
"use strict";
|
||
|
||
// adpanel:detector-cluster-shared — cluster-shared counters for the /login
|
||
// defense-in-depth layers (the attack detector's arming map + armed-mode
|
||
// brake, and the pre-auth captcha-gate IP latch). The constraint these
|
||
// helpers exist for: defense-in-depth layers must not silently fragment
|
||
// across PM2 cluster workers (ecosystem INSTANCES = cores−2) — per-process
|
||
// Maps make each worker see ~1/N of the traffic, so the ≥100-unique-source
|
||
// arming bar rises ~N×, the 25-hit/3s brake threshold effectively
|
||
// multiplies, and the captcha latch arms on only the workers that saw the
|
||
// credential failures (~1/N captcha enforcement). Every counter here rides
|
||
// the session Redis store (the client index.js already maintains) with
|
||
// short-TTL atomic ops and ONE key namespace per mechanism:
|
||
//
|
||
// arming — adpanel:attack-arm:<windowBucket> (HASH: field per source,
|
||
// ONE atomic HSETNX + missing-TTL re-arm script, see
|
||
// LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA below; HLEN = unique
|
||
// sources in the current window bucket)
|
||
// brake — adpanel:attack-brake:<sourceKey> (STRING counter: ONE atomic
|
||
// INCR + missing-TTL re-arm script, see
|
||
// LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA below; fixed-window
|
||
// approximation of the detector's sliding window)
|
||
// latch — adpanel:login-captcha-latch:<sourceKey> (STRING "1", SET EX
|
||
// mirroring the latch's LOGIN_CAPTCHA_GATE_TTL_MS, DEL on
|
||
// solve/success, SCAN sweep on the live-disable clear)
|
||
//
|
||
// Fail posture (must be preserved by every caller): these counters are
|
||
// defense-in-depth, NOT auth controls, and their pre-fix behavior was
|
||
// purely process-local. Every op is best-effort — gated on the caller's
|
||
// readiness flag, bounded by a hard timeout so the pre-auth /login path
|
||
// can never hang on Redis, never rejecting — and resolves to a
|
||
// "shared unavailable" result on ANY failure. Callers keep their
|
||
// per-process Maps as the fallback (write-through), so with Redis down
|
||
// both mechanisms behave exactly as before this module existed.
|
||
//
|
||
// Redis cost: 2-3 short-TTL ops per /login request (the shared limiter and
|
||
// throttle stores already pay Redis ops on the same path — acceptable);
|
||
// zero extra ops when Redis is unavailable.
|
||
|
||
const DEFAULT_OP_TIMEOUT_MS = 250;
|
||
|
||
// Key namespaces — one per mechanism, distinct from every limiter prefix
|
||
// (rate-limit-redis "arl:*", sessions "adpanel:sess:*", throttle counters).
|
||
const LOGIN_ATTACK_ARM_KEY_PREFIX = "adpanel:attack-arm:";
|
||
const LOGIN_ATTACK_BRAKE_KEY_PREFIX = "adpanel:attack-brake:";
|
||
const LOGIN_CAPTCHA_LATCH_KEY_PREFIX = "adpanel:login-captcha-latch:";
|
||
|
||
// adpanel:detector-cluster-shared — the brake counter's ONE atomic op. INCR
|
||
// and the TTL-ensure run server-side as a single script, mirroring the PTTL
|
||
// re-arm discipline of rate-limit-redis' increment script (the throttle
|
||
// stores): EXPIRE lands only when PTTL reports NO TTL (never on a live one),
|
||
// so the fixed-window approximation keeps its documented semantics — the TTL
|
||
// stays anchored to the first hit — while a LOST TTL self-heals on the next
|
||
// hit. The lost-TTL state was a real hole in the pre-fix two-command shape
|
||
// (INCR, then EXPIRE only when INCR returned 1): an EXPIRE dropped to a
|
||
// connection error in the round-trip gap left the key with NO TTL, and the
|
||
// count>1 branch never re-sent EXPIRE, so the key never expired and its /56
|
||
// stayed "aggressive" for every future armed window — a state that survives
|
||
// Redis restarts under persistence (a persisted key without TTL never
|
||
// expires). A lost TTL must self-heal: the pre-fix in-memory brake was
|
||
// self-healing by timestamp filter (entries pruned on read); the shared key
|
||
// must be too. Plain EVAL with the body inline (like the remember-registry
|
||
// scripts in index.js), NOT EVALSHA: this module's best-effort send() has no
|
||
// SCRIPT LOAD/NOSCRIPT self-heal machinery, so after a Redis restart flushed
|
||
// the script cache, every EVALSHA would silently resolve to the per-process
|
||
// Map fallback forever.
|
||
const LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA = [
|
||
"local v = redis.call('INCR', KEYS[1])",
|
||
"if redis.call('PTTL', KEYS[1]) < 0 then",
|
||
" redis.call('EXPIRE', KEYS[1], ARGV[1])",
|
||
"end",
|
||
"return v",
|
||
].join("\n");
|
||
|
||
// adpanel:attack-arm-atomic-ttl — the arm bucket's ONE atomic op. HSETNX and
|
||
// the TTL-ensure run server-side as a single script, mirroring the PTTL
|
||
// re-arm discipline of the brake script above (and rate-limit-redis'
|
||
// increment scripts): EXPIRE lands only when PTTL reports NO TTL (never on a
|
||
// live one), so the bucket TTL stays anchored to its first insert while a
|
||
// LOST TTL self-heals on the next first-insert. The lost-TTL state was the
|
||
// same real hole the brake's pre-fix two-command shape had (HSETNX, then
|
||
// EXPIRE only when it returned 1): an EXPIRE dropped to a connection error
|
||
// in the round-trip gap stranded a TTL-less adpanel:attack-arm:* hash —
|
||
// harmless by construction (future requests derive NEW bucket keys, so a
|
||
// stuck old bucket is never read again) but unbounded slow growth with no
|
||
// sweep, and it survives Redis restarts under persistence. Plain EVAL with
|
||
// the body inline, NOT EVALSHA: same rationale as the brake script — this
|
||
// module's best-effort send() has no SCRIPT LOAD/NOSCRIPT self-heal
|
||
// machinery, so after a Redis restart flushed the script cache, every
|
||
// EVALSHA would silently resolve to the per-process Map fallback forever.
|
||
const LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA = [
|
||
"local added = redis.call('HSETNX', KEYS[1], ARGV[1], '1')",
|
||
"if added == 1 then",
|
||
" if redis.call('PTTL', KEYS[1]) < 0 then",
|
||
" redis.call('EXPIRE', KEYS[1], ARGV[2])",
|
||
" end",
|
||
"end",
|
||
"return added",
|
||
].join("\n");
|
||
|
||
function normalizeTtlSeconds(ttlSeconds) {
|
||
const n = Math.floor(Number(ttlSeconds));
|
||
return Number.isFinite(n) && n >= 1 ? n : 1;
|
||
}
|
||
|
||
function createLoginSharedCounters(options = {}) {
|
||
const clientOf = options.clientOf || (() => null);
|
||
const readyOf = options.readyOf || (() => false);
|
||
const opTimeoutMs = Number.isFinite(Number(options.opTimeoutMs)) && Number(options.opTimeoutMs) >= 1
|
||
? Number(options.opTimeoutMs)
|
||
: DEFAULT_OP_TIMEOUT_MS;
|
||
const logger = options.logger && typeof options.logger.debug === "function" ? options.logger : console;
|
||
|
||
// The ONE Redis dial for this module. Resolves to null (never rejects,
|
||
// never hangs longer than opTimeoutMs) on: no client, not ready, dial
|
||
// error, timeout, or any rejection. The null result is the caller's
|
||
// signal to fall back to its per-process Map.
|
||
async function send(args) {
|
||
let client = null;
|
||
try {
|
||
client = clientOf();
|
||
} catch (err) {
|
||
logger.debug("[login-shared] clientOf failed:", err?.message || err);
|
||
return null;
|
||
}
|
||
if (!client || typeof client.sendCommand !== "function" || !readyOf()) return null;
|
||
let op;
|
||
try {
|
||
op = client.sendCommand(args.map((arg) => String(arg)));
|
||
} catch (err) {
|
||
logger.debug("[login-shared] Redis command error:", err?.message || err);
|
||
return null;
|
||
}
|
||
// The race below may abandon this promise on timeout; pre-attach a
|
||
// rejection handler so a late connection error is never unhandled.
|
||
op.catch(() => {});
|
||
let timer = null;
|
||
try {
|
||
return await Promise.race([
|
||
op,
|
||
new Promise((resolve) => {
|
||
timer = setTimeout(() => resolve(null), opTimeoutMs);
|
||
}),
|
||
]);
|
||
} catch (err) {
|
||
logger.debug("[login-shared] Redis op failed:", err?.message || err);
|
||
return null;
|
||
} finally {
|
||
if (timer) clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
// adpanel:attack-arm-atomic-ttl — Arming: exact unique-source count for one
|
||
// window bucket. HSETNX adds the source's field only when absent (1 = newly
|
||
// added), so HLEN is the count of DISTINCT sources that reached this bucket
|
||
// — the cluster-wide equivalent of the detector map's size. The first
|
||
// insert and its EXPIRE are ONE atomic script (LOGIN_ATTACK_ARM_HSETNX_
|
||
// EXPIRE_LUA above): a lost EXPIRE can never strand a TTL-less arm bucket,
|
||
// and the PTTL<0 guard self-heals one on the next first-insert (see the
|
||
// script's comment). The bucket key self-expires (no sweep); the pre-fix
|
||
// TTL-less residue was harmless by construction — future requests derive
|
||
// NEW bucket keys, so a stuck old bucket is never read again — but it was
|
||
// unbounded slow growth, which the single atomic op removes entirely.
|
||
async function armWindowBucket(bucket, sourceKey, ttlSeconds) {
|
||
const key = `${LOGIN_ATTACK_ARM_KEY_PREFIX}${String(bucket)}`;
|
||
const added = await send([
|
||
"EVAL",
|
||
LOGIN_ATTACK_ARM_HSETNX_EXPIRE_LUA,
|
||
"1",
|
||
key,
|
||
String(sourceKey),
|
||
String(normalizeTtlSeconds(ttlSeconds)),
|
||
]);
|
||
if (added === null) return { sharedAvailable: false, uniqueSources: 0 };
|
||
const len = await send(["HLEN", key]);
|
||
if (len === null) return { sharedAvailable: false, uniqueSources: 0 };
|
||
return { sharedAvailable: true, uniqueSources: Number(len) };
|
||
}
|
||
|
||
// Armed-mode brake: per-source hit counter over a fixed window, written by
|
||
// the ONE atomic INCR + missing-TTL re-arm script above (LOGIN_ATTACK_
|
||
// BRAKE_INCR_EXPIRE_LUA — see its comment for why the TTL self-heals). The
|
||
// fixed window is the documented approximation of the detector's sliding 3s
|
||
// window — a burst straddling two bucket boundaries can spread its hits,
|
||
// acceptable because the brake only shapes traffic DURING armed attack mode
|
||
// while the Redis-shared login throttle remains the primary per-source
|
||
// bound.
|
||
async function brakeHit(sourceKey, ttlSeconds) {
|
||
const key = `${LOGIN_ATTACK_BRAKE_KEY_PREFIX}${String(sourceKey)}`;
|
||
const count = await send([
|
||
"EVAL",
|
||
LOGIN_ATTACK_BRAKE_INCR_EXPIRE_LUA,
|
||
"1",
|
||
key,
|
||
String(normalizeTtlSeconds(ttlSeconds)),
|
||
]);
|
||
if (count === null) return { sharedAvailable: false, hits: 0 };
|
||
return { sharedAvailable: true, hits: Number(count) };
|
||
}
|
||
|
||
// Captcha-gate latch: SET ... EX mirroring the local latch's TTL.
|
||
async function latchSet(sourceKey, ttlSeconds) {
|
||
const key = `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}${String(sourceKey)}`;
|
||
const reply = await send(["SET", key, "1", "EX", String(normalizeTtlSeconds(ttlSeconds))]);
|
||
return reply !== null;
|
||
}
|
||
|
||
// Captcha-gate latch read: true/false when the shared store answered,
|
||
// sharedAvailable false when it did not (caller falls back to its map).
|
||
async function latchGet(sourceKey) {
|
||
const key = `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}${String(sourceKey)}`;
|
||
const reply = await send(["GET", key]);
|
||
if (reply === null) return { sharedAvailable: false, armed: false };
|
||
return { sharedAvailable: true, armed: true };
|
||
}
|
||
|
||
async function latchDel(sourceKey) {
|
||
const key = `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}${String(sourceKey)}`;
|
||
await send(["DEL", key]);
|
||
}
|
||
|
||
// Live-disable clear (captcha switched off in settings): sweep every
|
||
// shared latch. Rare admin path, so the SCAN cost is acceptable; every
|
||
// op is best-effort and the latch is inert while captcha is off anyway
|
||
// (every gate read is ANDed with the captcha-enabled flag).
|
||
async function latchClearAll() {
|
||
let cursor = "0";
|
||
for (;;) {
|
||
const reply = await send(["SCAN", cursor, "MATCH", `${LOGIN_CAPTCHA_LATCH_KEY_PREFIX}*`, "COUNT", "500"]);
|
||
if (!Array.isArray(reply)) return false;
|
||
cursor = String(reply[0] || "0");
|
||
const keys = Array.isArray(reply[1]) ? reply[1] : [];
|
||
if (keys.length) {
|
||
await send(["DEL", ...keys.map((k) => String(k))]);
|
||
}
|
||
if (cursor === "0") return true;
|
||
}
|
||
}
|
||
|
||
return {
|
||
armWindowBucket,
|
||
brakeHit,
|
||
latchSet,
|
||
latchGet,
|
||
latchDel,
|
||
latchClearAll,
|
||
};
|
||
}
|
||
|
||
module.exports = {
|
||
createLoginSharedCounters,
|
||
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,
|
||
};
|