"use strict"; // adpanel:socket-session-liveness — ONE home for the "may this Socket.IO // socket keep streaming under its (possibly dead) HTTP session" decision. // Socket auth is handshake-only: once connected, the panel's 30-s connection // interval re-validated only the user ROW (suspension/ACL) while Phase 8's // 12-h remember-off idle timeout — and logout/admin revocation — can destroy // or expire the session record underneath a live socket (a socket emits no // HTTP request, so no session middleware ever runs for it again). The // constraint this module enforces: A SOCKET MUST NOT OUTLIVE ITS SESSION RECORD. // The connection interval calls the checker every tick with the sid captured // at handshake and disconnects the socket on verdict "dead". // // Verdict contract (fail-open by design): // "dead" — the record is provably gone (a miss from either backend // shape: connect-redis resolves null, session-file-store // rejects with ENOENT), OR the record exists but its sid is // tombstoned. The revocation half is NOT optional: // wrapSessionStoreWithTombstoneGuard wraps only set()/touch(), // so a readable record does not prove the sid un-revoked // (a destroy that raced/failed can leave the record in place // behind the tombstone), OR — when the caller hands in the // freshly re-read user row — the record's account binding no // longer matches that row: a DEFINITIVE stale binding // (reason "account-binding-stale", see below); // "unknown" — a store error (including the caller's bounded-read timeout) // or an unresolvable revocation check. The caller must KEEP // the socket: a store blip must not mass-disconnect // dashboards, and with the session store down no HTTP login // works either, so the exposure window is bounded by the // outage itself. The revocation check runs with // failClosed: false — mirroring the handshake's read-path // revoked-sid gate, an unreadable tombstone never CONFIRMS a // revocation; // "alive" — record present and sid not tombstoned. // // adpanel:socket-liveness-binding — the binding leg. Socket.IO's account // binding was enforced ONCE, at handshake; a credential change bumps the // row's session_epoch in the same statement as the credential (the write-side // contract), and a socket emits no HTTP request — so handshake-only checks // leave a 30-s+ window where a stale-binding session record keeps streaming // on a row that moved to a new generation. When the caller passes the row it // re-read for THIS tick, a successfully fetched record is compared against it // through the ONE shared predicate (sessionAccountBindingMismatch, // utils/session-account-binding.js — the same shape the HTTP session // middleware, the handshake and the SSH gate reject on). A mismatch is a // DEFINITIVE stale binding — disconnect (verdict "dead", reason // "account-binding-stale"); only store READ ERRORS stay fail-open. The // comparison is pure, so it runs BEFORE the tombstone read: a mismatch // disconnects even when the tombstone consult is unresolved, and it spares // the backend read entirely. A record minted before accountId/accountEpoch // existed carries neither field and is uncomparable (the shared predicate // passes it — the same documented posture as every other consumer; the // revocation sweep remains its guard). No row handed in → the leg is skipped // and every verdict is unchanged. // // Perf: one store read per socket per 30 s, comparable to the per-socket DB // read the interval already performs. const { sessionAccountBindingMismatch } = require("./session-account-binding"); const SOCKET_SESSION_LIVENESS_VERDICTS = Object.freeze({ ALIVE: "alive", DEAD: "dead", UNKNOWN: "unknown", }); // A missing record reports differently per backend: connect-redis resolves // null for a missing key; session-file-store rejects with ENOENT. Both // shapes count as "gone" (the same classification the verified-destroy // readback in index.js makes); any other error is "unknown", never a miss — // guessing would turn store outages into mass-disconnects. function isSessionRecordMissError(err) { const code = String(err?.code || ""); const msg = String(err?.message || ""); return code === "ENOENT" || msg.includes("ENOENT") || msg.includes("no such file"); } // deps.getSessionRecord(sid) must be the CALLER-BOUNDED read of the SAME // wrapped store instance the HTTP session middleware uses (index.js injects // withTimeout(callSessionStore("get", sid), ...) — never a second store or // client). deps.isSessionSidRevoked is the shared tombstone check. The // optional per-call { user } is the row the caller re-read for THIS tick // (index.js hands the interval's own findUserByEmail result) — it enables // the account-binding leg documented above. function createSocketSessionLivenessChecker({ getSessionRecord, isSessionSidRevoked } = {}) { if (typeof getSessionRecord !== "function") throw new TypeError("getSessionRecord dependency is required"); if (typeof isSessionSidRevoked !== "function") throw new TypeError("isSessionSidRevoked dependency is required"); return async function checkSocketSessionLiveness(sessionId, { user } = {}) { const sid = String(sessionId || "").trim(); if (!sid) return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN, reason: "no-session-id" }; let record = null; try { record = await getSessionRecord(sid); } catch (err) { if (!isSessionRecordMissError(err)) { return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN, reason: "store-error", error: err }; } record = null; // miss-shaped rejection: the record is gone } if (!record) return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, reason: "record-missing" }; // adpanel:socket-liveness-binding — a successfully read record whose // account binding no longer matches the freshly re-read row is a // DEFINITIVE stale binding, never a fail-open case: the credential // writers bump session_epoch in the same statement as the credential, // so an epoch (or accountId) disagreement proves the row moved on after // this record was bound — the socket must not keep streaming on it for // another tick. The comparison is pure and definitive, so it runs before // the tombstone read (a mismatch disconnects even when that consult is // unresolved, and spares the backend read entirely). A record without // the binding fields is uncomparable (shared predicate passes it); only // store READ ERRORS keep the fail-open posture. if (user && sessionAccountBindingMismatch(record, user)) { return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, reason: "account-binding-stale" }; } let revoked = null; try { revoked = await isSessionSidRevoked(sid, { failClosed: false }); } catch (err) { return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN, reason: "revocation-check-error", error: err }; } if (revoked === true) return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, reason: "sid-revoked" }; if (revoked === false) return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE, reason: "record-present" }; return { verdict: SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN, reason: "revocation-unresolved" }; }; } // adpanel:socket-session-liveness — throttled "unknown" logger: during a // store outage one warn per tick per socket would flood the log, so at most // one line per interval window (same shape as login-throttle's logErr // brake). Throttling the log is cosmetic; NOT disconnecting is the // fail-open contract above. function createSocketSessionLivenessLogger({ logger = console, intervalMs = 60 * 1000 } = {}) { let lastWarnAt = 0; return function logSocketSessionLivenessUnknown(reason, err) { const now = Date.now(); if (now - lastWarnAt < intervalMs) return; lastWarnAt = now; logger.warn(`[security] Socket session liveness unverifiable (${String(reason || "unknown-reason")}); failing open:`, err?.message || err || ""); }; } module.exports = { createSocketSessionLivenessChecker, createSocketSessionLivenessLogger, isSessionRecordMissError, SOCKET_SESSION_LIVENESS_VERDICTS, };