"use strict"; // adpanel:socket-session-liveness — unit tests for the ONE liveness-decision // module plus source pins holding the wiring in place. The wiring finding // (W-1): Socket.IO auth is handshake-only — after the connection is up, the // 30-s interval re-validated only the user ROW (suspension/ACL), never the // session record, and a socket emits no HTTP request, so no session // middleware ever re-validated it either. With Phase 8's 12-h remember-off // idle timeout, "live socket, dead session" became a normal-operation state: // a dashboard tab left open overnight kept streaming console output and // dashboard events after its session expired (or was destroyed by // logout/admin revoke). The pins below hold: the handshake captures the sid // it authenticated, the interval re-reads the session RECORD through the // SAME wrapped store the HTTP middleware uses (never a second store/client) // and disconnects on a dead record or a tombstoned sid, and a store error // fails OPEN — a Redis blip must not mass-disconnect dashboards (with the // store down no HTTP login works either, so the exposure window is bounded // by the outage itself). It reads index.js as text, like the other audit // tests. // // adpanel:socket-liveness-binding — the interval ALSO hands the checker the // row it re-read for this tick, so the record-vs-row account binding // (accountId/accountEpoch, the ONE shared predicate) is re-proven every 30 s: // the handshake proved it once, at connect, and a credential change bumps // session_epoch in the same statement as the credential — a stale-binding // record is a definitive disconnect ("account-binding-stale"), while store // read ERRORS alone keep the fail-open posture. 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 indexSource = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const moduleSrc = fs.readFileSync(path.join(ROOT, "utils", "socket-session-liveness.js"), "utf8"); const { createSocketSessionLivenessChecker, createSocketSessionLivenessLogger, isSessionRecordMissError, SOCKET_SESSION_LIVENESS_VERDICTS, } = require("../utils/socket-session-liveness"); const makeChecker = (overrides = {}) => createSocketSessionLivenessChecker({ getSessionRecord: async () => ({ cookie: { expires: "sometime" } }), isSessionSidRevoked: async () => false, ...overrides, }); test("an intact session (record present, sid not tombstoned) is alive", async () => { const verdicts = []; const checker = makeChecker({ isSessionSidRevoked: async (sid, opts) => { verdicts.push({ sid, opts }); return false; }, }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE); assert.strictEqual(result.reason, "record-present"); // adpanel:socket-session-liveness — the revocation half must run with // failClosed: false (the handshake's read-path posture): an unreadable // tombstone never confirms a revocation, and disconnecting on one would // mass-clear dashboards during a Redis blip. assert.deepStrictEqual(verdicts, [{ sid: "sid-1", opts: { failClosed: false } }]); }); test("a missing record disconnects: null, undefined and miss-shaped errors are all dead", async () => { for (const getSessionRecord of [ async () => null, async () => undefined, async () => { const e = new Error("ENOENT: no such file or directory, open '/sessions/sid.json'"); e.code = "ENOENT"; throw e; }, async () => { throw new Error("readfile /sessions/sid.json: no such file"); }, ]) { const checker = makeChecker({ getSessionRecord }); const result = await checker("sid-gone"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, `expected DEAD for ${getSessionRecord}`); assert.strictEqual(result.reason, "record-missing"); } }); test("a tombstoned-but-readable record is dead (the guard wraps only set/touch, not get)", async () => { const checker = makeChecker({ isSessionSidRevoked: async () => true }); const result = await checker("sid-revoked"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(result.reason, "sid-revoked"); }); test("store errors fail OPEN (unknown): a Redis blip must not mass-disconnect dashboards", async () => { const checker = makeChecker({ getSessionRecord: async () => { throw new Error("Connection is closed."); } }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "store-error"); assert.ok(result.error instanceof Error); }); test("a bounded-read timeout is unknown, never a miss (its label is not an ENOENT shape)", async () => { const checker = makeChecker({ getSessionRecord: async () => { throw new Error("socket-session-liveness-timeout"); } }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "store-error"); }); test("an errored revocation check fails OPEN too", async () => { const checker = makeChecker({ isSessionSidRevoked: async () => { throw new Error("Connection is closed."); } }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "revocation-check-error"); }); test("a non-boolean revocation answer is unresolved, never silently alive or dead", async () => { const checker = makeChecker({ isSessionSidRevoked: async () => undefined }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "revocation-unresolved"); }); test("a socket captured without a sid fails open (legacy/pre-capture sockets keep streaming)", async () => { let storeReads = 0; const checker = makeChecker({ getSessionRecord: async () => { storeReads += 1; return null; } }); const result = await checker(""); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "no-session-id"); assert.strictEqual(storeReads, 0, "no store read may be spent on an empty sid"); }); test("isSessionRecordMissError classifies both backend miss shapes and nothing else", () => { const enoentCode = Object.assign(new Error("x"), { code: "ENOENT" }); assert.strictEqual(isSessionRecordMissError(enoentCode), true); assert.strictEqual(isSessionRecordMissError(new Error("read: no such file or directory")), true); assert.strictEqual(isSessionRecordMissError(new Error("ENOENT somewhere in the text")), true); assert.strictEqual(isSessionRecordMissError(new Error("Connection is closed.")), false); assert.strictEqual(isSessionRecordMissError(new Error("socket-session-liveness-timeout")), false); assert.strictEqual(isSessionRecordMissError(null), false); }); // --------------------------------------------------------------------------- // adpanel:socket-liveness-binding — the record-vs-row account binding leg. // The handshake proved the binding ONCE, at connect; the credential writers // bump session_epoch in the same statement as the credential, and a socket // emits no HTTP request — so without this leg a stale-binding record could // keep streaming for 30-s+ ticks after the row moved to a new generation. // --------------------------------------------------------------------------- // A record shaped like a stored express-session record (identity fields at // the top level, exactly what sessionAccountBindingMismatch reads). const LIVE_RECORD = { cookie: { expires: "sometime" }, user: "user@example.test", accountId: 7, accountEpoch: 4 }; test("a record whose account binding mismatches the freshly re-read row is a DEFINITIVE stale binding (dead)", async () => { // A successfully read record that disagrees with the current row is proof // the row moved on after this record was bound — NOT a fail-open case. const row = { id: 7, email: "user@example.test", session_epoch: 9 }; const epochMismatch = makeChecker({ getSessionRecord: async () => ({ ...LIVE_RECORD, accountEpoch: 3 }) }); const r1 = await epochMismatch("sid-1", { user: row }); assert.strictEqual(r1.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(r1.reason, "account-binding-stale"); const row2 = { id: 8, email: "user@example.test", session_epoch: 4 }; const idMismatch = makeChecker({ getSessionRecord: async () => ({ ...LIVE_RECORD }) }); const r2 = await idMismatch("sid-1", { user: row2 }); assert.strictEqual(r2.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(r2.reason, "account-binding-stale"); }); test("a mismatched record disconnects even when the tombstone consult is unresolved (the binding leg runs first)", async () => { // The binding comparison is pure and definitive, so it short-circuits // before the backend tombstone read: a stale-binding record never gets a // second 30-s window because the tombstone consult came back unresolved. const revocationConsults = []; const checker = makeChecker({ getSessionRecord: async () => ({ ...LIVE_RECORD, accountEpoch: 3 }), isSessionSidRevoked: async (sid, opts) => { revocationConsults.push(sid); return undefined; }, }); const result = await checker("sid-1", { user: { id: 7, email: "user@example.test", session_epoch: 9 } }); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(result.reason, "account-binding-stale"); assert.deepStrictEqual(revocationConsults, [], "the definitive binding leg spares the backend tombstone read entirely"); }); test("a binding-clean record against the handed-in row stays alive", async () => { const checker = makeChecker({ getSessionRecord: async () => ({ ...LIVE_RECORD, accountId: 7, accountEpoch: 4 }), }); const result = await checker("sid-1", { user: { id: 7, email: "user@example.test", session_epoch: 4 } }); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE); assert.strictEqual(result.reason, "record-present"); }); test("a legacy record without accountId/accountEpoch stays uncomparable (alive; the revocation sweep remains its guard)", async () => { // Same documented posture as every other sessionAccountBindingMismatch // consumer: sessions minted before the binding fields existed pass the // shared predicate and are covered by the revocation sweep. const checker = makeChecker({ getSessionRecord: async () => ({ cookie: { expires: "sometime" } }), }); const result = await checker("sid-1", { user: { id: 7, email: "user@example.test", session_epoch: 4 } }); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE); assert.strictEqual(result.reason, "record-present"); }); test("without a handed-in row the binding leg is skipped (verdicts unchanged for existing callers)", async () => { const checker = makeChecker({ getSessionRecord: async () => ({ ...LIVE_RECORD, accountId: 7, accountEpoch: 3 }), }); const result = await checker("sid-1"); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE); assert.strictEqual(result.reason, "record-present"); }); test("store read ERRORS keep the fail-open posture even when a row is handed in", async () => { // The fail-open posture is for STORE READ ERRORS only — with no record // there is nothing to compare, and a store blip must not mass-disconnect. const checker = makeChecker({ getSessionRecord: async () => { throw new Error("Connection is closed."); } }); const result = await checker("sid-1", { user: { id: 7, email: "user@example.test", session_epoch: 9 } }); assert.strictEqual(result.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.UNKNOWN); assert.strictEqual(result.reason, "store-error"); }); test("record-missing and sid-revoked verdicts are unchanged when a row is handed in", async () => { const missing = makeChecker({ getSessionRecord: async () => null }); const r1 = await missing("sid-1", { user: { id: 7, email: "u", session_epoch: 9 } }); assert.strictEqual(r1.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(r1.reason, "record-missing"); const revoked = makeChecker({ isSessionSidRevoked: async () => true }); const r2 = await revoked("sid-1", { user: { id: 7, email: "u", session_epoch: 9 } }); assert.strictEqual(r2.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD); assert.strictEqual(r2.reason, "sid-revoked"); }); test("the checker requires its dependencies (no silent no-op wiring)", () => { assert.throws(() => createSocketSessionLivenessChecker({}), TypeError); assert.throws(() => createSocketSessionLivenessChecker({ getSessionRecord: async () => null }), TypeError); }); test("the unknown-logger is throttled to one line per window", async () => { const lines = []; const log = createSocketSessionLivenessLogger({ logger: { warn: (...args) => lines.push(args.join(" ")) }, intervalMs: 30, }); log("store-error", new Error("boom")); log("store-error", new Error("boom")); log("store-error", new Error("boom")); assert.strictEqual(lines.length, 1, "repeats inside the window must be suppressed"); assert.match(lines[0], /store-error/); assert.match(lines[0], /failing open/); await new Promise((resolve) => setTimeout(resolve, 40)); log("store-error", new Error("boom")); assert.strictEqual(lines.length, 2, "a later window logs again"); }); // --------------------------------------------------------------------------- // Source pins (index.js is read as text, like the other audit tests) // --------------------------------------------------------------------------- function sliceBetween(source, startAnchor, endAnchor) { const start = source.indexOf(startAnchor); assert.notStrictEqual(start, -1, `expected the anchor: ${startAnchor}`); const end = source.indexOf(endAnchor, start); assert.ok(end > start, `expected the end anchor after the start: ${endAnchor}`); return source.slice(start, end); } test("index.js wires exactly one checker, built on the shared store reference — never a second store/client", () => { assert.strictEqual( (indexSource.match(/require\("\.\/utils\/socket-session-liveness"\)/g) || []).length, 1, "the liveness module must be required exactly once" ); assert.strictEqual( (indexSource.match(/createSocketSessionLivenessChecker\(/g) || []).length, 1, "the checker must be constructed exactly once — a second wiring would be a forked implementation" ); assert.strictEqual( (indexSource.match(/checkSocketSessionLiveness\(/g) || []).length, 1, "exactly one interval call site — no other consumer, no re-implementation" ); assert.ok( indexSource.includes("const checkSocketSessionLiveness = createSocketSessionLivenessChecker("), "the checker is bound once at wiring time and reused by the interval" ); assert.strictEqual( (indexSource.match(/function checkSocketSessionLiveness\(/g) || []).length, 0, "the decision logic must stay in utils/socket-session-liveness.js, not re-inlined into the monolith" ); const wiring = sliceBetween( indexSource, "wrapSessionStoreWithTombstoneGuard(sessionStore);", "setInterval(sweepExpiredRevokedSidTombstones" ); assert.ok( wiring.includes('callSessionStore("get", sid)'), "the record read must go through callSessionStore — the SAME wrapped store instance the HTTP session middleware uses" ); assert.ok(wiring.includes("withTimeout(") && wiring.includes('"socket-session-liveness-timeout"'), "the read must be bounded so a wedged store cannot pile up one pending query per socket per tick"); assert.ok(wiring.includes("isSessionSidRevoked,"), "the shared tombstone check must be injected, not re-implemented"); assert.ok(!wiring.includes("new RedisStore") && !wiring.includes("FileStore"), "the wiring must not create a second store or client"); assert.ok(wiring.includes("createSocketSessionLivenessLogger({ intervalMs"), "the throttled unknown-logger must be wired from the shared module"); }); test("the handshake pins the sid it authenticated, after the revoked-sid check", () => { const handshake = sliceBetween(indexSource, "io.use((socket, next) => {", "const consoleHistory = new Map();"); const revokedAt = handshake.indexOf('isSessionSidRevoked(String(socket.request.sessionID || "")'); const captureAt = handshake.indexOf('socket.data.sessionId = String(socket.request.sessionID || "");'); assert.notStrictEqual(revokedAt, -1, "expected the handshake's revoked-sid check"); assert.notStrictEqual(captureAt, -1, "the handshake must capture the authenticated sid for the interval"); assert.ok( captureAt > revokedAt, "the sid may only be pinned once the handshake's binding + tombstone checks have passed" ); assert.ok( handshake.includes("// adpanel:socket-session-liveness"), "the capture must carry the campaign comment" ); }); test("the 30-s interval re-validates the session record and disconnects only on a DEAD verdict", () => { const interval = sliceBetween(indexSource, "const suspensionInterval = setInterval(async () => {", "}, 30_000);"); const suspendedAt = interval.indexOf("if (!latestUser || latestUser.suspended)"); const sidReadAt = interval.indexOf('String(socket.data?.sessionId || "")'); // Conscious pin update (adpanel:socket-liveness-binding): the interval now // hands the checker the row it re-read for THIS tick — the binding leg's // input. Same assertion strength: the interval must consult the shared // liveness checker, now with fresh row inputs. const checkAt = interval.indexOf('await checkSocketSessionLiveness(socketSessionId, { user: latestUser })'); assert.notStrictEqual(suspendedAt, -1, "expected the user-row check"); assert.notStrictEqual(sidReadAt, -1, "the interval must read the sid captured at handshake"); assert.notStrictEqual(checkAt, -1, "the interval must consult the shared liveness checker, handing it the freshly re-read row"); assert.ok( suspendedAt < sidReadAt && sidReadAt < checkAt, "the row check runs first (suspension disconnects immediately), then the session-record check against that same row" ); assert.ok(interval.includes("// adpanel:socket-session-liveness"), "the interval check must carry the campaign comment"); assert.ok( interval.includes("// adpanel:socket-liveness-binding"), "the binding handoff must carry its campaign comment (handshake-only checks leave a 30s+ window)" ); assert.ok( !interval.includes("sessionStore"), "the interval must go through the checker, never touch the store object directly" ); // Branch structure by offset: dead → disconnect + return; unknown → log // only. The disconnect on "dead" must come BEFORE the "unknown" branch so // a dead session never falls through into the unknown (keep-alive) path. const deadAt = interval.indexOf('sessionLiveness.verdict === "dead"'); const unknownAt = interval.indexOf('sessionLiveness.verdict === "unknown"'); const deadDisconnectAt = deadAt === -1 ? -1 : interval.indexOf("socket.disconnect(true);", deadAt); const isLatestAdminAt = interval.indexOf("const isLatestAdmin"); assert.notStrictEqual(deadAt, -1, "expected the dead branch"); assert.notStrictEqual(unknownAt, -1, "expected the unknown branch"); assert.notStrictEqual(deadDisconnectAt, -1, "a dead session must disconnect the socket"); assert.notStrictEqual(isLatestAdminAt, -1, "expected the end of the liveness block"); // adpanel:socket-liveness-binding — the definitive stale-binding disconnect // is visible in the log with its distinct reason (forensics: a stale epoch // row must not keep a live socket silently). const staleBindingLogAt = interval.indexOf('if (sessionLiveness.reason === "account-binding-stale") {', deadAt); assert.notStrictEqual(staleBindingLogAt, -1, "the dead branch logs the account-binding-stale reason before disconnecting"); assert.ok( staleBindingLogAt < deadDisconnectAt && interval.slice(staleBindingLogAt, deadDisconnectAt).includes("console.warn("), "the binding-stale warn sits inside the dead branch, before its disconnect" ); assert.ok(deadAt < deadDisconnectAt, "the disconnect belongs to the dead branch"); assert.ok(deadDisconnectAt < unknownAt, "dead must be handled before the fail-open branch"); assert.ok(unknownAt < isLatestAdminAt, "the liveness block must end before the ACL refresh"); const unknownBranch = interval.slice(unknownAt, isLatestAdminAt); assert.ok( unknownBranch.includes("logSocketSessionLivenessUnknown(") && !unknownBranch.includes("socket.disconnect"), "an unknown verdict must only log (throttled) and keep the socket — the fail-open contract" ); assert.ok( !unknownBranch.includes("return;"), "the unknown branch must fall through to the ACL refresh" ); }); test("the liveness block owns its errors: the outer fail-closed catch cannot swallow the fail-open posture", () => { const interval = sliceBetween(indexSource, "const suspensionInterval = setInterval(async () => {", "}, 30_000);"); const checkAt = interval.indexOf('await checkSocketSessionLiveness(socketSessionId, { user: latestUser })'); const catchAt = interval.indexOf("catch (livenessErr)", checkAt); assert.notStrictEqual(catchAt, -1, "the checker call must have its own try/catch"); const fallback = interval.slice(catchAt, interval.indexOf('sessionLiveness.verdict === "dead"', catchAt)); assert.ok( fallback.includes('"unknown"') && fallback.includes("liveness-check-errored"), "an unexpected checker failure must be coerced to the fail-open verdict, not reach the outer catch" ); assert.ok( /fails? OPEN/.test(interval) && interval.includes("mass-disconnect"), "the interval comment must document the fail-open posture and why" ); }); test("the fail-open/revocation contract stays documented in the shared module", () => { assert.ok( moduleSrc.includes("A SOCKET MUST NOT OUTLIVE ITS SESSION RECORD"), "the module header must state the enforced constraint" ); assert.ok( moduleSrc.includes("{ failClosed: false }"), "the module must run the tombstone check fail-closed:false (unreadable tombstone never confirms a revocation)" ); assert.ok( moduleSrc.includes("ENOENT") && moduleSrc.includes("no such file"), "the module must classify both backend miss shapes (redis null vs file-store ENOENT)" ); // adpanel:socket-liveness-binding — the binding leg is part of the module's // documented contract: the shared predicate, the definitive // stale-binding reason, and the read-errors-only fail-open boundary. assert.ok( moduleSrc.includes("sessionAccountBindingMismatch") && moduleSrc.includes('require("./session-account-binding")'), "the binding leg must decide through the ONE shared predicate, required from utils/session-account-binding.js" ); assert.ok( moduleSrc.includes("account-binding-stale"), "the module must name the definitive stale-binding verdict reason" ); }); test("Engine.IO rejects protocol-changing upgrades before namespace authentication and accepts a matching upgrade", { timeout: 5000 }, async (context) => { const http = require("node:http"); const { once } = require("node:events"); const { Server } = require("socket.io"); const WebSocket = require("ws"); const server = http.createServer(); const io = new Server(server, { allowEIO3: false, maxHttpBufferSize: 1e6 }); let namespaceAdmissions = 0; io.use((socket, next) => { namespaceAdmissions += 1; next(new Error("authentication required")); }); context.after(() => new Promise((resolve) => io.close(resolve))); server.listen(0, "127.0.0.1"); await once(server, "listening"); const host = `127.0.0.1:${server.address().port}`; const handshake = await fetch(`http://${host}/socket.io/?EIO=4&transport=polling`, { headers: { connection: "close" }, signal: AbortSignal.timeout(3000), }); assert.strictEqual(handshake.status, 200); const openingPacket = await handshake.text(); assert.strictEqual(openingPacket[0], "0"); const { sid } = JSON.parse(openingPacket.slice(1)); for (const revision of ["3", null]) { const query = new URLSearchParams({ transport: "websocket", sid }); if (revision !== null) query.set("EIO", revision); const websocket = new WebSocket(`ws://${host}/socket.io/?${query}`); context.after(() => websocket.terminate()); const status = await new Promise((resolve, reject) => { websocket.once("error", reject); websocket.once("open", () => { websocket.terminate(); reject(new Error("a protocol-changing upgrade was accepted")); }); websocket.once("unexpected-response", (request, response) => { response.resume(); resolve(response.statusCode); websocket.terminate(); }); }); assert.strictEqual(status, 400); assert.strictEqual(io.engine.clients[sid].protocol, 4); } const matching = new WebSocket(`ws://${host}/socket.io/?EIO=4&transport=websocket&sid=${encodeURIComponent(sid)}`); context.after(() => matching.terminate()); await once(matching, "open"); assert.strictEqual(namespaceAdmissions, 0); matching.terminate(); }); test("the Socket.IO parser refuses invalid attachment counts without allocating a reconstructor", () => { const { Decoder } = require("socket.io-parser"); for (const packet of ['50-["event"]', '5-1-["event"]', '51.5-["event"]', '511-["event"]', '5Infinity-["event"]']) { const decoder = new Decoder(); assert.throws(() => decoder.add(packet), /Illegal attachments|too many attachments/); assert.strictEqual(decoder.reconstructor, undefined); } }); test("the Socket.IO parser still reconstructs a valid binary event", () => { const { Decoder, Encoder, PacketType } = require("socket.io-parser"); const decoder = new Decoder(); const decoded = []; decoder.on("decoded", (packet) => decoded.push(packet)); const payload = Buffer.from("valid attachment"); const packets = new Encoder().encode({ type: PacketType.EVENT, nsp: "/", data: ["event", payload] }); for (const packet of packets) decoder.add(packet); assert.strictEqual(decoded.length, 1); assert.strictEqual(decoded[0].type, PacketType.EVENT); assert.deepStrictEqual(decoded[0].data, ["event", payload]); assert.strictEqual(decoder.reconstructor, null); });