docs: record auth hash alignment and validation results
This commit is contained in:
1 parent
22887fef03
commit
f7819904b9
51 files changed
+1792
-542
No files matched your search
@@ -1,16 +1,20 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { verifyTotpStep } from './totp.js';
|
||||
|
||||
const pbkdf2 = promisify(crypto.pbkdf2);
|
||||
|
||||
// Hashes written before the format recorded its parameters are `salt:hex` at
|
||||
// this count. They still verify and are rewritten on the next successful login.
|
||||
// New hashes use PASSWORD_ITERATIONS and carry the scheme prefix PASSWORD_FORMAT.
|
||||
// Node's old formats remain readable so successful logins can migrate them.
|
||||
const LEGACY_PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_ITERATIONS = 600000;
|
||||
const MAX_PBKDF2_ITERATIONS = 10000000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
const PASSWORD_FORMAT = 'pbkdf2-sha256';
|
||||
const BCRYPT_SCHEME = 'bcrypt$';
|
||||
const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$';
|
||||
const BCRYPT_ROUNDS = 12;
|
||||
const BCRYPT_MAX_PASSWORD_BYTES = 72;
|
||||
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
|
||||
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
||||
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
|
||||
@@ -38,6 +42,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -45,6 +50,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
UPDATE auth_users SET role = 'superadmin'
|
||||
@@ -100,38 +106,47 @@ function assertPasswordLength(password) {
|
||||
if (typeof password !== 'string' || password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters');
|
||||
}
|
||||
if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) {
|
||||
throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`);
|
||||
}
|
||||
}
|
||||
|
||||
function encodePasswordHash(salt, hash, iterations) {
|
||||
return [PASSWORD_FORMAT, iterations, salt, hash.toString('hex')].join('$');
|
||||
}
|
||||
|
||||
// Returns the salt, expected hash and iteration count recorded in a stored hash,
|
||||
// or null for a format this module does not verify (such as bcrypt written by
|
||||
// the Python or Go packages).
|
||||
function parsePasswordHash(stored) {
|
||||
function parsePbkdf2Hash(stored) {
|
||||
const text = String(stored);
|
||||
let iterations = LEGACY_PASSWORD_ITERATIONS;
|
||||
let salt;
|
||||
let expected;
|
||||
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
|
||||
const parts = text.split('$');
|
||||
if (parts.length !== 4) return null;
|
||||
const [, iterations, salt, expected] = parts;
|
||||
return { iterations: Number(iterations), salt, expected, legacy: false };
|
||||
}
|
||||
if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
||||
const [salt, expected] = text.split(':');
|
||||
return { iterations: LEGACY_PASSWORD_ITERATIONS, salt, expected, legacy: true };
|
||||
[, iterations, salt, expected] = parts;
|
||||
iterations = Number(iterations);
|
||||
} else if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
||||
[salt, expected] = text.split(':');
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null;
|
||||
if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null;
|
||||
return { iterations, salt, expected };
|
||||
}
|
||||
|
||||
function parseBcryptHash(stored) {
|
||||
const text = String(stored);
|
||||
if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true };
|
||||
if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false };
|
||||
if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, legacy: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
function usablePasswordHash(stored) {
|
||||
const parsed = parsePasswordHash(stored);
|
||||
if (!parsed || !parsed.salt || !parsed.expected || !isValidIterations(parsed.iterations)) return null;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function isValidIterations(iterations) {
|
||||
return Number.isSafeInteger(iterations) && iterations >= 1;
|
||||
function validBcryptHash(parsed) {
|
||||
if (!parsed?.hash) return false;
|
||||
try {
|
||||
bcrypt.getRounds(parsed.hash);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function passwordHashMatches(expected, actual) {
|
||||
@@ -140,34 +155,52 @@ function passwordHashMatches(expected, actual) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because
|
||||
* Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because
|
||||
* this call holds the event loop for the whole derivation.
|
||||
*/
|
||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
export function hashPassword(password) {
|
||||
assertPasswordLength(password);
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return encodePasswordHash(salt, hash, iterations);
|
||||
return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
/** Non-blocking variant of hashPassword with the same output format. */
|
||||
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
/** Non-blocking variant of hashPassword with the same bcrypt format. */
|
||||
export async function hashPasswordAsync(password) {
|
||||
assertPasswordLength(password);
|
||||
return derivePasswordHashAsync(password, iterations);
|
||||
return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
// The length rule belongs to user-facing hashing. Upgrading an old hash must
|
||||
// not refuse a password that was accepted when it was first set.
|
||||
async function derivePasswordHashAsync(password, iterations) {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = await pbkdf2(String(password), salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return encodePasswordHash(salt, hash, iterations);
|
||||
// A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve
|
||||
// the full password by hashing its UTF-8 bytes before bcrypt and marking that
|
||||
// representation explicitly in the stored scheme.
|
||||
function bcryptInputForLegacyPassword(password) {
|
||||
const text = String(password);
|
||||
if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) {
|
||||
return { scheme: BCRYPT_SCHEME, input: text };
|
||||
}
|
||||
return {
|
||||
scheme: BCRYPT_SHA256_SCHEME,
|
||||
input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
async function derivePasswordHashAsync(password) {
|
||||
const { scheme, input } = bcryptInputForLegacyPassword(password);
|
||||
return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
|
||||
export function verifyPassword(password, stored) {
|
||||
try {
|
||||
const parsed = usablePasswordHash(stored);
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return false;
|
||||
const input = bcryptHash.prehashed
|
||||
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||
: String(password);
|
||||
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||
return bcrypt.compareSync(input, bcryptHash.hash);
|
||||
}
|
||||
const parsed = parsePbkdf2Hash(stored);
|
||||
if (!parsed) return false;
|
||||
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return passwordHashMatches(parsed.expected, actual);
|
||||
@@ -179,7 +212,16 @@ export function verifyPassword(password, stored) {
|
||||
/** Non-blocking variant of verifyPassword. */
|
||||
export async function verifyPasswordAsync(password, stored) {
|
||||
try {
|
||||
const parsed = usablePasswordHash(stored);
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return false;
|
||||
const input = bcryptHash.prehashed
|
||||
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||
: String(password);
|
||||
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||
return await bcrypt.compare(input, bcryptHash.hash);
|
||||
}
|
||||
const parsed = parsePbkdf2Hash(stored);
|
||||
if (!parsed) return false;
|
||||
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return passwordHashMatches(parsed.expected, actual);
|
||||
@@ -189,12 +231,15 @@ export async function verifyPasswordAsync(password, stored) {
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a stored hash should be rewritten after a successful login: a
|
||||
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
|
||||
* True when a stored hash should be rewritten after a successful login.
|
||||
*/
|
||||
export function passwordHashNeedsUpgrade(stored) {
|
||||
const parsed = parsePasswordHash(stored);
|
||||
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS;
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return true;
|
||||
return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,7 +255,7 @@ export async function verifyAndUpgradePasswordAsync(password, stored) {
|
||||
if (!passwordHashNeedsUpgrade(stored)) {
|
||||
return { valid: true, upgradedHash: null };
|
||||
}
|
||||
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) };
|
||||
return { valid: true, upgradedHash: await derivePasswordHashAsync(password) };
|
||||
}
|
||||
|
||||
export function createSessionToken() {
|
||||
@@ -412,10 +457,10 @@ export class AuthStore {
|
||||
|
||||
async getTotpState(userId) {
|
||||
const result = await this.database.query(
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled, COALESCE(last_used_step, -1) AS last_used_step FROM auth_users WHERE id = $1',
|
||||
[userId],
|
||||
);
|
||||
return result.rows[0] || { secret: '', enabled: false };
|
||||
return result.rows[0] || { secret: '', enabled: false, last_used_step: -1 };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -425,7 +470,7 @@ export class AuthStore {
|
||||
*/
|
||||
async setTotpSecret(userId, secret) {
|
||||
const result = await this.database.query(
|
||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
|
||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
|
||||
[secret, userId],
|
||||
);
|
||||
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
|
||||
@@ -433,16 +478,33 @@ export class AuthStore {
|
||||
}
|
||||
}
|
||||
|
||||
async enableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
|
||||
[userId],
|
||||
async enableTotp(userId, token, now = Date.now()) {
|
||||
const state = await this.getTotpState(userId);
|
||||
if (!state.secret || state.enabled) return false;
|
||||
const step = verifyTotpStep(state.secret, token, now);
|
||||
if (step === null) return false;
|
||||
const result = await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
|
||||
[step, userId, state.secret],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async consumeTotpCode(userId, token, now = Date.now()) {
|
||||
const state = await this.getTotpState(userId);
|
||||
if (!state.secret || !state.enabled) return false;
|
||||
const step = verifyTotpStep(state.secret, token, now);
|
||||
if (step === null) return false;
|
||||
const result = await this.database.query(
|
||||
'UPDATE auth_users SET last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1',
|
||||
[step, userId, state.secret],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async disableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -60,16 +60,38 @@ export class Info {
|
||||
}
|
||||
}
|
||||
|
||||
/** Shortest SECRET a service accepts for its internal routes. */
|
||||
export const MIN_INTERNAL_SECRET_LENGTH = 16;
|
||||
|
||||
/**
|
||||
* True when the X-Internal-Auth value equals the configured secret. An unset
|
||||
* or empty secret never matches, and the comparison is constant-time.
|
||||
* Placeholders from .env.example files and the bare variable name. They are
|
||||
* public, so they never gate a route.
|
||||
*/
|
||||
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
|
||||
|
||||
/**
|
||||
* True when the configured secret is strong enough to gate an internal route:
|
||||
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||
* placeholder. Length counts characters, as the Python and Go helpers do.
|
||||
* @param {unknown} secret
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function internalSecretUsable(secret) {
|
||||
const value = String(secret ?? '');
|
||||
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the X-Internal-Auth value equals the configured secret. A secret
|
||||
* that is not usable (see internalSecretUsable) never matches, and the
|
||||
* comparison is constant-time.
|
||||
* @param {unknown} provided
|
||||
* @param {unknown} secret
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function internalSecretMatches(provided, secret) {
|
||||
const expected = Buffer.from(String(secret ?? ''));
|
||||
if (expected.length === 0) return false;
|
||||
if (!internalSecretUsable(secret)) return false;
|
||||
const expected = Buffer.from(String(secret));
|
||||
const actual = Buffer.from(String(provided ?? ''));
|
||||
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
}
|
||||
|
||||
@@ -33,11 +33,15 @@ export {
|
||||
generateTotpSecret,
|
||||
totpProvisioningUri,
|
||||
verifyTotp,
|
||||
verifyTotpStep,
|
||||
} from './totp.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||
export {
|
||||
EXAMPLE_INTERNAL_SECRETS,
|
||||
Info as CoreConfigInfo,
|
||||
MIN_INTERNAL_SECRET_LENGTH,
|
||||
Store as CoreConfigStore,
|
||||
internalSecretMatches,
|
||||
internalSecretUsable,
|
||||
} from './coreconfig.js';
|
||||
@@ -24,19 +24,24 @@ export function totpProvisioningUri(issuer, account, secret) {
|
||||
}
|
||||
|
||||
export function verifyTotp(secret, token, now = Date.now()) {
|
||||
return verifyTotpStep(secret, token, now) !== null;
|
||||
}
|
||||
|
||||
export function verifyTotpStep(secret, token, now = Date.now()) {
|
||||
const normalizedSecret = normalizeSecret(secret);
|
||||
const normalizedToken = normalizeToken(token);
|
||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false;
|
||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return null;
|
||||
|
||||
let key;
|
||||
try {
|
||||
key = decodeBase32(normalizedSecret);
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
if (key.length === 0) return false;
|
||||
if (key.length === 0) return null;
|
||||
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
|
||||
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) {
|
||||
// Prefer the current step if a six-digit collision occurs in the window.
|
||||
for (const offset of [0, -1, 1]) {
|
||||
if (period + offset < 0) continue;
|
||||
const counter = Buffer.alloc(8);
|
||||
counter.writeBigUInt64BE(BigInt(period + offset));
|
||||
@@ -47,9 +52,9 @@ export function verifyTotp(secret, token, now = Date.now()) {
|
||||
| (digest[index + 2] << 8)
|
||||
| digest[index + 3];
|
||||
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
|
||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true;
|
||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return period + offset;
|
||||
}
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeSecret(value) {
|
||||
|
||||
Reference in new issue
Block a user