Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,289 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:response-save-bounded — pins for the six response-gating session
|
||||
// saves bound with the house withTimeout (index.js).
|
||||
//
|
||||
// The audited gap: the six `req.session.save(callback)` calls that gate
|
||||
// login/captcha responses lacked the 5s withTimeout discipline every other
|
||||
// store write on this surface has (the login binder's save in
|
||||
// utils/login-session-bind.js, the restore lookups). A stalled Redis client
|
||||
// would wedge the request indefinitely — the limiter already hangs first on
|
||||
// the same client, and the 300s requestTimeout backstop is too coarse — so
|
||||
// the browser sits on a dead POST /login / POST /api/captcha/verify.
|
||||
//
|
||||
// Contract locked here:
|
||||
// - Each of the six saves is wrapped as
|
||||
// `withTimeout(<save promise>, 5000, <unique label>)`: respond after the
|
||||
// save settles OR 5s elapses, whichever first.
|
||||
// - The response body/status is unchanged and ships EXACTLY ONCE — on
|
||||
// settle, on save error, and on timeout (the pre-fix error-ignored
|
||||
// posture is preserved: the save's err was always ignored at these
|
||||
// sites; withTimeout's rejection is swallowed BEFORE the response so a
|
||||
// timeout still ships the ORIGINAL response, never a 500).
|
||||
// - withTimeout leaves the underlying promise running: a late completion
|
||||
// writing after the response is harmless (same sid; the
|
||||
// tombstone-guarded store wrapper — index.js
|
||||
// wrapSessionStoreWithTombstoneGuard — refuses set()/touch() for
|
||||
// revoked sids and settles the callback once, so a late write can never
|
||||
// resurrect a destroyed session). The six records are independent
|
||||
// single-session field writes (rotated CSRF token, bot-proof seed,
|
||||
// pending-captcha record, grace fields) — none participates in the
|
||||
// binder's tombstone→regenerate→save choreography, so a late write
|
||||
// corrupts no ordering; a CSRF token that did not persist self-heals via
|
||||
// the documented next-request re-403.
|
||||
// - The behavioral harness vm-extracts the REAL withTimeout and the REAL
|
||||
// bounded save block (sendError's) and drives it with fake sessions and
|
||||
// controllable fake timers — no real 5s waits.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
|
||||
const LABELS = [
|
||||
"captcha-verify-unlock-save",
|
||||
"captcha-verify-no-pending-save",
|
||||
"captcha-verify-finalize-save",
|
||||
"login-sendError-save",
|
||||
"login-captcha-challenge-json-save",
|
||||
"login-captcha-challenge-render-save",
|
||||
];
|
||||
|
||||
function endIndexOfBlock(source, startMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `marker ${startMarker} not found`);
|
||||
const bodyStart = source.indexOf("{", start);
|
||||
let depth = 0;
|
||||
for (let i = bodyStart; i < source.length; i += 1) {
|
||||
if (source[i] === "{") depth += 1;
|
||||
else if (source[i] === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) return i + 1;
|
||||
}
|
||||
}
|
||||
assert.fail(`unbalanced braces after marker ${startMarker}`);
|
||||
}
|
||||
|
||||
async function drain() {
|
||||
// Several macrotask turns: promise reactions, setImmediate callbacks and
|
||||
// the fake-timer rejections all settle within a couple of turns.
|
||||
for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins: all six sites bounded, response expressions unchanged.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("source: exactly six bounded saves, each withTimeout(..., 5000, <unique label>)", () => {
|
||||
for (const label of LABELS) {
|
||||
const re = new RegExp(
|
||||
`withTimeout\\(\\s*new Promise\\(\\(resolve\\) => req\\.session\\.save\\(\\(\\) => resolve\\(\\)\\)\\),\\s*5000,\\s*"${label}"`,
|
||||
"m"
|
||||
);
|
||||
assert.match(indexSource, re, `the ${label} save must be bounded at 5000ms like the binder's save`);
|
||||
assert.strictEqual(
|
||||
(indexSource.split(`"${label}"`).length - 1), 1,
|
||||
`the ${label} label must appear exactly once — no second copy of the gate`
|
||||
);
|
||||
}
|
||||
assert.strictEqual(
|
||||
(indexSource.split("adpanel:response-save-bounded").length - 1), 6,
|
||||
"the tag documents the fix at exactly the six bounded sites"
|
||||
);
|
||||
});
|
||||
|
||||
test("source: region order — the three captcha saves sit before POST /login, the three login saves after", () => {
|
||||
const postLoginAt = indexSource.indexOf('app.post("/login"');
|
||||
assert.ok(postLoginAt > 0, "POST /login registration must exist");
|
||||
const at = (s) => indexSource.indexOf(s);
|
||||
assert.ok(at("captcha-verify-unlock-save") < at("captcha-verify-no-pending-save"));
|
||||
assert.ok(at("captcha-verify-no-pending-save") < at("captcha-verify-finalize-save"));
|
||||
assert.ok(at("captcha-verify-finalize-save") < postLoginAt, "captcha verify completes before the login handler");
|
||||
assert.ok(postLoginAt < at("login-sendError-save"), "sendError's bounded save rides the POST /login handler");
|
||||
assert.ok(at("login-sendError-save") < at("login-captcha-challenge-json-save"));
|
||||
assert.ok(at("login-captcha-challenge-json-save") < at("login-captcha-challenge-render-save"));
|
||||
});
|
||||
|
||||
test("source: every response expression is unchanged (bounded path + fallback)", () => {
|
||||
// sendError: the save-gated render AND the no-save fallback both keep the
|
||||
// original expression — exactly two occurrences.
|
||||
assert.strictEqual(
|
||||
(indexSource.match(/res\.status\(status\)\.render\("login", renderData\)/g) || []).length, 2,
|
||||
"sendError keeps its bounded render + direct fallback, byte-identical"
|
||||
);
|
||||
assert.strictEqual(
|
||||
(indexSource.match(/res\.status\(403\)\.json\(jsonPayload\)/g) || []).length, 2,
|
||||
"sendCaptchaChallenge JSON keeps its bounded response + direct fallback"
|
||||
);
|
||||
assert.strictEqual(
|
||||
(indexSource.match(/res\.status\(403\)\.render\("login", renderData\)/g) || []).length, 2,
|
||||
"sendCaptchaChallenge render keeps its bounded render + direct fallback"
|
||||
);
|
||||
assert.ok(
|
||||
indexSource.includes('.then(() => res.json({ ok: true, unlocked: true }));'),
|
||||
"the unlock response body is unchanged inside the bounded then"
|
||||
);
|
||||
assert.ok(
|
||||
indexSource.includes('.then(() => res.status(409).json({ ok: false, error: "no-pending-login", redirect: "/login" }));'),
|
||||
"the stray-solve 409 body is unchanged inside the bounded then"
|
||||
);
|
||||
assert.ok(
|
||||
indexSource.includes('error: completedLogin.error || "login-not-finalized",'),
|
||||
"the failed-finalize envelope is unchanged"
|
||||
);
|
||||
});
|
||||
|
||||
test("source: the catch sits BEFORE the then — a timeout must ship the ORIGINAL response, never skip it", () => {
|
||||
// `.catch(() => { }).then(() => res.` is the load-bearing order: rejection
|
||||
// (timeout) is swallowed first, then the response fires. A
|
||||
// `.then(...).catch(...)` order would silently DROP the response on
|
||||
// timeout.
|
||||
assert.strictEqual(
|
||||
(indexSource.match(/\)\.catch\(\(\) => \{ \}\)\.then\(\(\) => res\./g) || []).length, 6,
|
||||
"all six bounded saves use catch-before-then"
|
||||
);
|
||||
});
|
||||
|
||||
test("source: the response-gating saves are the login/captcha surfaces' only inline saves — no fourth copy", () => {
|
||||
// Every other save on the login surface must ride the shared binder (its
|
||||
// own bounded save) — pinned by tests/login-session-bind-module.test.js.
|
||||
// Here: the six bounded sites must be the only bare `req.session.save(`
|
||||
// occurrences between the captcha verify route and the end of the login
|
||||
// handler.
|
||||
const start = indexSource.indexOf('app.post("/api/captcha/verify"');
|
||||
const end = indexSource.indexOf('app.post("/logout"');
|
||||
assert.ok(start > 0 && end > start, "region markers must exist");
|
||||
const region = indexSource.slice(start, end);
|
||||
const bareSaves = region.match(/return req\.session\.save\(/g) || [];
|
||||
assert.strictEqual(bareSaves.length, 0,
|
||||
"no unbounded callback-style save may exist in the captcha/login region");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Behavioral: the REAL withTimeout + the REAL bounded sendError save block
|
||||
// under vm, with fake sessions and controllable fake timers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function extractWithTimeoutSource() {
|
||||
const marker = 'function withTimeout(promise, ms, label = "timeout") {';
|
||||
return indexSource.slice(indexSource.indexOf(marker), endIndexOfBlock(indexSource, marker));
|
||||
}
|
||||
|
||||
function extractBoundedSaveBlock(label) {
|
||||
const labelAt = indexSource.indexOf(`"${label}"`);
|
||||
assert.ok(labelAt > 0, `label ${label} must exist`);
|
||||
const start = indexSource.lastIndexOf("return withTimeout(", labelAt);
|
||||
const endMarker = 'render("login", renderData));';
|
||||
const endAt = indexSource.indexOf(endMarker, labelAt);
|
||||
assert.ok(start > 0 && endAt > start, `bounded block around ${label} must be sliceable`);
|
||||
return indexSource.slice(start, endAt + endMarker.length);
|
||||
}
|
||||
|
||||
function buildHarness() {
|
||||
const timers = [];
|
||||
const context = vm.createContext({
|
||||
setTimeout: (fn, ms) => {
|
||||
timers.push({ fn, ms, cleared: false });
|
||||
return timers.length;
|
||||
},
|
||||
clearTimeout: (id) => {
|
||||
if (timers[id - 1]) timers[id - 1].cleared = true;
|
||||
},
|
||||
});
|
||||
vm.runInContext(extractWithTimeoutSource(), context, { filename: "index.js#withTimeout" });
|
||||
// The extracted block's free variables: withTimeout (context global),
|
||||
// req/res/status (parameters) and renderData (the builder's render payload,
|
||||
// threaded through as a parameter).
|
||||
const run = vm.runInContext(
|
||||
`(req, res, status, renderData) => {\n${extractBoundedSaveBlock("login-sendError-save")}\n}`,
|
||||
context,
|
||||
{ filename: "index.js#bounded-save" }
|
||||
);
|
||||
return { timers, run };
|
||||
}
|
||||
|
||||
function makeRes() {
|
||||
const res = { statuses: [], rendered: [], jsonBodies: [] };
|
||||
res.status = (code) => { res.statuses.push(code); return res; };
|
||||
res.render = (view, data) => { res.rendered.push([view, data]); return res; };
|
||||
res.json = (body) => { res.jsonBodies.push(body); return res; };
|
||||
return res;
|
||||
}
|
||||
|
||||
const RENDER_DATA = { error: "bad login", loginEmail: "a@b.c" };
|
||||
|
||||
test("behavior: a save that NEVER settles cannot wedge the response — the 5s timer ships it", async () => {
|
||||
const { timers, run } = buildHarness();
|
||||
const res = makeRes();
|
||||
const session = {
|
||||
save(cb) { this.registeredCb = cb; }, // stores the callback, never settles
|
||||
};
|
||||
const p = run({ session }, res, 401, RENDER_DATA);
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 0, "no response before the save settles or times out");
|
||||
assert.strictEqual(typeof session.registeredCb, "function", "the save callback was wired");
|
||||
assert.strictEqual(timers.length, 1, "exactly one timer armed");
|
||||
assert.strictEqual(timers[0].ms, 5000, "bounded at 5s like the binder's save");
|
||||
|
||||
timers[0].fn(); // the timeout rejects with Error(label)
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "the response ships on timeout");
|
||||
assert.deepStrictEqual(res.statuses, [401], "the ORIGINAL status, never a 500");
|
||||
assert.deepStrictEqual(res.rendered[0], ["login", RENDER_DATA], "the ORIGINAL body");
|
||||
assert.strictEqual(timers[0].cleared, true, "withTimeout's finally cleared the timer");
|
||||
await p; // the chain must settle without surfacing a rejection
|
||||
});
|
||||
|
||||
test("behavior: a save that settles first ships the response WITHOUT waiting for the timer", async () => {
|
||||
const { timers, run } = buildHarness();
|
||||
const res = makeRes();
|
||||
const session = { save(cb) { setImmediate(() => cb()); } };
|
||||
const p = run({ session }, res, 403, RENDER_DATA);
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "the response shipped on settle");
|
||||
assert.deepStrictEqual(res.statuses, [403], "original status");
|
||||
assert.strictEqual(timers[0].cleared, true, "the timer was disarmed by the settle");
|
||||
await p;
|
||||
});
|
||||
|
||||
test("behavior: a save callback arriving AFTER the timeout cannot double-respond", async () => {
|
||||
const { timers, run } = buildHarness();
|
||||
const res = makeRes();
|
||||
const session = { save(cb) { this.cb = cb; } };
|
||||
const p = run({ session }, res, 401, RENDER_DATA);
|
||||
await drain();
|
||||
timers[0].fn();
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "response shipped on timeout");
|
||||
session.cb(); // late settle — withTimeout left it running; resolve() is a no-op
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "STILL exactly one response");
|
||||
await p;
|
||||
});
|
||||
|
||||
test("behavior: a save ERROR still ships the original response (error-ignored posture preserved)", async () => {
|
||||
const { run } = buildHarness();
|
||||
const res = makeRes();
|
||||
const session = { save(cb) { setImmediate(() => cb(new Error("store down"))); } };
|
||||
const p = run({ session }, res, 400, RENDER_DATA);
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "the response ships despite the save error");
|
||||
assert.deepStrictEqual(res.statuses, [400], "original status");
|
||||
await p;
|
||||
});
|
||||
|
||||
test("behavior: a synchronous save() throw cannot wedge or crash — the response still ships", async () => {
|
||||
const { run } = buildHarness();
|
||||
const res = makeRes();
|
||||
const session = { save() { throw new Error("store detached"); } };
|
||||
const p = run({ session }, res, 400, RENDER_DATA);
|
||||
await drain();
|
||||
assert.strictEqual(res.rendered.length, 1, "the executor throw becomes a swallowed rejection, then the response");
|
||||
assert.deepStrictEqual(res.statuses, [400], "original status");
|
||||
await p;
|
||||
});
|
||||
Reference in new issue
Block a user