Files
Kelx/tests/botproof-timing-safe.test.js
T
2026-11-30 16:32:37 +00:00

272 lines
13 KiB
JavaScript

"use strict";
// adpanel:botproof-timing-safe — source pins + behavior pins for the bot-proof
// seed comparison on the login surface.
//
// botProofSeed is a session-bound secret (generated by ensureBotProofSeed,
// validated by isBotProofValid against the form's botProof field in
// POST /login). Every other secret comparison on the login surface goes
// through the timing-safe helper safeCompare; isBotProofValid was the last
// one using a raw `===`. These pins hold the guarantees:
// 1. isBotProofValid compares through safeCompare and contains no raw
// `value === expected` secret compare;
// 2. the comparison still runs against the session seed (not a cookie) and
// keeps the truthy guard, so the function stays a pure boolean gate;
// 3. the behavior is byte-identical to the old `!!value && value ===
// expected` for every input class: safeCompare's typeof gate rejects
// non-strings exactly like strict equality did (including the
// ["<seed>"] array case a String() coercion would have let pass).
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 ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
// Brace-balanced extraction of a live source block (same shape as the
// extractBlock helper in update-plane-hardening.test.js): a naive
// slice-to-first-"\n}" would stop inside nested blocks or miss them. The scan
// skips // and /* */ comments so quote characters inside the adpanel: comment
// convention (e.g. an apostrophe) cannot desync the string tracker.
function extractBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
let i = start + startMarker.length;
let depth;
if (startMarker.endsWith("{")) {
// The marker already includes the opening brace.
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; continue; }
if (ch === inString) inString = null;
continue;
}
if (ch === "/" && source[i + 1] === "/") {
while (i < source.length && source[i] !== "\n") i += 1;
continue;
}
if (ch === "/" && source[i + 1] === "*") {
i += 2;
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
i += 1;
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);
}
const FN_MARKER = "function isBotProofValid(req, value) {";
const fnStart = indexSource.indexOf(FN_MARKER);
const fnSource = fnStart >= 0
? indexSource.slice(fnStart, indexSource.indexOf("\n}", fnStart))
: "";
test("pins: isBotProofValid compares through the timing-safe helper, not ===", () => {
assert.ok(fnStart >= 0, "isBotProofValid must still exist");
assert.ok(
fnSource.includes("safeCompare(value, expected)"),
"isBotProofValid must delegate the secret comparison to safeCompare"
);
assert.ok(
!fnSource.includes("value === expected"),
"isBotProofValid must not keep the raw non-constant-time secret compare"
);
});
test("pins: the comparison stays session-bound and boolean-gated", () => {
assert.ok(
fnSource.includes("req?.session?.botProofSeed"),
"validation must keep comparing against the session seed, not a cookie"
);
assert.ok(
fnSource.includes("!!value &&"),
"the truthy guard on the submitted value must remain"
);
});
// Execute the REAL extracted source (safeCompare + isBotProofValid) so the
// behavior pins cannot drift from what index.js actually ships.
function buildBotProofSandbox() {
const sandbox = { crypto, Buffer, console };
vm.createContext(sandbox);
vm.runInContext(
extractBlock(indexSource, "function safeCompare(a, b) {") + "\n" +
extractBlock(indexSource, FN_MARKER),
sandbox
);
return sandbox;
}
test("behavior: correct seed → true, wrong seed → false", () => {
const { isBotProofValid } = buildBotProofSandbox();
const seed = crypto.randomBytes(18).toString("hex");
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, seed), true);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, seed + "0"), false);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, seed.slice(0, -1)), false);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, seed.toUpperCase()), false);
});
test("behavior: empty value, missing seed, missing session → false", () => {
const { isBotProofValid } = buildBotProofSandbox();
const seed = crypto.randomBytes(18).toString("hex");
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, ""), false);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, undefined), false);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: seed } }, null), false);
assert.strictEqual(isBotProofValid({ session: {} }, seed), false);
assert.strictEqual(isBotProofValid({ session: { botProofSeed: "" } }, seed), false);
assert.strictEqual(isBotProofValid({}, seed), false);
assert.strictEqual(isBotProofValid(undefined, seed), false);
});
test("behavior: non-string values are rejected exactly like strict === did", () => {
const { isBotProofValid } = buildBotProofSandbox();
const seed = crypto.randomBytes(18).toString("hex");
const req = { session: { botProofSeed: seed } };
// typeof gate in safeCompare must keep rejecting non-strings — in
// particular ["<seed>"], which a String() coercion would wrongly accept.
assert.strictEqual(isBotProofValid(req, true), false);
assert.strictEqual(isBotProofValid(req, 42), false);
assert.strictEqual(isBotProofValid(req, {}), false);
assert.strictEqual(isBotProofValid(req, []), false);
assert.strictEqual(isBotProofValid(req, [seed]), false);
assert.strictEqual(isBotProofValid(req, new String(seed)), false);
assert.strictEqual(isBotProofValid(req, NaN), false);
});
test("behavior: parity with the old `!!value && value === expected` on an input corpus", () => {
const { isBotProofValid } = buildBotProofSandbox();
const seed = crypto.randomBytes(18).toString("hex");
const oldIsValid = (value, expected) => !!value && value === expected;
const corpus = [
seed, seed + "0", seed.slice(0, -1), "", " ", "0", "false", "null",
seed.toUpperCase(), "random guess", "<script>alert(1)</script>",
undefined, null, false, true, 0, 1, NaN, Infinity, 42, -1,
{}, [], [seed], [seed, seed], ["wrong"], [{ toString: () => seed }],
new String(seed), new String("wrong"), new String(""),
Symbol("seed"), Buffer.from(seed), () => seed,
];
for (const value of corpus) {
assert.strictEqual(
isBotProofValid({ session: { botProofSeed: seed } }, value),
oldIsValid(value, seed),
`behavior diverged from the old === for input: ${String(value)}`
);
assert.strictEqual(typeof isBotProofValid({ session: { botProofSeed: seed } }, value), "boolean");
}
});
// ---------------------------------------------------------------------------
// adpanel:botproof-timing-safe — CSRF twin alignment. isValidLoginCsrfToken
// compares the SAME class of session-bound secret with the SAME timing-safe
// helper as isBotProofValid, so it must keep the SAME strict shape: the
// submitted token must BE a string. The old String(token || "") coercion
// would let ["<token>"] stringify into a match — the exact hole the botproof
// fix closed. Deliberately STRICTER than before (fail-closed for non-strings
// incl. boxed Strings); no legit flow breaks: the login template's hidden
// input and the fetch's URLSearchParams(FormData(form)) echo both send a
// primitive string, and hpp collapses duplicate urlencoded fields to their
// last STRING element (node_modules/hpp/lib/index.js — body check applies to
// urlencoded content types only, so a JSON body's array _csrf is
// attacker-shaped and now fails closed).
// ---------------------------------------------------------------------------
const CSRF_FN_MARKER = "function isValidLoginCsrfToken(req, token) {";
const csrfFnStart = indexSource.indexOf(CSRF_FN_MARKER);
const csrfFnSource = csrfFnStart >= 0
? indexSource.slice(csrfFnStart, indexSource.indexOf("\n}", csrfFnStart))
: "";
test("pins: isValidLoginCsrfToken keeps the strict botProof shape (no String() coercion of the submitted token)", () => {
assert.ok(csrfFnStart >= 0, "isValidLoginCsrfToken must still exist");
assert.ok(
csrfFnSource.includes("!!token && typeof token === \"string\" && safeCompare(token,"),
"the CSRF compare must keep the strict shape: a truthy STRING token into safeCompare (the botProof parity contract its comment documents)"
);
assert.ok(
!csrfFnSource.includes("String(token"),
"the submitted token must never be String()-coerced — String([\"<token>\"]) would stringify an array into a match"
);
assert.ok(
csrfFnSource.includes("req.session.loginCsrfToken"),
"validation must stay bound to the session token, not a cookie"
);
});
// Execute the REAL extracted source (safeCompare + both validators) so the
// parity pins cannot drift from what index.js actually ships.
function buildCsrfSandbox() {
const sandbox = { crypto, Buffer, console };
vm.createContext(sandbox);
vm.runInContext(
extractBlock(indexSource, "function safeCompare(a, b) {") + "\n" +
extractBlock(indexSource, FN_MARKER) + "\n" +
extractBlock(indexSource, CSRF_FN_MARKER),
sandbox
);
return sandbox;
}
test("behavior: string token passes, every non-string shape fails closed", () => {
const { isValidLoginCsrfToken } = buildCsrfSandbox();
const token = crypto.randomBytes(32).toString("hex");
const req = { session: { loginCsrfToken: token } };
assert.strictEqual(isValidLoginCsrfToken(req, token), true, "the legit client shape (hidden-input value / fetch echo) passes");
assert.strictEqual(isValidLoginCsrfToken(req, token + "0"), false);
assert.strictEqual(isValidLoginCsrfToken(req, token.slice(0, -1)), false);
// The coercion hole this closes: an array carrying the token stringified
// into a match under the old String(token || "") shape.
assert.strictEqual(isValidLoginCsrfToken(req, [token]), false, "array-wrapped token must be rejected (the String() coercion hole)");
assert.strictEqual(isValidLoginCsrfToken(req, [token, token]), false);
assert.strictEqual(isValidLoginCsrfToken(req, ["wrong"]), false);
assert.strictEqual(isValidLoginCsrfToken(req, { toString: () => token }), false, "a toString-forged object must be rejected");
assert.strictEqual(isValidLoginCsrfToken(req, new String(token)), false, "even a boxed String must be rejected (stricter, fail-closed)");
assert.strictEqual(isValidLoginCsrfToken(req, 42), false);
assert.strictEqual(isValidLoginCsrfToken(req, true), false);
assert.strictEqual(isValidLoginCsrfToken(req, {}), false);
assert.strictEqual(isValidLoginCsrfToken(req, []), false);
assert.strictEqual(isValidLoginCsrfToken(req, ""), false);
assert.strictEqual(isValidLoginCsrfToken(req, undefined), false);
assert.strictEqual(isValidLoginCsrfToken(req, null), false);
assert.strictEqual(isValidLoginCsrfToken(req, Buffer.from(token)), false);
});
test("behavior: the CSRF and botProof validators reject the identical non-string corpus (same shape, one contract)", () => {
const { isValidLoginCsrfToken, isBotProofValid } = buildCsrfSandbox();
const secret = crypto.randomBytes(32).toString("hex");
const csrfReq = { session: { loginCsrfToken: secret } };
const bpReq = { session: { botProofSeed: secret } };
const corpus = [
secret, secret + "0", secret.slice(0, -1), "", " ", "0",
undefined, null, false, true, 0, 1, NaN, Infinity, 42,
{}, [], [secret], [secret, secret], ["wrong"], [{ toString: () => secret }],
new String(secret), new String("wrong"),
Symbol("x"), Buffer.from(secret), () => secret,
];
for (const value of corpus) {
assert.strictEqual(
isValidLoginCsrfToken(csrfReq, value),
isBotProofValid(bpReq, value),
`the two same-class secret compares diverged for input: ${String(value)}`
);
}
});