144 lines
6.0 KiB
JavaScript
144 lines
6.0 KiB
JavaScript
"use strict";
|
|
|
|
// Follow-up to the 2026-09-08 create-flow round (finding M1): the root CLI
|
|
// scripts/create-user.js generated its printed recovery codes with
|
|
// Math.random(), a seeded PRNG that must never produce secret material
|
|
// (CWE-338). The codes are account credentials — they are bcrypt-hashed into
|
|
// the users row and shown once on the terminal — so every character now comes
|
|
// from the OS CSPRNG via crypto.randomInt (rejection-sampled internally, so
|
|
// the alphabet stays uniformly covered even if its size changes).
|
|
//
|
|
// The CLI's seed-exposure decision stands (see SECURITY-FIXES.md): whoever
|
|
// can run this script can read the users table directly. This round only
|
|
// fixes the randomness source. The generator is behavior-tested by extracting
|
|
// its live source (same technique as tests/password-policy-parity.test.js),
|
|
// because the script connects to the database when required.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const crypto = require("node:crypto");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const CLI_JS = path.join(ROOT, "scripts", "create-user.js");
|
|
|
|
const cliSource = fs.readFileSync(CLI_JS, "utf8");
|
|
|
|
function sliceBetween(source, startMarker, endMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
|
|
const end = source.indexOf(endMarker, start + startMarker.length);
|
|
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
return haystack.split(needle).length - 1;
|
|
}
|
|
|
|
// Comment lines may legitimately name Math.random (the rationale does), so
|
|
// randomness assertions run against executable code only.
|
|
function codeOnly(source) {
|
|
return source.split("\n").filter(line => !line.trim().startsWith("//")).join("\n");
|
|
}
|
|
|
|
// The alphabet constants and generateRecoveryCode live together inside
|
|
// main(); this slice is exactly the code under test.
|
|
const generatorSource = sliceBetween(
|
|
cliSource,
|
|
"const RECOVERY_CODE_COUNT",
|
|
"const plainRecoveryCodes = [];"
|
|
);
|
|
const generateRecoveryCode = new Function(
|
|
"crypto",
|
|
`${generatorSource}\nreturn generateRecoveryCode;`
|
|
)(crypto);
|
|
|
|
const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
const CODE_LENGTH = 8;
|
|
const CODE_COUNT = 7;
|
|
|
|
test("generator produces length-8 codes from the unambiguous alphabet only", () => {
|
|
for (let i = 0; i < 1000; i++) {
|
|
const code = generateRecoveryCode();
|
|
assert.strictEqual(code.length, CODE_LENGTH, "codes must keep their 8-character length");
|
|
assert.match(code, /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]+$/,
|
|
"codes must only use RECOVERY_CODE_CHARS (no I/O/0/1 lookalikes)");
|
|
}
|
|
});
|
|
|
|
test("generator output is uniformly distributed across the alphabet", () => {
|
|
// 32,000 characters -> 1,000 expected per character. With a true uniform
|
|
// source the per-char count's sigma is ~31, so the 700-1300 band sits far
|
|
// beyond any legitimate fluctuation while still catching gross bias (a
|
|
// skewed modulo or a partially-used alphabet).
|
|
const DRAWS = 4000;
|
|
const counts = new Map();
|
|
const seen = new Set();
|
|
for (let i = 0; i < DRAWS; i++) {
|
|
const code = generateRecoveryCode();
|
|
seen.add(code);
|
|
for (const char of code) {
|
|
counts.set(char, (counts.get(char) || 0) + 1);
|
|
}
|
|
}
|
|
const expected = (DRAWS * CODE_LENGTH) / ALPHABET.length;
|
|
for (const char of ALPHABET) {
|
|
const count = counts.get(char) || 0;
|
|
assert.ok(count >= expected * 0.7 && count <= expected * 1.3,
|
|
`character ${char} drew ${count} times (expected ~${expected}); distribution is skewed`);
|
|
}
|
|
});
|
|
|
|
test("codes are collision-free at generation scale", () => {
|
|
const seen = new Set();
|
|
for (let i = 0; i < 4000; i++) {
|
|
const code = generateRecoveryCode();
|
|
assert.ok(!seen.has(code), "no duplicate codes may appear in one batch");
|
|
seen.add(code);
|
|
}
|
|
});
|
|
|
|
test("the generator sources its randomness from the OS CSPRNG", () => {
|
|
assert.ok(generatorSource.includes("crypto.randomInt(RECOVERY_CODE_CHARS.length)"),
|
|
"generateRecoveryCode must draw via crypto.randomInt");
|
|
assert.ok(!codeOnly(generatorSource).includes("Math.random"),
|
|
"generateRecoveryCode must not fall back to the seeded PRNG");
|
|
assert.ok(cliSource.includes('require("crypto")'),
|
|
"the CLI must import node:crypto");
|
|
});
|
|
|
|
test("the avatar picker is the only remaining Math.random in the CLI", () => {
|
|
// Tripwire: this file exists to mint credentials. Any future Math.random
|
|
// needs a conscious decision, not an unnoticed default.
|
|
assert.strictEqual(countOccurrences(codeOnly(cliSource), "Math.random"), 1,
|
|
"no Math.random may return outside the cosmetic avatar picker");
|
|
const avatarFn = sliceBetween(
|
|
cliSource,
|
|
"function pickDefaultAvatar",
|
|
"async function ensureUsersColumn"
|
|
);
|
|
assert.ok(avatarFn.includes("Math.random()"),
|
|
"the remaining use must be the non-security avatar selection");
|
|
});
|
|
|
|
test("plaintext codes are still hashed before storage and shown only once", () => {
|
|
const generationBlock = sliceBetween(
|
|
cliSource,
|
|
"const plainRecoveryCodes = [];",
|
|
"const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes);"
|
|
);
|
|
assert.ok(generationBlock.includes("for (let i = 0; i < RECOVERY_CODE_COUNT; i++)"),
|
|
"the batch loop must still generate RECOVERY_CODE_COUNT codes");
|
|
// adpanel:bcrypt-cost-parity — the cost literal was consciously replaced by
|
|
// the shared BCRYPT_ROUNDS resolver (a hardcoded cost-10 row answered login
|
|
// compares measurably faster than the panel's dummy hash, an account
|
|
// oracle). The assertion's contract is unchanged: each code is bcrypt-
|
|
// hashed before it reaches the users row, at the panel's own cost.
|
|
assert.ok(generationBlock.includes("bcrypt.hashSync(code, BCRYPT_ROUNDS)"),
|
|
"each code must be bcrypt-hashed before it reaches the users row");
|
|
assert.ok(cliSource.includes("const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes);"),
|
|
"only the hashed codes may be persisted to the users row");
|
|
});
|