Files
Kelx/tests/secure-pin-durable.test.js
T
2026-11-30 16:32:37 +00:00

543 lines
27 KiB
JavaScript

"use strict";
// adpanel:secure-pin-durable — pins for the Upgrade-only Secure-sync
// middleware (index.js, mounted directly after the session middleware).
//
// The constraint the fix enforces: the Secure pin must reach the STORED
// session record, not just the in-request cookie object and this response's
// Set-Cookie. express-session's hash() (node_modules/express-session/index.js
// :611-626) EXCLUDES the top-level `cookie` key from its replacer, so flipping
// `req.session.cookie.secure` alone never flips isModified (:440-442); with
// `resave:false` the end handler (:349-369) only issues connect-redis's
// bare-EXPIRE touch() (connect-redis dist :55-62 — TTL bump, value never
// rewritten) and the stored record keeps cookie.secure=false. In a mixed
// HTTP+HTTPS auto-mode deployment the un-pinned record then lets
// express-session re-issue a NON-Secure Set-Cookie over plain HTTP until some
// real write dirties the session. The fix sets a plain enumerable string-keyed
// session field (`cookieSecurePinned = true`) alongside the pin: that key IS
// included in hash(), so the first pin dirties the session and the end
// handler's save persists the whole record (one extra store SET per session
// lifetime; the `cookie.secure !== true` guard makes every later request a
// no-op). Upgrade-only semantics are preserved: the branch requires
// `cookieSecureForRequest(req) === true`, so insecure requests never enter it
// and neither the pin nor the marker is ever cleared or downgraded.
//
// Pins held here:
// 1. Library semantics (the mechanism the fix leans on), pinned against the
// INSTALLED express-session source + a line-for-line replica of hash():
// cookie is excluded from hash() while plain string keys are included, so
// the marker — not the cookie flip — is what flips the resave:false save
// trigger. If an express-session upgrade changes these semantics, the
// pins fail loudly instead of silently rotting the fix.
// 2. Source pins on index.js: the marker assignment exists INSIDE the
// guarded branch, only on pin-change (exactly one occurrence), the branch
// guard keeps the idempotence (`cookie.secure !== true`) and upgrade-only
// (`cookieSecureForRequest(req) === true`) predicates, the
// adpanel:secure-pin-durable comment is present, and nothing in the
// region ever downgrades (no false/null/delete of the pin or the marker).
// Method gating verified: express-session's end handler has NO
// HTTP-method gate (shouldSave never reads req.method), so an HTTPS GET
// pin persists at the end of that same GET — pinned here too.
// 3. Behavioral end-to-end with the REAL express-session@1.19.0 middleware
// (MemoryStore-backed, connect-redis-shaped serialization: set()
// stringifies the whole session, touch() never rewrites the value) and
// the REAL vm-extracted index.js middleware + cookieSecureForRequest:
// HTTP-generated record carries cookie.secure=false; the HTTPS request
// pins (marker + secure=true), persists BOTH into the stored JSON, and
// the marker survives the JSON round-trip; a second HTTPS request is a
// no-op (touch only, no SET); a later HTTP request neither downgrades the
// record nor re-issues the cookie non-Secure (express-session suppresses
// re-sending a Secure cookie over HTTP, index.js:242-246). A PRE-FIX
// control (pin without the marker) reproduces the audited regression —
// only a touch, record stays secure=false, HTTP re-issues non-Secure —
// proving the marker is the load-bearing difference.
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 crypto = require("node:crypto");
const http = require("node:http");
const express = require("express");
const session = require("express-session");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const ES_INDEX_JS = path.join(ROOT, "node_modules", "express-session", "index.js");
const CONNECT_REDIS_CJS = path.join(ROOT, "node_modules", "connect-redis", "dist", "connect-redis.cjs");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const esSource = fs.readFileSync(ES_INDEX_JS, "utf8");
function countOccurrences(haystack, needle) {
let count = 0;
let pos = 0;
for (;;) {
const idx = haystack.indexOf(needle, pos);
if (idx < 0) return count;
count += 1;
pos = idx + needle.length;
}
}
function indexOfOrThrow(haystack, needle, from = 0) {
const idx = haystack.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
// Extract the braced block starting at `start` (the opening `{` is the first
// non-whitespace char after, or IS the last char of, `startMarker`).
function extractBracedBlock(source, startMarker, from = 0) {
const start = indexOfOrThrow(source, startMarker, from);
let i = start + startMarker.length;
let depth;
if (startMarker.endsWith("{")) {
depth = 1;
} else {
while (i < source.length && /\s/.test(source[i])) i += 1;
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
depth = 1;
}
let inString = null;
while (i < source.length && depth > 0) {
i += 1;
const ch = source[i];
if (inString) {
if (ch === "\\") i += 1;
else if (ch === inString) inString = null;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
else if (ch === "{") depth += 1;
else if (ch === "}") depth -= 1;
}
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
return source.slice(start, i + 1);
}
function secureSyncRegion() {
const start = indexOfOrThrow(indexSource, "// Upgrade-only Secure sync:");
const endMarker = "next();\n});";
const end = indexOfOrThrow(indexSource, endMarker, start) + endMarker.length;
return indexSource.slice(start, end);
}
// ---------------------------------------------------------------------------
// 1. Library semantics — the mechanism the fix leans on.
// ---------------------------------------------------------------------------
test("express-session hash() excludes ONLY the top-level cookie key (installed library source)", () => {
const hashBlock = extractBracedBlock(esSource, "function hash(sess) {");
// The replacer must skip `cookie` only when it is a top-level key of sess —
// every other enumerable string-keyed field is serialized and therefore
// hashed (this is what makes a plain session field a dirtying marker).
assert.ok(
hashBlock.includes("if (this === sess && key === 'cookie') {"),
"hash() must keep excluding the top-level sess.cookie key from its digest"
);
assert.ok(hashBlock.includes("JSON.stringify(sess, function (key, val) {"), "hash() must serialize via the replacer");
});
test("express-session isModified is hash-based and the end handler save path has NO method gate", () => {
const isModifiedBlock = extractBracedBlock(esSource, "function isModified(sess) {");
assert.ok(
isModifiedBlock.includes("originalHash !== hash(sess)"),
"isModified must remain the hash comparison — the marker's dirtying trigger"
);
// The end handler must call req.session.save when shouldSave fires, with no
// HTTP-method predicate anywhere in shouldSave/shouldTouch: an HTTPS GET pin
// must persist at the end of that same GET, not wait for a POST.
const shouldSaveBlock = extractBracedBlock(esSource, "function shouldSave(req) {");
assert.doesNotMatch(shouldSaveBlock, /\bmethod\b/i, "shouldSave must not be method-gated");
const shouldTouchBlock = extractBracedBlock(esSource, "function shouldTouch(req) {");
assert.doesNotMatch(shouldTouchBlock, /\bmethod\b/i, "shouldTouch must not be method-gated");
const saveBranchAt = indexOfOrThrow(esSource, "if (shouldSave(req)) {");
const touchBranchAt = indexOfOrThrow(esSource, "} else if (storeImplementsTouch && shouldTouch(req)) {", saveBranchAt);
assert.ok(touchBranchAt > saveBranchAt, "end handler must save BEFORE falling back to a bare touch");
const saveBranch = esSource.slice(saveBranchAt, touchBranchAt);
assert.ok(saveBranch.includes("req.session.save(function onsave(err)"), "save branch must persist the whole session");
});
test("connect-redis touch() stays a bare EXPIRE (value never rewritten) while set() stringifies the session", () => {
const crSource = fs.readFileSync(CONNECT_REDIS_CJS, "utf8");
const touchBlock = extractBracedBlock(crSource, "async touch(sid, sess, cb) {");
assert.ok(
touchBlock.includes("await this.client.expire(key, this.getTTL(sess));"),
"touch() must remain a bare EXPIRE — a TTL bump cannot persist cookie.secure"
);
assert.doesNotMatch(touchBlock, /\bset\b|\.set\(/i, "touch() must not write the stored value");
const setBlock = extractBracedBlock(crSource, "async set(sid, sess, cb) {");
assert.ok(
setBlock.includes("this.serializer.stringify(sess)"),
"set() must persist the full serialized session — the durable-pin write"
);
});
test("replica of express-session hash(): cookie flip is NOT dirtying, the marker IS (resave:false trigger)", () => {
// Line-for-line replica of express-session@1.19.0 hash()
// (node_modules/express-session/index.js:611-626); the source pins above
// hold the replica and the library in lockstep.
function hash(sess) {
const str = JSON.stringify(sess, function (key, val) {
if (this === sess && key === "cookie") {
return undefined;
}
return val;
});
return crypto.createHash("sha1").update(str, "utf8").digest("hex");
}
const before = {
cookie: { originalMaxAge: 31536000000, secure: false, httpOnly: true, path: "/", sameSite: "lax" },
seed: "state",
};
const h0 = hash(before);
// The audited trigger gap: flipping cookie.secure alone must NOT change the
// digest — this is exactly why the bare pin never reached the store.
const cookieFlipOnly = { ...before, cookie: { ...before.cookie, secure: true } };
assert.equal(hash(cookieFlipOnly), h0, "cookie.secure flip alone must not dirty the session (hash excludes sess.cookie)");
// The fix's mechanism: the plain enumerable string key IS included, so the
// marker flips the digest → isModified → the end handler saves.
const pinned = { ...cookieFlipOnly, cookieSecurePinned: true };
assert.notEqual(hash(pinned), h0, "the marker must dirty the session so the end handler persists the pin");
// Store round-trip stability: the marker survives JSON serialization (what
// connect-redis' serializer.stringify produces and get() parses back), and
// the re-inflated record still hashes differently from the un-pinned one —
// so the dirtying persists across requests, not just within one.
const roundTripped = JSON.parse(JSON.stringify(pinned));
assert.equal(roundTripped.cookieSecurePinned, true, "marker must survive the store JSON round-trip");
assert.equal(roundTripped.cookie.secure, true, "pinned cookie.secure must survive the store JSON round-trip");
assert.equal(hash(roundTripped), hash(pinned), "re-inflated record must keep the post-pin digest");
});
// ---------------------------------------------------------------------------
// 2. Source pins on the index.js Secure-sync middleware.
// ---------------------------------------------------------------------------
test("middleware pins cookie.secure AND sets the dirtying marker, only on pin-change, upgrade-only", () => {
const region = secureSyncRegion();
// The AGENTS.md comment convention tag must document the constraint here.
assert.ok(region.includes("// adpanel:secure-pin-durable —"), "adpanel:secure-pin-durable comment must be present");
// Guard: pin-change only (idempotence — no re-pin, no re-dirty once
// cookie.secure is already true) and upgrade-only (secure request).
assert.ok(
region.includes("if (req.session?.cookie && req.session.cookie.secure !== true && cookieSecureForRequest(req) === true) {"),
"branch guard must keep the idempotence + upgrade-only predicates"
);
// Order: the pin, then the marker, then next() — the marker must be INSIDE
// the guarded branch, so it is set only when the pin actually changed the
// value.
const pinAt = indexOfOrThrow(region, "req.session.cookie.secure = true;");
const markerAt = indexOfOrThrow(region, "req.session.cookieSecurePinned = true;");
const nextAt = indexOfOrThrow(region, "next();", markerAt);
assert.ok(pinAt < markerAt && markerAt < nextAt, "marker must follow the pin and precede next() inside the branch");
// Exactly one marker reference (the assignment): the marker must never be
// written outside the pin-change branch.
assert.equal(
countOccurrences(region, "cookieSecurePinned"),
1,
"the marker must appear exactly once — inside the guarded branch, on pin-change only"
);
// The marker must be a PLAIN string-keyed enumerable assignment: Symbol keys
// and non-enumerable properties are invisible to hash()'s JSON.stringify.
assert.match(region, /req\.session\.cookieSecurePinned = true;/, "marker must be a plain enumerable string key");
// Upgrade-only: no downgrade path may exist anywhere in the region — the pin
// and the marker are never cleared, never set false.
for (const forbidden of [
"cookie.secure = false",
"cookieSecurePinned = false",
"cookieSecurePinned = null",
"cookieSecurePinned = undefined",
"delete req.session.cookieSecurePinned",
]) {
assert.ok(!region.includes(forbidden), `no downgrade in the Secure-sync middleware: ${forbidden}`);
}
});
// ---------------------------------------------------------------------------
// 3. Behavioral end-to-end — the REAL express-session + REAL extracted
// middleware against a connect-redis-shaped recording store.
// ---------------------------------------------------------------------------
// Real cookieSecureForRequest vm-extracted from index.js, bound to auto mode
// (SESSION_COOKIE_SECURE unset → explicit consts false). It resolves to
// `req.connection.encrypted || req.secure === true` WIDENED with the
// peer-trust leg `getTrustedForwardedProto(req) === "https"`
// (adpanel:cookie-secure-trusted-proto): a TRUSTED_PROXY_IPS-trusted proxy
// reporting https must also yield Secure. The extraction therefore injects
// the REAL peer-trust helper chain from index.js (TRUSTED_PROXY_IPS env set
// through getTrustedForwardedProto), not a stub — the widened leg is the
// real resolver, no test-only copy. The behavioral flows below are
// unaffected by the widening: every request in them either rides
// `trust proxy loopback` + XFP https (req.secure already true — leg 2) or
// carries no https claim (resolver returns "" — leg 3 false).
function makeRealCookieSecureForRequest() {
const fnSource = extractBracedBlock(indexSource, "function cookieSecureForRequest(req) {");
// The peer-trust helper chain: everything from the TRUSTED_PROXY_IPS const
// through getTrustedForwardedProto (the same slice shape
// tests/remote-proxy-misconfig-warning.test.js uses for its runtime
// sandbox, extended past getLastForwardedValue to reach the resolver the
// widened leg calls).
const protoStart = indexSource.indexOf("function getTrustedForwardedProto(req)");
const protoBlock = extractBracedBlock(indexSource, "function getTrustedForwardedProto(req)");
const helpers = indexSource.slice(
indexSource.indexOf("const TRUSTED_PROXY_IPS = new Set("),
protoStart + protoBlock.length
);
const sandbox = vm.createContext({
SESSION_COOKIE_SECURE_EXPLICIT: false,
SESSION_COOKIE_SECURE: false,
net: require("node:net"),
process: { env: { TRUSTED_PROXY_IPS: "" } },
});
vm.runInContext(helpers, sandbox, { filename: "index.js#peer-trust-helpers" });
vm.runInContext(fnSource, sandbox, { filename: "index.js#cookieSecureForRequest" });
const fn = sandbox.cookieSecureForRequest;
assert.strictEqual(typeof fn, "function", "cookieSecureForRequest extraction failed");
assert.strictEqual(typeof sandbox.getTrustedForwardedProto, "function",
"the widened leg's resolver must be defined in the extraction sandbox");
return fn;
}
// The REAL Secure-sync middleware vm-extracted from index.js. The
// warnRemoteProxyMisconfigOnce telemetry line (adpanel:remote-proxy-misconfig-
// warning, its own finding + test) is orthogonal to the pin and stubbed here.
function makeRealSecureSyncMiddleware() {
const startMarker = "app.use((req, res, next) => {";
const start = indexOfOrThrow(indexSource, startMarker, indexOfOrThrow(indexSource, "// Upgrade-only Secure sync:"));
const endMarker = "next();\n});";
const end = indexOfOrThrow(indexSource, endMarker, start) + endMarker.length;
const snippet = indexSource.slice(start, end);
let captured = null;
const sandbox = vm.createContext({
app: { use: (fn) => { captured = fn; } },
cookieSecureForRequest: makeRealCookieSecureForRequest(),
warnRemoteProxyMisconfigOnce: () => { },
});
vm.runInContext(snippet, sandbox, { filename: "index.js#secure-sync-middleware" });
assert.strictEqual(typeof captured, "function", "Secure-sync middleware extraction failed");
return captured;
}
// connect-redis-shaped store: set() persists the FULL serialized session
// (serializer.stringify), touch() is a bare EXPIRE that never rewrites the
// value. `records` mirrors the stored JSON bytes; `ops` mirrors the wire ops.
class RecordingRedisShapedStore extends session.MemoryStore {
constructor() {
super();
this.records = new Map(); // sid -> last stored JSON string
this.ops = []; // { op, sid, raw? } in wire order
}
set(sid, sess, cb) {
const raw = JSON.stringify(sess);
this.records.set(sid, raw);
this.ops.push({ op: "set", sid, raw });
return super.set(sid, sess, cb);
}
touch(sid, sess, cb) {
// Bare EXPIRE: TTL bump only — the stored value is deliberately untouched.
this.ops.push({ op: "touch", sid });
return cb();
}
get(sid, cb) {
return super.get(sid, cb);
}
}
// Mirrors index.js: trust proxy loopback (TRUST_PROXY default) so a
// X-Forwarded-Proto: https request from loopback yields req.secure === true;
// session config mirrors the monolith's (resave:false, saveUninitialized:
// false, rolling:true, secure:"auto").
function buildSessionApp(middleware) {
const store = new RecordingRedisShapedStore();
const app = express();
app.set("trust proxy", "loopback");
app.use(session({
store,
secret: "secure-pin-durable-test-secret",
name: "adpanel.sid",
resave: false,
saveUninitialized: false,
rolling: true,
cookie: { maxAge: 300000, sameSite: "lax", secure: "auto", httpOnly: true },
}));
app.use(middleware);
app.get("/seed", (req, res) => { req.session.seed = "state"; res.json({ ok: true }); });
app.get("/probe", (req, res) => {
res.json({
secure: req.session.cookie.secure === true,
pinned: req.session.cookieSecurePinned === true,
});
});
return { app, store };
}
function get(port, path, headers) {
return new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path, headers }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("error", reject);
res.on("end", () => {
let parsed = null;
try { parsed = JSON.parse(body); } catch { }
resolve({ status: res.statusCode, setCookie: res.headers["set-cookie"] || [], body: parsed });
});
});
req.on("error", reject);
});
}
const HTTPS_HEADERS = (sid) => ({ cookie: sid, "x-forwarded-proto": "https" });
const HTTP_HEADERS = (sid) => ({ cookie: sid });
function sidFrom(setCookie) {
const sc = setCookie.find((c) => c.startsWith("adpanel.sid="));
return sc ? sc.split(";")[0] : null;
}
async function runFlow(middleware) {
const { app, store } = buildSessionApp(middleware);
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.on("listening", resolve));
const port = server.address().port;
try {
// A: HTTP seed — a session created over plain HTTP in auto mode.
const a = await get(port, "/seed", {});
const sid = sidFrom(a.setCookie);
assert.ok(sid, "seed must mint a session cookie");
const afterA = store.ops.filter((o) => o.op === "set").length;
// B: same sid arrives over HTTPS.
const setsBeforeB = store.ops.length;
const b = await get(port, "/probe", HTTPS_HEADERS(sid));
const bSets = store.ops.slice(setsBeforeB).filter((o) => o.op === "set");
// C: HTTPS again — the idempotence probe.
const setsBeforeC = store.ops.length;
const c = await get(port, "/probe", HTTPS_HEADERS(sid));
const cSets = store.ops.slice(setsBeforeC).filter((o) => o.op === "set");
// D: plain HTTP again — the downgrade probe.
const setsBeforeD = store.ops.length;
const d = await get(port, "/probe", HTTP_HEADERS(sid));
const dSets = store.ops.slice(setsBeforeD).filter((o) => o.op === "set");
const setsBefore = { afterA, setsBeforeB, setsBeforeC, setsBeforeD };
return { store, a, b, c, d, sid, bSets, cSets, dSets, setsBefore };
} finally {
server.close();
}
}
test("real express-session: HTTPS pin persists cookie.secure=true + marker into the STORED record (one extra SET)", async () => {
const { store, a, b, sid, bSets, setsBefore } = await runFlow(makeRealSecureSyncMiddleware());
// A: HTTP-generated record — stored WITHOUT Secure, no marker. Read from
// the ordered op list: records.get(sid) holds the LATEST stored JSON, and
// B's pin has already replaced it by the time the flow returns.
const allSets = store.ops.filter((o) => o.op === "set");
const seededJson = JSON.parse(allSets[0].raw);
assert.equal(seededJson.cookie.secure, false, "HTTP-generated record must start cookie.secure=false");
assert.ok(!("cookieSecurePinned" in seededJson), "no marker before any HTTPS request");
// B: the HTTPS request must persist BOTH the pin and the marker via exactly
// ONE extra SET (the end handler save, NOT a bare touch).
assert.equal(bSets.length, 1, "the pin request must produce exactly one store SET");
const pinnedRecord = JSON.parse(bSets[0].raw);
assert.equal(pinnedRecord.cookie.secure, true, "SET must persist cookie.secure=true");
assert.equal(pinnedRecord.cookieSecurePinned, true, "SET must persist the dirtying marker");
assert.equal(b.body.secure, true, "in-request cookie must be pinned");
assert.equal(b.body.pinned, true, "in-request marker must be set");
assert.ok(/Secure/.test(b.setCookie[0] || ""), "HTTPS response must carry the Secure attribute");
// Method gating, empirically: request B was a GET and its end handler
// performed the save above — express-session's save path is not
// method-gated, so the pin does not wait for a POST. One extra store SET
// per session lifetime: the only two sets in the whole flow are A's init
// save and B's pin save.
assert.equal(
store.ops.filter((o) => o.op === "set").length,
2,
"the pin must cost exactly one extra store SET beyond the session's init save"
);
assert.ok(setsBefore.afterA === 1, "sanity: the seed produced the single init save");
});
test("real express-session: marker survives the store JSON round-trip and the re-request is a no-op", async () => {
const { b, c, cSets, store } = await runFlow(makeRealSecureSyncMiddleware());
// C: probe response is served from the session INFLATED from the stored
// JSON — reading pinned:true here proves the marker survived
// serializer.stringify → get → parse → Session reconstruction.
assert.equal(c.body.pinned, true, "marker must survive the store JSON round-trip");
assert.equal(c.body.secure, true, "cookie.secure must survive the store JSON round-trip");
assert.deepEqual(cSets, [], "idempotent re-request must NOT re-dirty (touch only, no SET)");
// The stored record still holds both facts (touch never rewrote them).
const stored = store.ops.filter((o) => o.op === "set");
const finalRecord = JSON.parse(stored[stored.length - 1].raw);
assert.equal(finalRecord.cookie.secure, true, "stored cookie.secure must stay pinned");
assert.equal(finalRecord.cookieSecurePinned, true, "stored marker must stay pinned");
assert.equal(b.body.pinned, true, "first HTTPS request set the marker");
});
test("real express-session: no downgrade — HTTP never clears the pin/marker and never re-issues non-Secure", async () => {
const { d, dSets, store } = await runFlow(makeRealSecureSyncMiddleware());
assert.deepEqual(dSets, [], "HTTP request must not write the store");
assert.equal(d.body.secure, true, "HTTP must not downgrade the pinned cookie");
assert.equal(d.body.pinned, true, "HTTP must not clear the marker");
const stored = store.ops.filter((o) => o.op === "set");
const finalRecord = JSON.parse(stored[stored.length - 1].raw);
assert.equal(finalRecord.cookie.secure, true, "stored record must survive HTTP un-downgraded");
assert.equal(finalRecord.cookieSecurePinned, true, "stored marker must survive HTTP un-cleared");
// express-session suppresses re-sending a Secure cookie over plain HTTP
// (index.js:242-246) — the durable pin turns the pre-fix non-Secure
// re-issue into NO re-issue at all.
assert.equal(
d.setCookie.find((c) => c.startsWith("adpanel.sid=")),
undefined,
"HTTP must not re-issue the now-Secure session cookie (express-session suppression)"
);
});
test("PRE-FIX control: pin without the marker reproduces the audited regression (touch-only, record stays non-Secure, HTTP re-issues non-Secure)", async () => {
// Replica of the pre-fix middleware — pin only, no dirtying marker. This
// control proves the marker is the load-bearing difference AND that the
// harness itself detects the regression the fix closes: if express-session
// ever starts persisting cookie-only flips, the POST-FIX pins above become
// vacuous and this control's non-Secure re-issue disappears.
const preFix = (req, res, next) => {
if (req.session?.cookie && req.session.cookie.secure !== true && req.secure === true) {
req.session.cookie.secure = true;
}
next();
};
const { b, d, bSets, dSets } = await runFlow(preFix);
assert.deepEqual(bSets, [], "cookie-only flip must NOT trigger a store SET (hash excludes sess.cookie)");
assert.equal(b.body.secure, true, "pre-fix pin still upgrades the in-request cookie");
assert.equal(d.body.secure, false, "pre-fix: the STORED record stays non-Secure (pin never persisted)");
assert.ok(
d.setCookie.find((c) => c.startsWith("adpanel.sid=")),
"pre-fix: HTTP re-issues the session cookie"
);
const reissued = d.setCookie.find((c) => c.startsWith("adpanel.sid="));
assert.doesNotMatch(reissued, /Secure/, "pre-fix: the HTTP re-issue lacks Secure — the audited leak window");
});