Files
Kelx/scripts/reset-recovery-codes.js
T
2026-11-30 16:32:37 +00:00

211 lines
7.0 KiB
JavaScript

"use strict";
// Break-glass recovery-code reset for a fully locked-out account owner.
//
// The web UI cannot do this for admin targets by design: the admin reset
// route (/api/admin/user/reset-recovery-codes) refuses admin accounts because
// answering with the plaintext codes would expose them to the acting admin
// and break non-repudiation, and self-service regeneration requires the
// owner to be signed in. This CLI is the out-of-band path for the degenerate
// state where the owner cannot sign in at all: whoever can run it as root on
// the panel server can read the users table directly, so handing it the new
// plaintext codes is not an additional exposure (same reasoning as the
// create-user script in SECURITY-FIXES.md).
//
// The stored set is REPLACED: every previous recovery code is invalidated the
// moment the new hashes are written.
const crypto = require("crypto");
const path = require("path");
require("dotenv").config({
path: path.join(__dirname, "..", ".env"),
override: true,
});
const db = require("../db");
// adpanel:bcrypt-cost-parity — hashes written here must cost the SAME bcrypt
// work the panel resolves (one shared resolver, see utils/bcrypt-rounds.js);
// a hardcoded cheaper-cost literal re-introduces the heterogeneous-row
// problem the create-user script had.
const { resolveBcryptRounds, loadBcrypt } = require("../utils/bcrypt-rounds");
const bcrypt = loadBcrypt();
// Resolved after dotenv.config above so BCRYPT_ROUNDS comes from the loaded
// .env, exactly like the running panel.
const BCRYPT_ROUNDS = resolveBcryptRounds();
async function ensureUsersColumn(columnName, definition) {
try {
await db.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS ${columnName} ${definition}`);
} catch (err) {
if (!err.message?.includes("Duplicate column")) {
try {
const cols = await db.query(`SHOW COLUMNS FROM users LIKE '${columnName}'`);
if (!cols || cols.length === 0) {
await db.query(`ALTER TABLE users ADD COLUMN ${columnName} ${definition}`);
}
} catch (_) {
}
}
}
}
function usage() {
return [
"Usage:",
" sudo node scripts/reset-recovery-codes.js --email user@example.com",
"",
"Regenerates and prints new recovery codes for an existing account.",
"All previous recovery codes are invalidated (the stored set is replaced).",
"",
"Must run on the panel server as root: the codes are bcrypt-hashed into",
"the users table and the plaintext is printed here exactly once.",
"",
"Panel admins cannot reset recovery codes for admin accounts from the web",
"UI by design — the plaintext codes would be exposed to the acting admin",
"and non-repudiation would be broken. This script is the break-glass path",
"for a fully locked-out account owner (admin or user).",
].join("\n");
}
function parseArgs(argv) {
// Only --email is supported: a recovery code is generated here, never
// accepted, so no credential can ride argv the way create-user guards
// against. Unknown flags are ignored and the required --email gate below
// prints the usage instead.
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--help" || arg === "-h") {
out.help = true;
continue;
}
if (arg === "--email") {
out.email = argv[i + 1];
i += 1;
continue;
}
}
return out;
}
function requireSudo() {
if (typeof process.getuid === "function" && process.getuid() !== 0) {
console.error("This script must be run with sudo.");
return false;
}
return true;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (!requireSudo()) {
return 1;
}
if (args.help || !args.email) {
console.log(usage());
return 1;
}
const email = String(args.email || "").trim().toLowerCase();
if (!email) {
console.error("Invalid email.");
return 1;
}
// users.email is VARCHAR(255) and MySQL strict mode raises error 1406 on
// longer values, so cap at 254 to match normalizeProvisionedEmail in
// index.js and the create-user script: no email longer than 254 characters
// can exist in the table, so a lookup could never match anyway.
if (email.length > 254) {
console.error("Email must be 254 characters or fewer.");
return 1;
}
if (/[\x00-\x1f\x7f]/.test(email)) {
console.error("Email contains invalid control characters.");
return 1;
}
await db.ensureSchema();
await ensureUsersColumn("recovery_codes", "TEXT NULL");
const found = await db.query(
"SELECT id, email FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1",
[email]
);
const existing = Array.isArray(found) ? found[0] : null;
if (!existing) {
console.error("User not found.");
return 2;
}
const RECOVERY_CODE_COUNT = 7;
const RECOVERY_CODE_LENGTH = 8;
const RECOVERY_CODE_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
// Recovery codes are account credentials, so every character must come from
// the OS CSPRNG. crypto.randomInt is rejection-sampled internally and stays
// uniformly distributed over the alphabet even if its size ever stops being
// a power of two — Math.random is a seeded PRNG and must never generate
// secret material (CWE-338). Same generator as scripts/create-user.js and
// the panel's own issuance routes, so the printed codes match what the
// recovery/verify step-up consumes.
function generateRecoveryCode() {
let code = '';
for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) {
code += RECOVERY_CODE_CHARS.charAt(crypto.randomInt(RECOVERY_CODE_CHARS.length));
}
return code;
}
const plainRecoveryCodes = [];
const hashedRecoveryCodes = [];
for (let i = 0; i < RECOVERY_CODE_COUNT; i++) {
const code = generateRecoveryCode();
plainRecoveryCodes.push(code);
hashedRecoveryCodes.push(bcrypt.hashSync(code, BCRYPT_ROUNDS));
}
await db.query(
"UPDATE users SET recovery_codes = ? WHERE id = ?",
[JSON.stringify(hashedRecoveryCodes), existing.id]
);
console.log(`Recovery codes reset: ${existing.email}`);
console.log('');
console.log('\x1b[1m\x1b[33m==================== RECOVERY CODES ====================\x1b[0m');
console.log('\x1b[1m\x1b[31mSAVE THESE CODES! They can only be shown ONCE!\x1b[0m');
console.log('\x1b[1m\x1b[31mEach code can only be used ONE TIME.\x1b[0m');
console.log('');
plainRecoveryCodes.forEach((code, idx) => {
console.log(` \x1b[1m\x1b[36m${idx + 1}. ${code}\x1b[0m`);
});
console.log('');
console.log('\x1b[1m\x1b[33m=========================================================\x1b[0m');
return 0;
}
async function run() {
let exitCode = 0;
try {
exitCode = await main();
} catch (err) {
console.error("[reset-recovery-codes] failed:", err?.message || err);
exitCode = 1;
} finally {
try {
await db.close();
} catch (err) {
console.error("[reset-recovery-codes] close failed:", err?.message || err);
exitCode = exitCode || 1;
}
}
process.exitCode = exitCode;
}
run();