Files
Kelx/utils/totp-claim.js
T
2026-11-30 16:32:37 +00:00

158 lines
7.1 KiB
JavaScript

"use strict";
// adpanel:totp-atomic-claim — ONE home for the cross-worker TOTP step claim.
// The constraint this module enforces: a TOTP code authorizes EXACTLY ONE
// verification across ALL workers/instances, so consuming a step must be a
// single atomic compare-and-set, never a check-then-write split. The old
// posture (read users.totp_last_counter as a snapshot, then fire-and-forget
// `UPDATE ... GREATEST(...)`) was monotonic but never EXCLUSIVE: two
// overlapping requests holding stale snapshots both passed the pre-check and
// both GREATEST-wrote, so one code authorized two verifications. The claim
// below IS the persist — a winning claim writes the counter, a losing claim
// writes nothing (its UPDATE matches zero rows) — and it is the cross-worker
// authority. The process-local replay Map (markTotpCodeUsed in index.js)
// stays as the fast same-process guard layered IN FRONT of this claim; it is
// never a substitute for it.
//
// Fail-closed posture: every flow that reaches the verifier already treats
// the DB as a hard dependency, so a claim that cannot be adjudicated
// (timeout, unreachable DB, unexpected driver error) must fail the
// verification ({ won: false, failed: true }) rather than risk a double
// spend. SOLE exception: ER_BAD_FIELD_ERROR means the legacy schema predates
// the totp_last_counter column (the boot ALTER failed) — in that mode the
// old GREATEST write failed silently too, so the claim degrades OPEN
// ({ won: true, degraded: true }) exactly like the historical behavior,
// logs loudly ONCE per process, and the in-memory Map remains the only
// replay guard. Never upgrade that degradation into a new deployment's
// default: a missing column on a fresh boot is an operator emergency.
//
// Contract: the returned claim function NEVER REJECTS. Every outcome —
// malformed arguments, a synchronous throw from a broken adapter, a
// rejection, a timeout — resolves to a result object, so callers cannot
// create an unhandled-rejection crash class by awaiting it. The claim is
// refused (failed) for malformed arguments and no query is issued. That
// contract is unconditional: the injected logger (and deps.now, which stamps
// the log timestamps) is fault-isolated, so a logger that throws
// synchronously cannot convert a fail-closed resolution into a rejection.
const ER_BAD_FIELD_ERROR = "ER_BAD_FIELD_ERROR";
const DEFAULT_CLAIM_TIMEOUT_MS = 8000;
function createTotpStepClaimer(deps = {}) {
const db = deps.db;
if (!db || typeof db.query !== "function") {
throw new Error("createTotpStepClaimer requires a db dependency exposing query(sql, params)");
}
const logger = deps.logger || console;
const now = typeof deps.now === "function" ? deps.now : Date.now;
const timeoutMs = Number.isFinite(deps.timeoutMs) && deps.timeoutMs > 0
? deps.timeoutMs
: DEFAULT_CLAIM_TIMEOUT_MS;
let degradedLoggedOnce = false;
// adpanel:totp-atomic-claim — the NEVER-REJECTS contract extends to the
// injected deps: a logger that throws synchronously must not be able to
// turn a fail-closed resolution into a rejection (a throw inside the
// timeout branch would fall into the catch below, whose classifyClaimError
// logs again and escapes claimTotpStep entirely). Logging — including
// timestamp construction via deps.now — is therefore fault-isolated:
// logger failures are swallowed silently and are never claim outcomes.
function logSafely(log) {
try {
log();
} catch {
// Swallowed on purpose: logging must never reject the claim.
}
}
return async function claimTotpStep(userId, step) {
// Malformed arguments are a caller bug, never an authorization signal:
// refuse the claim (fail closed) without touching the database.
if (userId == null || userId === "" || !Number.isFinite(Number(step))) {
return { won: false, failed: true };
}
// Atomic claim-by-monotonic-step. The WHERE clause is the mutex: the
// row lock serializes concurrent claims and the surviving re-evaluation
// excludes equal-or-higher steps, so exactly one of N racers gets
// affectedRows >= 1 and the rest get 0 rows matched (nothing written).
// NULL means "never consumed" and stays distinct from 0 for accounts on
// their first claim.
const CLAIM_SQL =
"UPDATE users SET totp_last_counter = ? WHERE id = ? AND (totp_last_counter IS NULL OR totp_last_counter < ?)";
const params = [step, userId, step];
let queryPromise;
try {
queryPromise = db.query(CLAIM_SQL, params);
} catch (err) {
return classifyClaimError(err);
}
// Boundary against the timeout path below: if the timeout wins the race,
// the abandoned query settles later — its rejection (or value) must never
// surface as an unhandled rejection.
if (!queryPromise || typeof queryPromise.then !== "function") {
return { won: false, failed: true };
}
queryPromise.then(
() => {},
() => {}
);
let timer = null;
try {
const result = await Promise.race([
queryPromise,
new Promise((resolve) => {
timer = setTimeout(() => resolve({ __totpClaimTimedOut: true }), timeoutMs);
if (timer && typeof timer.unref === "function") timer.unref();
}),
]);
if (result && result.__totpClaimTimedOut) {
logSafely(() =>
logger.error(
`[security] totp-atomic-claim timed out after ${timeoutMs}ms — failing closed (no code consumed) at ${new Date(now()).toISOString()}`
)
);
return { won: false, failed: true };
}
// db.query resolves the OkPacket for UPDATEs — affectedRows decides.
// Any other shape (undefined/0 rows) is adjudicated as a LOSS: fail
// closed rather than guess.
const affectedRows = result && typeof result === "object" ? Number(result.affectedRows || 0) : 0;
if (affectedRows >= 1) return { won: true };
// A clean loss (another request consumed an equal-or-higher step
// first) is an expected race outcome, not an error: stay silent and
// indistinguishable from a wrong code downstream.
return { won: false };
} catch (err) {
return classifyClaimError(err);
} finally {
if (timer) clearTimeout(timer);
}
function classifyClaimError(err) {
if (err && err.code === ER_BAD_FIELD_ERROR) {
if (!degradedLoggedOnce) {
degradedLoggedOnce = true;
logSafely(() =>
logger.error(
"[security] totp-atomic-claim: users.totp_last_counter column is missing (legacy schema, boot ALTER failed) — degrading OPEN to the in-memory replay cache as the only guard. Fix the schema: cross-worker replay protection is DISABLED in this mode."
)
);
}
return { won: true, degraded: true };
}
logSafely(() =>
logger.error(
`[security] totp-atomic-claim failed closed (no code consumed): ${err?.message || err} at ${new Date(now()).toISOString()}`
)
);
return { won: false, failed: true };
}
};
}
module.exports = { createTotpStepClaimer };