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:bcrypt-cost-parity — unit pins for the ONE bcrypt-cost module.
// resolveBcryptRounds is the single env resolver (default 12, sane clamp
// 10..15); parseHashCost must reject malformed rows (cost 0), because both
// the timing decision and the rehash decision derive from it; rehashIfStale
// must be upgrade-only, null on any internal failure, and never throw.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { DEFAULT_BCRYPT_ROUNDS, MIN_BCRYPT_ROUNDS, MAX_BCRYPT_ROUNDS, resolveBcryptRounds, parseHashCost, rehashIfStale, loadBcrypt, bcryptHashInputError } = require("./bcrypt-rounds");
// A real cost-12 hash produced once (bcrypt output is deterministic given
// the salt; we only need its shape here, so a fixed string is fine).
const COST_12_HASH = "$2b$12$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
// Real-shaped cost-10 and cost-14 strings (salt/checksum body transplanted).
const COST_10_HASH = "$2a$10$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
const COST_14_HASH = "$2y$14$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
// Above-ceiling rows (adpanel:bcrypt-cost-parity A-2): the old unbounded
// BCRYPT_ROUNDS env parse accepted 16..99 verbatim, so legacy rows can carry
// costs the current clamp can never produce again. Well-formed shapes, real
// parseable costs (parseHashCost's band is 04..31).
const COST_16_HASH = "$2a$16$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
const COST_20_HASH = "$2y$20$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
const COST_31_HASH = "$2b$31$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
test("resolveBcryptRounds defaults to 12 on unset, empty, garbage, zero and negative env", () => {
assert.strictEqual(DEFAULT_BCRYPT_ROUNDS, 12, "documented default is 12");
assert.strictEqual(resolveBcryptRounds({}), 12, "unset must give the default");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "" }), 12, "empty string must give the default");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "garbage" }), 12, "non-numeric must give the default");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "0" }), 12, "zero must give the default");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "-5" }), 12, "negative must give the default");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "12" }), 12);
});
test("resolveBcryptRounds clamps into the sane 10..15 band", () => {
assert.strictEqual(MIN_BCRYPT_ROUNDS, 10, "documented floor is 10");
assert.strictEqual(MAX_BCRYPT_ROUNDS, 15, "documented ceiling is 15");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "4" }), 10, "below-floor values clamp up to 10");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "8" }), 10, "8 clamps to the floor (cost-parity band)");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "10" }), 10, "in-band values pass through");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "15" }), 15, "in-band values pass through");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "20" }), 15, "above-ceiling values clamp down to 15");
assert.strictEqual(resolveBcryptRounds({ BCRYPT_ROUNDS: "31" }), 15);
});
// adpanel:env-int-clamp — the resolver must delegate to the ONE shared
// clamped-int helper with zeroPolicy "default": a non-positive value means
// "not configured" (fallback 12), NOT the band floor — this is the exact
// zero-handling the pre-consolidation private resolver had and the other
// campaign modules' floor policy intentionally differs from.
test("resolveBcryptRounds delegates to the shared clamped-int helper (no private env-parse copy, default zero policy)", () => {
const src = fs.readFileSync(path.join(__dirname, "bcrypt-rounds.js"), "utf8");
assert.ok(src.includes("resolveClampedInt("), "the resolver must consume utils/clamped-int.js");
assert.ok(src.includes('zeroPolicy: "default"'), "BCRYPT_ROUNDS must explicitly pin the default zero policy");
assert.ok(!src.includes("parseInt(String(env"), "no private parseInt resolver copy may remain");
});
test("parseHashCost extracts the embedded cost from well-formed $2a/$2b/$2y hashes", () => {
assert.strictEqual(parseHashCost(COST_12_HASH), 12);
assert.strictEqual(parseHashCost(COST_10_HASH), 10);
assert.strictEqual(parseHashCost(COST_14_HASH), 14);
assert.strictEqual(parseHashCost("$2a$04$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC"), 4, "zero-padded low costs parse");
// adpanel:bcrypt-cost-parity (A-2) — above-ceiling legacy rows are REAL
// parseable costs (not 0): the repair path must be able to audit them.
assert.strictEqual(parseHashCost(COST_16_HASH), 16);
assert.strictEqual(parseHashCost(COST_20_HASH), 20);
assert.strictEqual(parseHashCost(COST_31_HASH), 31, "cost 31 is the parse band's ceiling, still auditable");
});
test("parseHashCost returns 0 for malformed / truncated / foreign hashes", () => {
for (const bad of [
null,
undefined,
"",
"not-a-hash",
"$2a$99$xxx", // the prefix-only shape scripts/create-user.js validation used to accept
"$2a$10$", // truncated body
"$2a$10$short", // short body
"$2x$10$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", // unsupported prefix
"$1$10$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", // md5-crypt prefix
"$2a$32$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", // cost out of bcrypt's 04..31 range
"$2a$00$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", // cost 0 invalid
`$2a$10$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBCextra`, // trailing garbage
42,
{},
]) {
assert.strictEqual(parseHashCost(bad), 0, `malformed input must parse as 0: ${JSON.stringify(bad)}`);
}
});
test("native bcrypt verifies equivalent imported $2a$, $2b$, and $2y$ hashes without changing them", async () => {
const native = require("bcrypt");
const compatible = loadBcrypt();
for (const password of ["synthetic-password", "synthetic-\u00e9-\u263a-password"]) {
const generated = await native.hash(password, 4);
const body = generated.slice(4);
const imported = "$2y$" + body;
assert.strictEqual(await native.compare(password, imported), false, "control: the native backend rejects the imported prefix");
for (const prefix of ["$2a$", "$2b$", "$2y$"]) {
const hash = prefix + body;
assert.strictEqual(bcryptHashInputError(hash), null);
assert.strictEqual(await compatible.compare(password, hash), true);
assert.strictEqual(compatible.compareSync(password, hash), true);
assert.strictEqual(await new Promise((resolve, reject) => compatible.compare(password, hash, (error, result) => error ? reject(error) : resolve(result))), true);
assert.strictEqual(await compatible.compare("incorrect-password", hash), false);
assert.strictEqual(hash, prefix + body, "stored hash and its credential fingerprint remain unchanged");
}
}
assert.strictEqual(compatible.hash, native.hash);
assert.strictEqual(compatible.hashSync, native.hashSync);
});
test("CLI imports and panel comparisons use one shared bcrypt parser and backend adapter", () => {
for (const invalid of [null, "", "$2y$00$" + COST_12_HASH.slice(7), "$2y$32$" + COST_12_HASH.slice(7), "$2x$12$" + COST_12_HASH.slice(7), COST_12_HASH + "extra"]) {
assert.ok(bcryptHashInputError(invalid));
}
const root = path.join(__dirname, "..");
for (const filename of ["index.js", "scripts/create-user.js", "scripts/reset-recovery-codes.js"]) {
const source = fs.readFileSync(path.join(root, filename), "utf8");
assert.match(source, /const bcrypt = loadBcrypt\(\);/);
assert.doesNotMatch(source, /bcrypt = require\("bcrypt(?:js)?"\)/);
}
const cli = fs.readFileSync(path.join(root, "scripts", "create-user.js"), "utf8");
assert.match(cli, /resolveBcryptRounds, loadBcrypt, bcryptHashInputError/);
assert.doesNotMatch(cli, /function bcryptHashInputError|const BCRYPT_HASH_SHAPE/);
});
// Capturing fake bcrypt: records the requested cost, returns a well-formed
// hash carrying that cost (or throws, to exercise the failure path).
function makeFakeBcrypt({ fail = false } = {}) {
const calls = [];
return {
calls,
async hash(password, rounds) {
calls.push({ password, rounds });
if (fail) throw new Error("hash exploded");
const body = "n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC";
return `$2b$${String(rounds).padStart(2, "0")}$${body}`;
},
};
}
test("rehashIfStale upgrades a stale (cheaper) row to the configured rounds", async () => {
const fake = makeFakeBcrypt();
const upgraded = await rehashIfStale(COST_10_HASH, "correct-password", 12, { bcrypt: fake });
assert.strictEqual(upgraded, "$2b$12$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", "the upgraded hash must carry the target cost");
assert.deepStrictEqual(fake.calls, [{ password: "correct-password", rounds: 12 }]);
});
test("rehashIfStale never downgrades and never re-hashes a current row", async () => {
const fake = makeFakeBcrypt();
assert.strictEqual(await rehashIfStale(COST_12_HASH, "pw", 12, { bcrypt: fake }), null, "cost == rounds → no rehash");
assert.strictEqual(await rehashIfStale(COST_14_HASH, "pw", 12, { bcrypt: fake }), null, "cost > rounds → NEVER downgrade (in-band row: a legitimate operator choice)");
assert.deepStrictEqual(fake.calls, [], "no bcrypt.hash call may happen for current/stronger rows");
});
// adpanel:bcrypt-cost-parity (A-2) — repair-only heal: rows ABOVE the clamp
// ceiling (cost 16..31) are operator error from the old unbounded env parse.
// They answer SLOWER than the cost-rounds dummy (residual slower-direction
// timing oracle) and at cost 20+ the login's 8 s compare timeout fails —
// so the rehash direction is pathological-cost → configured rounds.
test("rehashIfStale repairs a pathological above-ceiling row DOWN to the configured rounds", async () => {
const fake = makeFakeBcrypt();
const repaired = await rehashIfStale(COST_20_HASH, "correct-password", 12, { bcrypt: fake });
assert.strictEqual(repaired, "$2b$12$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", "a cost-20 legacy row must be rewritten at the configured rounds");
assert.deepStrictEqual(fake.calls, [{ password: "correct-password", rounds: 12 }], "the repair hashes the proven password at the configured rounds");
// Boundary: the first cost the clamp can never produce (ceiling + 1)
// repairs even when the target is the ceiling itself — parity at rounds
// is the goal in BOTH directions.
const fake15 = makeFakeBcrypt();
assert.strictEqual(await rehashIfStale(COST_16_HASH, "pw", MAX_BCRYPT_ROUNDS, { bcrypt: fake15 }), "$2b$15$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", "cost 16 > ceiling repairs to rounds 15");
assert.deepStrictEqual(fake15.calls, [{ password: "pw", rounds: 15 }]);
// The parse band's top (cost 31) is still auditable and repairable.
const fake31 = makeFakeBcrypt();
assert.strictEqual(await rehashIfStale(COST_31_HASH, "pw", 12, { bcrypt: fake31 }), "$2b$12$n886gyiJjPF9JQSUfeIZTORcEU638uk3zvDVKtP3wjVP6zHOesJBC", "a cost-31 row repairs to the configured rounds");
});
test("rehashIfStale still refuses to rewrite unparseable rows in the repair direction", async () => {
const fake = makeFakeBcrypt();
// "$2a$99$xxx" is the prefix-only malformed shape: parseHashCost → 0, so
// it must stay refused (fail closed) even though 99 is numerically above
// the ceiling — only AUDITED rows may be rewritten.
assert.strictEqual(await rehashIfStale("$2a$99$xxx", "pw", 12, { bcrypt: fake }), null);
assert.deepStrictEqual(fake.calls, [], "refused repair calls must not reach bcrypt at all");
});
test("rehashIfStale returns null (never throws) on bad arguments, malformed hashes and internal failures", async () => {
const fake = makeFakeBcrypt();
const throwing = makeFakeBcrypt({ fail: true });
for (const [hash, password, rounds, deps] of [
[COST_10_HASH, "pw", 12, { bcrypt: throwing }], // internal hash() failure
[COST_10_HASH, "", 12, { bcrypt: fake }], // empty password
[COST_10_HASH, "pw", 0, { bcrypt: fake }], // bad target rounds
[COST_10_HASH, "pw", 99, { bcrypt: fake }],
[COST_10_HASH, "pw", "NaN", { bcrypt: fake }],
["$2a$99$xxx", "pw", 12, { bcrypt: fake }], // malformed source row: refuse to touch
["", "pw", 12, { bcrypt: fake }],
[null, "pw", 12, { bcrypt: fake }],
]) {
assert.strictEqual(await rehashIfStale(hash, password, rounds, deps), null, `must return null, never throw: ${JSON.stringify([hash, password, rounds])}`);
}
assert.deepStrictEqual(fake.calls, [], "refused calls must not reach bcrypt at all");
});
test("rehashIfStale rejects an upgrade whose own output fails to parse back at the target cost", async () => {
const broken = {
async hash() { return "$2b$99$short"; }, // malformed output (unparseable cost shape)
};
assert.strictEqual(await rehashIfStale(COST_10_HASH, "pw", 12, { bcrypt: broken }), null, "a hash we cannot audit must not be persisted");
});