"use strict"; // adpanel:login-audit-durable — ONE durable, operator-owned record per // successful login. Before this module, a completed login left no artifact an // attacker could not destroy: securityLog is console-only, and the only // persistent trace was the remember-login registry entry in Redis, which the // attacker's own logout or password change revokes. This module owns the whole // login-audit responsibility: the canonical table shape, the belt-and-suspenders // guarded CREATE, the retention prune, and the ONE insert all authentication // completion paths (POST /login password success, completePendingCaptchaLogin, // and the remember-cookie restore) call post-bind/post-save. // // adpanel:failed-login-audit — the same recorder also owns the durable // FAILED-login record (fresh audit F3: failed logins left only in-memory / // Redis throttle counters and console securityLog — no forensic row an // attacker could not outlive). The standing-block refusals // (arm:id-account-blocked / arm:id-totp-blocked — each one already consumed // an ADMITTED fold-only reservation, so their rate IS the admission budget) // ALWAYS record; ordinary credential failures are SAMPLED deterministically // 1-in-20. The never-gates / never-rejects / post-decision-position contract // below is byte-identical for the failure recorder. // // Non-negotiable contract (why login callers may fire-and-forget): // 1. The audit NEVER gates the login and NEVER adds DB latency to it — the // insert is not awaited on the login critical path. recordSuccessfulLoginAudit // therefore must NEVER reject: every failure path is caught and warned. // 2. Failure is fail-open and LOUD: a failed insert warns and the login // response is unchanged. The audit must not become a login-DoS surface // (a downed/blocked audit sink must not produce a wave of login 500s). // 3. Call-site position is fixed: after the session is bound, immediately // before the success response — by then every fallible step has already // returned, so the call cannot change the wire outcome, and its failure // semantics cannot leak into the response body or status. The failure // recorder mirrors this: it is called after the failure decision // (finalizeCredentialFailure), immediately before the uniform 400. // 4. Write-volume bound (adpanel:failed-login-audit — an attack must not // amplify DB writes): failure rows are bounded by the throttle budgets // themselves. Ordinary failures record only after an ADMITTED credential // reservation (≤ LOGIN_IP_MAX_FAILURES admitted per source per window — // default 10/10min), and only every 20th of those records (deterministic // rolling counter) — ≈0.05 × an already budget-bounded rate. The // standing-block refusals record always but their admission is the same // budget (~10/source/10min). NEVER recorded: pre-row 429 refusals and // reservation refusals (honest throttles — already visible via // Retry-After), honeypot/non-browser 403s (attacker-known state, // unbounded), CSRF/botProof failures (pre-credential). // // Dependency direction is one-way: index.js requires this module; this module // requires only utils/*. The `db` handle and the trusted-proxy-aware IP // resolver arrive through the injected `deps` object (the pattern of // utils/login-session-bind.js). // The canonical table shape. mysql-schema.sql carries the byte-identical // CREATE TABLE IF NOT EXISTS (fresh installs + the every-boot schema replay // in db.ensureSchema); this guarded DDL is the belt-and-suspenders copy for a // schema replay that has not landed (the pending_session_revocations rule: // the shape is owned by the schema file, this copy must stay in lockstep — // pinned by tests/login-audit-durable.test.js). No comments inside the DDL: // the schema parser splits on ";" and lockstep comparison is line-based. // // Column notes: email is the RESOLVED account's canonical email from the user // row (not the submitted form value — the audit records who logged in, not // what was typed) for SUCCESS rows. A FAILED row (adpanel:failed-login-audit) // inverts that deliberately: it stores the SUBMITTED string, bounded — // trimmed, control chars stripped, ≤254 chars (the RFC 5321 operational // limit, inside the column's 255) — because the forensic point is exactly // what the attacker typed (collation variants included, which may resolve to // no row at all); it is never resolved to a canonical row and never logged to // console raw. A failed row's user_id is the 0 sentinel (no resolved account; // the column is NOT NULL and 0 needs no schema change). user_agent is the // 255-char bound the panel's other audit surfaces use. method is a closed // VARCHAR set (only the whitelisted methods below may be recorded); an ENUM // was rejected deliberately — a further authentication completion path would // then need an ENUM-widen migration before it could record anything, and the // whitelist below already enforces the closed set (the remember-restore and // failed additions needed no migration — the VARCHAR choice paying off // exactly as intended). created_at is server-side // (INSERT supplies no timestamp) so // the row's clock is the database's, not the application's. const LOGIN_AUDIT_DDL = ` CREATE TABLE IF NOT EXISTS login_audit ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT UNSIGNED NOT NULL, email VARCHAR(255) NOT NULL, ip VARCHAR(64) NOT NULL DEFAULT '', user_agent VARCHAR(255) NOT NULL DEFAULT '', method VARCHAR(32) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_login_audit_user_created (user_id, created_at), KEY idx_login_audit_created (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`; // The closed set of authentication completion methods. A successful login // arrives either through the POST /login password path, through the // captcha-completion finalize of a pending login, or through the // remember-cookie restore (restoreRememberedLogin — the silent re-issue of a // valid remember credential is itself a full authentication event and was // invisible to forensics before it was whitelisted here). "failed" is added // CONSCIOUSLY (adpanel:failed-login-audit): the failure recorder below writes // method:'failed' rows under the write-volume bound documented in the // contract block; the success recorder never passes it (its call sites are // pinned to the three completion literals). Anything else is a bug and is // warned + skipped, never written. const LOGIN_AUDIT_METHODS = new Set(["password", "captcha-completion", "remember-restore", "failed"]); // adpanel:failed-login-audit — the method the failure recorder writes, the // failure reasons that ALWAYS record (the standing-block refusals: each one // already consumed an ADMITTED fold-only reservation, so recording them adds // at most one row per admitted reservation — their rate IS the throttle // budget), and the deterministic sample denominator for every other failure // reason. The ALWAYS set holds only the two fixed debugLabel literals the // login handler refuses with — no free text, no attacker-controlled string // ever reaches a recording decision (an unknown reason simply samples). const FAILED_LOGIN_AUDIT_METHOD = "failed"; const FAILED_LOGIN_AUDIT_ALWAYS_REASONS = new Set(["arm:id-account-blocked", "arm:id-totp-blocked"]); const FAILED_LOGIN_AUDIT_SAMPLE_ONE_IN = 20; // Control characters (C0 + DEL) never belong in a forensic row or a log line: // the submitted email and the reason are attacker-influenced strings, so they // are stripped before bounding. const LOGIN_AUDIT_CONTROL_CHARS = /[\u0000-\u001F\u007F]/g; // Retention: rows older than LOGIN_AUDIT_RETENTION_DAYS are pruned at boot. // Fixed (not env-tunable) on purpose — an operator lowering this to 0 must // not be able to silently disable the forensic trail the finding asked for. const LOGIN_AUDIT_RETENTION_DAYS = 180; const LOGIN_AUDIT_PRUNE_BATCH = 10000; const LOGIN_AUDIT_PRUNE_MAX_BATCHES = 5; function createLoginAuditRecorder(deps) { const missing = [ "db", "getRequestIp", ].filter((key) => key === "db" ? typeof deps?.db?.query !== "function" : typeof deps?.[key] !== "function"); if (missing.length) { throw new Error(`createLoginAuditRecorder: missing required deps: ${missing.join(", ")}`); } const { db, getRequestIp, logger = console } = deps; // adpanel:failed-login-audit — the deterministic 1-in-20 sample counter for // ordinary credential failures (see recordFailedLoginAudit). Per-recorder: // index.js constructs exactly ONE recorder for the process, so this is the // module-level counter in production; tests construct fresh recorders, // which keeps the sample deterministic. let failedLoginAuditSampleCounter = 0; // Single-flight DDL (the initServerDeleteJobsTable pattern): the boot call // creates the table, and the insert path lazily retries the same guarded // CREATE if the boot pass failed — a ready flag alone would freeze a failed // boot in the failed state, so the flag is only set after a successful DDL. let loginAuditTableReady = false; let loginAuditTableInitPromise = null; async function ensureLoginAuditTable() { if (loginAuditTableReady) return; if (loginAuditTableInitPromise) return loginAuditTableInitPromise; loginAuditTableInitPromise = (async () => { await db.query(LOGIN_AUDIT_DDL); loginAuditTableReady = true; })().finally(() => { loginAuditTableInitPromise = null; }); return loginAuditTableInitPromise; } // Bounded boot-time retention (the pruneTerminalAiAgentJobs pattern): batched // DELETEs on the created_at index, stopping at the first short batch. // Best-effort — a failed prune warns and never blocks startup. async function pruneLoginAuditRetention() { if (!db?.query) return 0; let removedTotal = 0; try { for (let batch = 0; batch < LOGIN_AUDIT_PRUNE_MAX_BATCHES; batch++) { const result = await db.query( `DELETE FROM login_audit WHERE created_at < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ${LOGIN_AUDIT_RETENTION_DAYS} DAY) LIMIT ${LOGIN_AUDIT_PRUNE_BATCH}` ); const removed = Number(result?.affectedRows || 0); removedTotal += removed; if (removed < LOGIN_AUDIT_PRUNE_BATCH) break; } } catch (err) { logger.warn("[security] login audit retention prune skipped:", err?.message || err); return removedTotal; } if (removedTotal > 0) { logger.log(`[security] Pruned ${removedTotal} login_audit row(s) older than ${LOGIN_AUDIT_RETENTION_DAYS} day(s)`); } return removedTotal; } // THE one INSERT (the one-true-home rule): both recorders — success and // failed — write through this single statement shape; there is exactly one // audit-table INSERT statement string in this module (pinned by // tests/login-audit-durable.test.js's no-parallel-implementation test). // The lazy re-ensure lives here: if the boot-time create failed (DB briefly // down), the first row after recovery repairs the table instead of silently // dropping every audit row forever. Any failure falls through to the // calling recorder's catch — fail-open. async function insertLoginAuditRow({ userId, email, ip, userAgent, method }) { await ensureLoginAuditTable(); await db.query( "INSERT INTO login_audit (user_id, email, ip, user_agent, method) VALUES (?, ?, ?, ?, ?)", [userId, email, ip, userAgent, method] ); } // Records ONE row for a login whose session binding already succeeded. // Deliberately NEVER rejects and NEVER throws: the whole body is caught, // and the warn itself is guarded, so callers may fire-and-forget it // without creating an unhandled-rejection crash surface (the exact class // that has crashed this worker before — an upstream-less promise rejection // must not exist here). async function recordSuccessfulLoginAudit({ user, req, method }) { try { // Structural guards first: a login that somehow reached us without a // resolved account row or with an unknown method is warned + skipped — // junk rows are worse than missing rows, and both conditions are // impossible from the two pinned call sites. const userId = Number(user?.id); if (!Number.isFinite(userId) || userId <= 0) { logger.warn("[security] login audit skipped: no resolved account id (login unaffected)"); return; } if (!LOGIN_AUDIT_METHODS.has(method)) { logger.warn(`[security] login audit skipped: unknown method "${String(method).slice(0, 32)}" (login unaffected)`); return; } const email = String(user?.email || "").trim().slice(0, 255); const ip = String(getRequestIp(req) || "").slice(0, 64); // Same 255-char UA bound every other audit surface in the panel uses. const userAgent = String(req?.get?.("user-agent") || "").trim().slice(0, 255); await insertLoginAuditRow({ userId, email, ip, userAgent, method }); } catch (err) { try { logger.warn("[security] login audit write failed (login unaffected):", err?.message || err); } catch { } } } // Durable forensics for failed logins. Same never-reject/never-throwing // contract as the success recorder: the whole body is caught and the warn // itself is guarded, so the login handler may call it after the failure // decision without awaiting — the insert cannot add latency to the failure // path and cannot change the wire outcome. The warn NEVER carries the // submitted email (attacker-controlled — it is never logged raw; only the // fixed reason literal and the db error message reach the console). async function recordFailedLoginAudit({ email, req, reason }) { // adpanel:failed-login-audit — durable forensics for failed logins (F3): // budget-crossing refusals always, ordinary failures sampled 1-in-20 — // write volume bounded by the throttle budgets; fire-and-forget, never // gates. try { // The reason is the login handler's fixed debugLabel literal (arm:* // constants — module-defined strings, no free text); it is bounded // anyway because this module is the one home of the row shape and must // not trust its callers with the log. It is NOT persisted: the frozen // table shape has no reason column (adding one is a schema change, out // of scope for this recorder) — the token decides the recording policy // below, which is its whole job. const reasonToken = String(reason || "").replace(LOGIN_AUDIT_CONTROL_CHARS, "").trim().slice(0, 64); const standingBlock = FAILED_LOGIN_AUDIT_ALWAYS_REASONS.has(reasonToken); if (!standingBlock) { // Deterministic 1-in-20: a rolling counter, not a dice roll — every // 20th sampled-eligible failure records, so 20 ordinary failures // produce exactly one row and the worst case is exactly // 1/FAILED_LOGIN_AUDIT_SAMPLE_ONE_IN (0.05×) of an already // budget-bounded rate: ordinary failures record only after an // ADMITTED credential reservation (≤ LOGIN_IP_MAX_FAILURES admitted // per source per window, default 10/10min), so sampled rows are // bounded by the throttle budgets themselves and an attack cannot // amplify DB writes past the budget it already pays. The counter // advances before the insert decision — a failed insert does not // re-roll the sample. failedLoginAuditSampleCounter += 1; if (failedLoginAuditSampleCounter % FAILED_LOGIN_AUDIT_SAMPLE_ONE_IN !== 0) return; } // The SUBMITTED email — the forensic point is exactly what the attacker // typed, including the collation variants a canonical resolution would // erase; a failed probe may not resolve to any row, so it is never // resolved to a canonical row here. Bounded: control chars stripped, // trimmed, ≤254 chars (the RFC 5321 operational limit, inside the // column's 255). const boundedEmail = String(email || "").replace(LOGIN_AUDIT_CONTROL_CHARS, "").trim().slice(0, 254); const ip = String(getRequestIp(req) || "").slice(0, 64); // Same 255-char UA bound every other audit surface in the panel uses. const userAgent = String(req?.get?.("user-agent") || "").trim().slice(0, 255); // user_id 0 is the "no resolved account" sentinel: the column is NOT // NULL and the submitted string must not be resolved into a user id — // the row would otherwise leak account existence exactly like the // oracle the uniform-failure shape exists to close. await insertLoginAuditRow({ userId: 0, email: boundedEmail, ip, userAgent, method: FAILED_LOGIN_AUDIT_METHOD, }); } catch (err) { try { logger.warn("[security] failed login audit write failed (login unaffected):", err?.message || err); } catch { } } } return { ensureLoginAuditTable, pruneLoginAuditRetention, recordSuccessfulLoginAudit, recordFailedLoginAudit }; } module.exports = { createLoginAuditRecorder, LOGIN_AUDIT_DDL, LOGIN_AUDIT_METHODS, LOGIN_AUDIT_RETENTION_DAYS, LOGIN_AUDIT_PRUNE_BATCH, LOGIN_AUDIT_PRUNE_MAX_BATCHES, FAILED_LOGIN_AUDIT_METHOD, FAILED_LOGIN_AUDIT_ALWAYS_REASONS, FAILED_LOGIN_AUDIT_SAMPLE_ONE_IN, };