Files
Kelx/utils/credential-session-rebind.js
2026-11-30 16:32:37 +00:00

220 lines
11 KiB
JavaScript

"use strict";
// adpanel:credential-session-rebind — ONE shared implementation of the
// post-credential-change session rebind that every interactive credential
// change must run: destroy EVERY browser session of the user (tombstone +
// store destroy + user-wide remember revocation via
// revokeRememberLoginsForUser inside the injected destroyer), tombstone the
// caller's own pre-regeneration sid, regenerate the session under its 5s
// timeout, re-bind the user/accountId/accountEpoch identity, rebuild the
// browser-session audit object the regenerate wiped (the login binder's
// step, mirrored), re-issue the remember cookie with { forceFreshId: true }
// (adpanel:remember-fresh-reissue:
// the re-issue follows a user-wide remember revoke, so a stale session id
// must never be reused), mark the remember-login lifetime fresh, upsert the
// active browser-session cache entry, and save under its 5s timeout. If
// anything after the remember mint fails (the cache upsert or the bounded
// save), the just-minted credential is revoked first — a visibly-failed
// credential change must not leave a live 365-day remember credential riding
// the error response — and the regenerated sid is tombstoned, so a late store
// write cannot commit the authenticated record behind the 500.
//
// The constraint this module enforces: after a credential change NO copy of
// any pre-change session may survive — including the caller's OWN session
// identifier. The four routes this replaces (self-service password change,
// recovery password change, settings password change, email change, 2FA
// secret rotation) previously swept every OTHER session of the user while
// keeping their own sid alive: anyone holding a COPY of that same session
// cookie retained full access after the "remediation", and the routes carried
// line-for-line parallel copies of the destroy/re-issue sequence that could
// (and did) drift. A stolen-cookie remediation that leaves the stolen
// identifier valid is not a remediation, so the self-exclusion is gone and
// the owner is re-bound onto a freshly regenerated session in the same
// atomic sequence.
//
// Sockets are deliberately NOT handled here: they authenticate at connect
// time only and stay bound to their OLD sid, which the destroy below kills —
// the routes disconnect them without an exclusion for the same reason.
//
// Deliberately per-surface and therefore NOT here: the credential writes
// themselves (each is a compare-and-swap on the verified snapshot credential
// — adpanel:credential-change-cas — and must stay at its own route, where the
// verified snapshot lives), the socket disconnects, and the response bodies.
//
// Dependency direction is one-way: index.js requires this module; this
// module requires only utils/*. Every index.js closure the sequence needs
// arrives through the injected `deps` object (the pattern of
// utils/login-session-bind.js, whose sessionCallbackToPromise shape, 5s
// timeout constants and post-mint hygiene vocabulary this module shares).
// The two timeouts are load-bearing (same values the login binder and the
// inline copies used): a hung store callback must not wedge the
// credential-change request forever.
const REGENERATE_TIMEOUT_MS = 5000;
const SAVE_TIMEOUT_MS = 5000;
const REGENERATE_TIMEOUT_LABEL = "session-regenerate-timeout";
const SAVE_TIMEOUT_LABEL = "session-save-timeout";
// Session-callback contract shared by regenerate() and save(): express-session
// reports exactly once through err; wrap into promise form.
function sessionCallbackToPromise(action) {
return new Promise((resolve, reject) => action((err) => (err ? reject(err) : resolve())));
}
// Fails closed on missing machinery (the login binder's rule): a rebinder
// silently missing the tombstone write or the remember re-issue would leave
// the owner on a dead sid or a resurrectable credential instead of failing
// loudly at construction.
function requireDeps(deps) {
const missing = [
"withTimeout",
"destroyBrowserSessionsForUser",
"writeRevokedSidTombstone",
"getSessionDisplayId",
"ensureRememberLoginSessionId",
"buildBrowserSessionAuditFromRequest",
"setRememberLoginCookie",
"markRememberLoginSessionFresh",
"upsertActiveBrowserSessionCacheEntry",
"clearRememberLoginCookie",
"revokeRememberLoginRegistryEntry",
].filter((key) => typeof deps?.[key] !== "function");
if (missing.length) {
throw new Error(`createCredentialSessionRebinder: missing required deps: ${missing.join(", ")}`);
}
}
function createCredentialSessionRebinder(deps) {
requireDeps(deps);
const {
withTimeout,
destroyBrowserSessionsForUser,
writeRevokedSidTombstone,
getSessionDisplayId,
ensureRememberLoginSessionId,
buildBrowserSessionAuditFromRequest,
setRememberLoginCookie,
markRememberLoginSessionFresh,
upsertActiveBrowserSessionCacheEntry,
clearRememberLoginCookie,
revokeRememberLoginRegistryEntry,
logger = console,
} = deps;
// The ONE shared core. Steps run in exactly this order.
//
// `user` is BOTH the identity to re-bind (email/accountId/accountEpoch) and
// the remember-mint material — the routes pass the post-change row view
// ({ ...user, password: hashedPassword } / { ...user, secret: newSecret } /
// { ...user, email: newEmail }) so the remember fingerprint matches the row
// the mint will live against. `destroyAs` overrides ONLY the identity the
// user-wide destroy matches on — the email change passes the OLD email so
// old-email sessions and remember entries are the ones swept, while the
// re-bind below lands on the new email.
async function rebindOwnerSession(req, res, { user, destroyAs } = {}) {
// (a) Destroy every session of the user — NO exclusion. The destroyer
// tombstones + store-destroys each match (the current sid included when
// the cache scan sees it) and revokes remember credentials user-wide.
const sessionInvalidation = await destroyBrowserSessionsForUser(destroyAs || user);
// adpanel:credential-session-rebind — the destroyer's scan is cache-based
// and can miss THIS request's own sid (a session record absent from the
// active-session cache still holds a live store record), so the
// pre-regeneration sid is tombstoned explicitly, exactly like the login
// binder: an in-flight request of the old session must not be able to
// re-save its authenticated record after the regenerate destroys it. A
// tombstone that cannot be made durable still leaves the regenerate
// below applied (warn + continue — the destroy above already swept the
// cache-visible copies).
const preRegenerateSid = String(req.sessionID || "").trim();
if (preRegenerateSid && !(await writeRevokedSidTombstone(preRegenerateSid))) {
logger.warn(`[security] Could not tombstone pre-regeneration session ${getSessionDisplayId(preRegenerateSid)} during credential change; the regenerate below still applies`);
}
await withTimeout(
sessionCallbackToPromise((cb) => req.session.regenerate(cb)),
REGENERATE_TIMEOUT_MS,
REGENERATE_TIMEOUT_LABEL
);
// (c) Re-bind the owner's identity onto the fresh session. The email
// change passes the NEW email here (after destroying by the old one).
req.session.user = user.email;
req.session.accountId = Number(user.id);
req.session.accountEpoch = Number(user.session_epoch || 0);
// (c2) Rebuild the browser-session audit object, mirroring the login
// binder's position exactly. adpanel:credential-session-rebind — the
// regenerate above wiped the audit, and the active-session inventory is
// built FROM it: without this rebuild the inventory record degrades to
// its defaults (no UA/IP/createdAt) until the next touch, and the
// forceFreshId mint's audit re-sync below would be a no-op. The ensured
// id is pre-mint lineage bookkeeping; the flagged mint re-points the
// audit at the identifier it actually issued.
const rememberLoginId = ensureRememberLoginSessionId(req);
req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, user.email, rememberLoginId);
// (d) Re-issue the remember credential against the post-change material.
// adpanel:remember-fresh-reissue — this mint follows a user-wide remember
// revoke (step a), so the rule is mandatory: forceFreshId guarantees a NEW
// identifier is minted and the session's audit copy is re-synced, never
// the just-revoked id resurrected under a fresh lease. A refused mint
// (remote-proxy-trust gate) bails out with no expiry — matching the
// binder's tolerated early bail-out, nothing to clean up below.
const rememberExpiresAt = setRememberLoginCookie(req, res, user, { forceFreshId: true });
markRememberLoginSessionFresh(req, rememberExpiresAt);
const mintedRememberLoginId = rememberExpiresAt
? String(req.session.rememberLoginId || "").trim()
: "";
try {
// (e) The regenerated session is the owner's live record from here on.
upsertActiveBrowserSessionCacheEntry(req.sessionID, req.session);
// (f) Bounded save — same posture as the login binder.
await withTimeout(
sessionCallbackToPromise((cb) => req.session.save(cb)),
SAVE_TIMEOUT_MS,
SAVE_TIMEOUT_LABEL
);
// adpanel:tombstone-skip-signal — same conversion as the login binder:
// the store's tombstone guard reports a refused write as SUCCESS, so a
// save SKIPPED for a tombstone read error must not resolve as a finished
// rebind.
const storeWriteSkipReason = req.session?.[Symbol.for("adpanel:storeWriteSkipped")];
if (storeWriteSkipReason) {
throw new Error(`session store write skipped (${storeWriteSkipReason})`);
}
} catch (err) {
// (g) Post-mint failure hygiene, identical to the login binder's: a
// visibly-failed credential change must not leave a live 365-day
// credential behind — the just-minted cookie is cleared, its registry
// entry revoked (awaited; the revoke never rejects), the regenerated sid
// is tombstoned so a late store write cannot commit the authenticated
// record behind the route's 500, and the ORIGINAL error is rethrown so
// each route's existing 500 handling is unchanged. A regenerate failure
// happens before any mint: nothing to clean, rethrown as-is.
if (mintedRememberLoginId) {
clearRememberLoginCookie(req, res);
await revokeRememberLoginRegistryEntry(mintedRememberLoginId);
}
const postFailureSid = String(req.sessionID || "").trim();
if (postFailureSid && !(await writeRevokedSidTombstone(postFailureSid))) {
logger.warn(`[security] Could not tombstone post-regeneration session ${getSessionDisplayId(postFailureSid)} after a failed credential change; a late store write may still commit the rebind's record`);
}
throw err;
}
return { sessionInvalidation };
}
// adpanel:binder-call-contract — same rule as the login binder: the factory
// returns an OBJECT carrying the named async method, never a bare callable,
// so a contract flip fails loudly at the call sites instead of vanishing
// into a TypeError on a hot path.
return { rebindOwnerSession };
}
module.exports = { createCredentialSessionRebinder };