Files
Kelx/utils/bcrypt-rounds.js
T
2026-11-30 16:32:37 +00:00

356 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// adpanel:bcrypt-cost-parity — ONE home for the bcrypt cost decision. The
// cost of a bcrypt comparison is embedded in the STORED hash string, not in
// configuration, so two rows written at different costs answer
// bcrypt.compare at measurably different speeds. POST /login equalizes
// unknown accounts against DUMMY_BCRYPT_HASH (hashSync at the resolved
// rounds); any stored row whose embedded cost differs from that same
// resolved rounds re-opens an account-existence oracle through response
// timing (a cost-10 row answers ~60 ms against a ~215 ms cost-12 dummy —
// ~6σ separation inside the login throttle's 20-probe per-account budget).
// The constraint this module documents: every stored hash and the dummy
// hash must cost the same, so there is exactly one env resolver here (no
// inline parseInt copies), a cost parser to audit stored rows, and a
// rehash-on-login helper that upgrades stale rows on a successful password
// proof. Downgrade policy (conscious amendment, A-2): security parity is
// cost == rounds in BOTH directions. A row INSIDE the clamp band
// (cost <= MAX_BCRYPT_ROUNDS) that is stronger than the configured rounds is
// a legitimate operator choice and is never rewritten ("never downgrade" —
// lowering BCRYPT_ROUNDS does not rewrite still-valid stronger rows). A row
// ABOVE the ceiling (cost 16..31) is operator error from the old UNBOUNDED
// BCRYPT_ROUNDS env parse (it accepted 16..99 verbatim): such a row answers
// SLOWER than the dummy hash — a residual slower-direction timing oracle —
// and at cost 20+ its compare exceeds the login's 8 s timeout, so it is
// repaired DOWN to the configured rounds on a proven password, which also
// unbreaks the permanent-lockout family for rows the compare can still
// complete against (the pre-existing T1-B 500s for slower rows were a
// separate, disclosed residual — narrowed by adpanel:login-id-refusal-
// parity, L4: a compare-window breach on the login path now settles as the
// uniform credential failure, never a 500; see the degraded-load regime
// below).
//
// adpanel:bcrypt-cost-parity-dummy — cost-parity FLOOR amendment. The plain
// "dummy == configured rounds" rule above still leaves the known-vs-unknown
// channel open for any row whose embedded cost differs from the configured
// rounds while it exists: the wrong-password compare MUST run against the
// real hash at the cost embedded in it (that is what password verification
// is — it cannot run anywhere else), so a row at cost R answers T(R) while
// an unknown account answers T(BCRYPT_ROUNDS). In-band stronger rows
// (cost 13..15 vs configured 12) are never downgraded, so their divergence
// was permanent. Equalizing the DUMMY side alone cannot close this — the
// unknown-email path has no row to parse a cost from, so no dummy choice can
// match an unknown R. The only closure the evidence supports is a FLOOR: a
// bcrypt compare at cost c costs ~2^c work units, so every credential
// failure — known or unknown email — is made to pay exactly 2^FLOOR units,
// with FLOOR = MAX_BCRYPT_ROUNDS (the strongest row the never-downgrade
// policy can leave in place):
// - unknown email: ONE compare against a dummy minted at FLOOR;
// - known email, wrong password: the real compare at R (untouched), then
// pad compares whose combined work is exactly 2^FLOOR − 2^R units — the
// exact binary decomposition 2^FLOOR − 2^R = Σ 2^c for c in [R..FLOOR−1],
// one compare per cost. Within one bcrypt library T(c) ∝ 2^c, so the
// attempt's total equals T(FLOOR) for EVERY parseable row R ≤ FLOOR —
// including the permanent 13..15 band and legacy rows below MIN —
// without any timing loop or elapsed-time feedback.
// Known residuals (disclosed, not closable without weakening verification):
// - rows ABOVE the ceiling (16..31): the real compare alone exceeds the
// floor and cannot be shortened; they self-repair on a proven password.
// On the LOGIN path a compare-window breach no longer answers a 500 —
// since adpanel:login-id-refusal-parity (L4) it settles through the ONE
// uniform failure path (the byte-identical 400; the outstanding
// reservation is finalized, so the failure record stands — and
// adpanel:uniform-failure-admission keeps every such burn
// admission-bounded). The pre-existing T1-B 500 posture NARROWS to
// compare consumers OUTSIDE the login surface — each reached only by an
// ALREADY-AUTHENTICATED caller, so no pre-auth oracle — and none of them
// answers a 500 on a slow compare (correcting this clause: an earlier
// revision claimed an above-ceiling row could "breach its own 8 s
// window" into a 500 here). The recovery-code check (index.js
// /api/account/recovery/verify, the compare at ~48279) carries NO 8 s
// window at all — it blocks on the compare, swallows a compare error as
// a non-match, and only ever compares hashes the panel itself minted at
// the configured cost, so an above-ceiling row cannot occur there. The
// step-up consumers DO carry 8 s windows — verifyPasswordForUser
// (~2643) and verifyAdminProvisioningStepUp (~47334) wrap their compares
// in withTimeout(…, 8000) whose breach settles FAIL-CLOSED (verdict
// false / step-up refused), stricter than a 500;
// - unparseable rows (cost 0): no cost can be derived from them;
// - pad fixed-overheads: each pad compare carries ~B of non-scaling
// overhead, so a padded attempt costs T(FLOOR) + (FLOOR−R)·B — bounded
// by (FLOOR−4)·B ≲ 10 ms, far inside the 400–800 ms loginDelay jitter;
// - latency budget: every failed attempt now costs ~T(15) of threadpool
// work instead of ~T(BCRYPT_ROUNDS). Successful logins are untouched
// (pads run only on the failure paths an unauthenticated caller can
// reach: unknown-email and wrong-password — wrong-TOTP and the
// stale-credential re-proof are reachable only with the password).
// Three controls bound the extra CPU together (adpanel:login-bcrypt-
// admission): the throttle + captcha-gate budgets bound the per-attempt
// RATE at entry; the login-throttle reservation (reserve-then-finalize/
// refund, utils/login-throttle.js) bounds the COUNT of compare-bearing
// attempts admitted per window — a parallel burst is refunded and
// refused before any compare runs, and EVERY parity-burn path (the
// unknown-email dummy AND the row-resolved refusals' burn, via
// adpanel:uniform-failure-admission) reserves through that same
// fold-only/source budget FIRST: the burn is recorded as a failure, so
// the budget refills and refuses further burns before any compare —
// there is no reservationless burn left that could slip past the count
// bound; and the login-bcrypt admission semaphore
// (utils/bcrypt-admission.js) bounds how many admitted compares occupy
// libuv threads at once. Per-attempt, per-window-count and
// in-parallel: the work floor can no longer be amplified by
// concurrency;
// - degraded-load regime (threadpool degradation, measured ≥2.6x on one
// box and 4.8x on the calibration box): every failure path bounds its
// bcrypt work with an 8 s window, and a breach surfaces differently by
// direction. ALL dummy/pad work windows — the unknown-email compare and
// the wrong-password pads — deliberately fail OPEN to the uniform 400
// by design: the breach logs and the attempt falls through to
// failCredentials (the unknown-email verdict is never read — that
// compare is pure parity work). Without the unknown window's fail-open
// catch the degraded regime would INVERT the existence oracle (unknown
// → 500 while known rows answer 400); with it, no dummy/pad window may
// ever produce a 500. Conscious amendment (adpanel:login-id-refusal-
// parity, L4): the KNOWN row's real-compare breach used to be the one
// remaining 500 divergence (the disclosed T1-B family) — a 500 on a
// RESOLVED row against the unknown path's uniform 400 is the same
// account-existence oracle family the refusal reshaping closes, so both
// credential compare windows (the real compare and the rehash-CAS
// re-proof) now settle a breach through the ONE uniform failure path
// (the verdict never arrived → fail-closed failure record via the
// outstanding reservation's finalize, byte-identical 400). The T1-B 500
// posture NARROWS to what it should always have been: non-credential
// internal errors only (DB, session, TOTP store, config) — a breached
// compare can no longer answer differently from any other credential
// failure.
const { resolveClampedInt } = require("./clamped-int");
const crypto = require("crypto");
const DEFAULT_BCRYPT_ROUNDS = 12;
const MIN_BCRYPT_ROUNDS = 10;
const MAX_BCRYPT_ROUNDS = 15;
// Full-shape check: $2a$/$2b$/$2y$ + 2-digit cost + 53 base64 chars
// (22-char salt + 31-char checksum). Malformed rows ($2a$99$xxx and other
// prefix-only shapes) must parse as 0 — unparseable — so callers refuse to
// derive timing (or rehash) decisions from them.
const BCRYPT_HASH_SHAPE_RE = /^\$2[aby]\$(\d{2})\$[./A-Za-z0-9]{53}$/;
// adpanel:env-int-clamp — resolves through the ONE shared clamped-int helper
// with zeroPolicy "default": a non-positive BCRYPT_ROUNDS is "not
// configured" (the pre-consolidation resolver treated 0 and negatives as
// unusable and fell back to the documented default), NOT a request for the
// band floor.
function resolveBcryptRounds(env = process.env) {
return resolveClampedInt(env, "BCRYPT_ROUNDS", {
fallback: DEFAULT_BCRYPT_ROUNDS,
min: MIN_BCRYPT_ROUNDS,
max: MAX_BCRYPT_ROUNDS,
zeroPolicy: "default",
});
}
// Returns the embedded cost (04..31) of a well-formed $2a$/$2b$/$2y$ hash,
// 0 if the string is not a parseable bcrypt hash.
function parseHashCost(hash) {
if (typeof hash !== "string") return 0;
const match = BCRYPT_HASH_SHAPE_RE.exec(hash);
if (!match) return 0;
const cost = parseInt(match[1], 10);
if (!Number.isFinite(cost) || cost < 4 || cost > 31) return 0;
return cost;
}
function bcryptHashInputError(rawHash) {
if (typeof rawHash !== "string" || rawHash.length !== 60) {
return "Password hash must be a full 60-character bcrypt hash.";
}
if (!parseHashCost(rawHash)) {
return "Password hash must be a valid bcrypt hash ($2a/$2b/$2y, cost 04-31, 53-character base64 body).";
}
return null;
}
function compatibleBcrypt(lib) {
// adpanel:bcrypt-import-compat - native bcrypt does not accept $2y$;
// its fixed algorithm matches $2b$, without rewriting stored credentials.
const normalizeHash = (hash) => typeof hash === "string" && hash.startsWith("$2y$") && parseHashCost(hash)
? "$2b$" + hash.slice(4)
: hash;
const compatible = Object.create(lib);
compatible.compare = (password, hash, callback) => lib.compare(password, normalizeHash(hash), callback);
compatible.compareSync = (password, hash) => lib.compareSync(password, normalizeHash(hash));
return compatible;
}
// Loads the bcrypt implementation lazily (native first, bcryptjs fallback —
// the same order scripts/create-user.js uses) so callers that already hold a
// bcrypt instance can inject it instead via the deps argument.
function loadBcrypt() {
try {
return compatibleBcrypt(require("bcrypt"));
} catch {
return compatibleBcrypt(require("bcryptjs"));
}
}
// Async rehash helper: returns the rewritten hash at `rounds` cost, or null.
// Null means "no rewrite available" — already at parity, an in-band stronger
// row (never downgrade), an unparseable source hash, bad arguments, or ANY
// internal failure (hash() threw, the rewritten hash failed to parse back at
// the target cost). Cheaper rows are upgraded up; pathological rows ABOVE
// MAX_BCRYPT_ROUNDS (legacy writes from the old unbounded env parse) are
// repaired down — see the module comment. Never throws, so a failed rehash
// can only ever be logged, never fail a login.
async function rehashIfStale(hash, password, rounds, deps = {}) {
try {
const targetRounds = Number(rounds);
if (!Number.isFinite(targetRounds) || targetRounds < 4 || targetRounds > 31) return null;
if (typeof password !== "string" || password === "") return null;
const cost = parseHashCost(hash);
if (cost === 0) return null; // refuse to rewrite a row we cannot audit
if (cost === targetRounds) return null; // already at parity
// adpanel:bcrypt-cost-parity — never downgrade a row INSIDE the sane
// band: a stored cost above the configured rounds but within
// [MIN, MAX] is a legitimate operator choice. Rows ABOVE the ceiling
// fall through to the repair path: they are rehashed DOWN to the
// configured rounds (residual slower-direction timing oracle + the
// permanent-lockout family — rationale in the module comment).
if (cost <= MAX_BCRYPT_ROUNDS && cost > targetRounds) return null;
const lib = deps.bcrypt || loadBcrypt();
const upgraded = await lib.hash(password, targetRounds);
if (parseHashCost(upgraded) !== targetRounds) return null;
return upgraded;
} catch {
return null;
}
}
// adpanel:bcrypt-cost-parity-dummy — the strongest row the never-downgrade
// policy leaves in place. EVERY login attempt's bcrypt work floor: an
// unknown account is answered with one compare at this cost, and a
// wrong-password attempt against any parseable row is padded up to exactly
// the same work (see the module header). Not the configured rounds — the
// configured rounds is what the configured-cost dummy already costs, and
// flooring there would leave the permanent 13..15 band diverging.
const BCRYPT_COST_PARITY_FLOOR = MAX_BCRYPT_ROUNDS;
// Per-cost dummy-hash cache (cost -> $2a/$2b/$2y hash minted at that cost).
// Bounded by construction: the key domain is [4..MAX_BCRYPT_ROUNDS] (the
// guard below refuses anything else), i.e. at most MAX_BCRYPT_ROUNDS − 3
// entries — inside the MAX_BCRYPT_ROUNDS + 2 cap. Only the minter writes it;
// a mint that fails to parse back at its own cost is never cached.
const dummyHashCache = new Map();
// Throwaway secret for dummy hashes — never a real credential. Fresh per
// mint, same pattern as index.js's plain DUMMY_BCRYPT_HASH.
function dummySecret() {
return `dummy-${crypto.randomBytes(24).toString("hex")}`;
}
// Introspection for the structural tests (and nothing else): how many costs
// are currently minted. Bounded by construction — the key domain is
// [4..MAX_BCRYPT_ROUNDS], i.e. at most MAX_BCRYPT_ROUNDS − 3 entries.
function dummyHashCacheSize() {
return dummyHashCache.size;
}
// Returns a dummy bcrypt hash whose embedded cost is EXACTLY `cost`, so a
// compare against it costs what a compare against any row of that cost
// costs. Sync by design: on the request path it is a Map hit (the boot
// pre-mint below covers MIN..MAX); a miss mints once via hashSync — the
// request that hits a cold cost pays that mint one time, process-wide.
// Any failure (bad cost, mint throw, mint that fails to parse back at the
// requested cost) returns `deps.fallbackHash` — dummy minting must never
// fail, slow down past one mint, or alter a login.
function getDummyHashForCost(cost, deps = {}) {
const fallbackHash = deps.fallbackHash;
// Strict domain: the integers 4..MAX_BCRYPT_ROUNDS only (parseHashCost's
// band and the ceiling). Strings and other coercible junk are refused —
// every caller passes a number from parseHashCost or the floor constant.
if (typeof cost !== "number" || !Number.isInteger(cost) || cost < 4 || cost > MAX_BCRYPT_ROUNDS) return fallbackHash;
const c = cost;
const cached = dummyHashCache.get(c);
if (cached) return cached;
try {
const lib = deps.bcrypt || loadBcrypt();
const hash = lib.hashSync(dummySecret(), c);
if (parseHashCost(hash) !== c) return fallbackHash;
dummyHashCache.set(c, hash);
return hash;
} catch {
return fallbackHash;
}
}
// The exact binary decomposition of the missing work between a row at cost
// R and the parity floor: 2^FLOOR − 2^R = 2^(FLOOR−1) + ... + 2^R, so ONE
// compare per cost in [R..FLOOR−1] brings the attempt's total to exactly
// 2^FLOOR units. Returns [] when there is nothing to derive (R >= floor,
// unparseable/absurd cost) or nothing missing (R === floor).
function planParityPadCosts(realCost, floorCost = BCRYPT_COST_PARITY_FLOOR) {
const r = Number(realCost);
const f = Number(floorCost);
if (!Number.isInteger(r) || !Number.isInteger(f)) return [];
if (r < 4 || r > 31 || f < 4 || f > 31) return [];
if (r >= f) return [];
const costs = [];
for (let c = f - 1; c >= r; c--) costs.push(c);
return costs;
}
// Executes the pad plan for a failed credential attempt: runs one dummy
// compare per planned cost against the per-cost dummy cache. The REAL
// compare has already run and its verdict is respected unconditionally —
// padding never touches the match outcome, only the attempt's cost. Bounded:
// at most FLOOR − 4 compares (each a plain bcrypt.compare in the libuv
// threadpool). Callers wrap this in the login's existing withTimeout posture
// and catch: a pad failure is logged and the attempt proceeds into the ONE
// uniform failure path — a pad must never change a failure response.
async function padCompareWorkToParityFloor(realCost, deps = {}) {
const password = deps.password;
if (typeof password !== "string") return;
const costs = planParityPadCosts(realCost, deps.floorCost);
if (costs.length === 0) return;
const lib = deps.bcrypt || loadBcrypt();
const compare = deps.compare || ((pw, hash) => lib.compare(pw, hash));
for (const c of costs) {
const hash = getDummyHashForCost(c, { bcrypt: lib, fallbackHash: deps.fallbackHash });
if (!hash) return;
await compare(password, hash);
}
}
// Boot-time pre-mint so the steady-state request path never mints on-path:
// mints the floor cost first (the unknown-email dummy — the most expensive
// and most critical), then descending to MIN. Uses ASYNC hash so the mints
// run in the libuv threadpool (native bcrypt) instead of blocking the event
// loop for seconds; sequential, one at a time, so boot IO is not starved.
// A failed cost is skipped (the lazy on-path mint retries it on first use)
// and reported through done(err) for logging only.
function premintDummyHashesForParity(deps = {}, done) {
const lib = deps.bcrypt || loadBcrypt();
const costs = [];
for (let c = BCRYPT_COST_PARITY_FLOOR; c >= MIN_BCRYPT_ROUNDS; c--) costs.push(c);
const finish = (err) => {
if (typeof done === "function") done(err || null);
};
if (costs.length === 0) return finish(null);
const failed = [];
const mintNext = (i) => {
if (i >= costs.length) {
return finish(failed.length ? new Error(`costs ${failed.join(", ")} failed to pre-mint`) : null);
}
const c = costs[i];
lib.hash(dummySecret(), c, (err, hash) => {
if (err || parseHashCost(hash) !== c) failed.push(c);
else dummyHashCache.set(c, hash);
mintNext(i + 1);
});
};
mintNext(0);
}
module.exports = { DEFAULT_BCRYPT_ROUNDS, MIN_BCRYPT_ROUNDS, MAX_BCRYPT_ROUNDS, BCRYPT_COST_PARITY_FLOOR, resolveBcryptRounds, parseHashCost, rehashIfStale, getDummyHashForCost, planParityPadCosts, padCompareWorkToParityFloor, premintDummyHashesForParity, dummyHashCacheSize, loadBcrypt, bcryptHashInputError };