Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+217
View File
@@ -0,0 +1,217 @@
"use strict";
// adpanel:login-bind-one-true-home — ONE shared implementation of the
// session-binding core that every authentication completion path must run:
// tombstone the pre-regeneration sid (when the session was already
// authenticated, or carries protected pending auth state via the predicate
// dep below), regenerate the session under its 5s timeout, bind
// user/accountId/accountEpoch/rememberLoginId/browserSessionAudit, mark the
// remember-login lifetime fresh (issuing the remember cookie), upsert the
// active browser-session cache entry, and save under its 5s timeout. If
// anything after the remember mint fails (the cache upsert, the beforeSave
// hook, or the bounded save), the just-minted credential is revoked first —
// a visibly-failed login 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 two callers — the POST /login success path and
// completePendingCaptchaLogin (both index.js) — previously carried line-for-
// line parallel copies of this sequence. Copies of a security-critical
// sequence drift: a guard added to one login path but not the other re-opens
// exactly the destroy/save resurrection race the tombstone closes (an
// in-flight request of the OLD session re-saving the authenticated record
// after regenerate destroyed it). A change to this sequence must land in one
// place; the tombstone-before-regenerate ordering and the 5s timeouts are
// structural, pinned by tests/session-resurrection-tombstone.test.js against
// this file.
//
// Deliberately per-surface and therefore NOT here (they stay at the call
// sites, reattached via the two interstitial hooks where the captcha path
// historically interleaves them): suspension re-checks, captcha/pending
// state clears, per-path TOTP budget resets, throttle gate clears, and the
// response rendering (sendOk vs JSON envelope).
//
// 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/dashboard-assistant-tools.js).
// The two timeouts are load-bearing (same values the inline copies used):
// a hung store callback must not wedge the login 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 server-create service's rule): a
// binder silently missing the tombstone write would re-open the resurrection
// race instead of failing loudly at construction.
function requireDeps(deps) {
const missing = [
"withTimeout",
"writeRevokedSidTombstone",
"sessionCarriesProtectedPendingAuthState",
"getSessionDisplayId",
"ensureRememberLoginSessionId",
"buildBrowserSessionAuditFromRequest",
"setRememberLoginCookie",
"markRememberLoginSessionFresh",
"upsertActiveBrowserSessionCacheEntry",
"clearRememberLoginCookie",
"revokeRememberLoginRegistryEntry",
].filter((key) => typeof deps?.[key] !== "function");
if (missing.length) {
throw new Error(`createLoginSessionBinder: missing required deps: ${missing.join(", ")}`);
}
}
function createLoginSessionBinder(deps) {
requireDeps(deps);
const {
withTimeout,
writeRevokedSidTombstone,
sessionCarriesProtectedPendingAuthState,
getSessionDisplayId,
ensureRememberLoginSessionId,
buildBrowserSessionAuditFromRequest,
setRememberLoginCookie,
markRememberLoginSessionFresh,
upsertActiveBrowserSessionCacheEntry,
clearRememberLoginCookie,
revokeRememberLoginRegistryEntry,
logger = console,
} = deps;
// The ONE shared core. Steps run in exactly this order; the optional hooks
// run the callers' own steps at the positions the historical copies used
// (the captcha path clears its local state after identity binding and
// resets the TOTP budget after the cache upsert, before the save).
async function bindLoginSession(req, res, { user, afterIdentityBinding, beforeSave } = {}) {
// Re-login while already authenticated: tombstone the pre-regeneration
// sid so an in-flight request from the old session cannot re-save the
// authenticated record after the regenerate destroys it.
//
// adpanel:login-bind-preauth-pending-tombstone — a PRE-auth sid can
// still carry PROTECTED pending auth state (the solved-captcha flag and
// the pending-captcha-login record; the predicate dep owns those key
// names as index.js concepts). A pre-auth request holding that state
// can land after regenerate() and re-save it under the old sid: a
// stolen pre-auth cookie plus a matching IP+UA fingerprint then revives
// a captcha-cleared (and possibly 2FA-verified) login within the
// pending state's TTL — the same destroy/save resurrection race, one
// step earlier. Sids carrying protected pending state are therefore
// tombstoned exactly like authenticated ones; pre-auth sids WITHOUT it
// stay skipped (tombstoning every login sid would bloat Redis with raw
// login volume — the carriers are bounded by solved-captcha volume).
if (req.session?.user || sessionCarriesProtectedPendingAuthState(req.session)) {
const preRegenerateSid = String(req.sessionID || "").trim();
if (preRegenerateSid && !(await writeRevokedSidTombstone(preRegenerateSid))) {
logger.warn(`[security] Could not tombstone pre-regeneration session ${getSessionDisplayId(preRegenerateSid)}; the regenerate below still applies`);
}
}
await withTimeout(
sessionCallbackToPromise((cb) => req.session.regenerate(cb)),
REGENERATE_TIMEOUT_MS,
REGENERATE_TIMEOUT_LABEL
);
req.session.user = user.email;
req.session.accountId = Number(user.id);
req.session.accountEpoch = Number(user.session_epoch || 0);
const rememberLoginId = ensureRememberLoginSessionId(req);
req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, user.email, rememberLoginId);
if (afterIdentityBinding) await afterIdentityBinding();
// adpanel:login-bind-save-failure-hygiene — a visibly-failed login must
// not leave a live 365-day credential behind. The remember cookie is set
// and its registry entry minted BEFORE the bounded session save, so a
// save failure/timeout used to ride the cookie out on the 500 response
// (the caller sees "login failed", yet the browser stays remembered).
// Any failure after this mint therefore revokes THIS call's just-minted
// credential — cookie cleared, registry entry revoked (the revoke is
// awaited and never rejects; its own failure is dead-letter covered) —
// and rethrows the ORIGINAL error, so the routes' existing 500 handling
// is unchanged. A regenerate failure happens before any mint: nothing to
// clean, rethrown as before.
const rememberExpiresAt = setRememberLoginCookie(req, res, user);
markRememberLoginSessionFresh(req, rememberExpiresAt);
// The regenerated session guarantees this id is fresh for THIS call, and
// the truthy expiry proves the cookie was actually issued (an early
// bail-out of setRememberLoginCookie leaves nothing to clean up).
const mintedRememberLoginId = rememberExpiresAt
? String(req.session.rememberLoginId || "").trim()
: "";
try {
upsertActiveBrowserSessionCacheEntry(req.sessionID, req.session);
if (beforeSave) await beforeSave();
await withTimeout(
sessionCallbackToPromise((cb) => req.session.save(cb)),
SAVE_TIMEOUT_MS,
SAVE_TIMEOUT_LABEL
);
// adpanel:tombstone-skip-signal — the store's tombstone guard reports a
// refused write as SUCCESS (finish(null) is its caller contract), so a
// save SKIPPED for a tombstone READ ERROR would otherwise resolve here
// as "login OK" with nothing persisted and none of the hygiene below
// firing. The guard marks the live session object with this registry
// symbol ONLY for a read-error skip (confirmed-revocation skips stay
// silent — dropping a dead sid's write is intentional; touch skips are
// unchanged), so presence here converts the false success into the
// labeled failure whose catch below revokes the just-minted remember
// credential, tombstones the regenerated sid, and rethrows → the
// routes' existing 500 handling.
const storeWriteSkipReason = req.session?.[Symbol.for("adpanel:storeWriteSkipped")];
if (storeWriteSkipReason) {
throw new Error(`session store write skipped (${storeWriteSkipReason})`);
}
} catch (err) {
if (mintedRememberLoginId) {
clearRememberLoginCookie(req, res);
await revokeRememberLoginRegistryEntry(mintedRememberLoginId);
}
// adpanel:login-bind-save-failure-tombstone — the failed save was
// saving the REGENERATED sid, whose record is already authenticated
// (user/accountId/audit bound above, before the mint). A late-landing
// store write of an in-flight request could commit that authenticated
// record behind the 500 response; tombstone the regenerated sid so
// the store's tombstone guard refuses the late save. A login that
// answered 500 must not leave a live authenticated session when the
// store write lands late. The write is internally time-bounded and
// returns bool; on false this warns and still rethrows the ORIGINAL
// error. A regenerate failure never reaches this block (it throws
// before the try): nothing was minted, nothing is tombstoned.
const postFailureSid = String(req.sessionID || "").trim();
if (postFailureSid && !(await writeRevokedSidTombstone(postFailureSid))) {
logger.warn(`[security] Could not tombstone post-regeneration session ${getSessionDisplayId(postFailureSid)}; a late store write may still commit the failed login's record`);
}
throw err;
}
}
// adpanel:binder-call-contract — the factory's returned contract is an
// OBJECT carrying the named `bindLoginSession` async method, never a bare
// callable. Both index.js call sites (POST /login success and
// completePendingCaptchaLogin) invoke the instance's `bindLoginSession`
// method against exactly this shape; a bare-function return made that call
// throw `TypeError: loginSessionBinder.bindLoginSession is not a function`
// on EVERY successful login. The integration pin in
// tests/login-session-bind-module.test.js executes the real extracted call
// statements against a real factory instance, so any silent flip of this
// contract fails CI instead of failing every login at runtime. The method
// keeps its name for stack traces.
return { bindLoginSession };
}
module.exports = { createLoginSessionBinder };