/** * Emergency break-glass: clear Super Admin TOTP + recovery codes after phone / authenticator loss. * * This is intentionally NOT an HTTP API. It requires: * - SSH / Docker access to the VPS * - BREAK_GLASS_TOKEN set in the environment (min 32 chars, distinct from JWT / setup tokens) * - CLI --token matching that env value * - Explicit --confirm=RESET_ADMIN_2FA * * VPS (from repo root, after image build): * sudo docker compose run --rm --no-deps backend \ * node dist/scripts/breakGlassResetAdmin2fa.js \ * --email=admin@example.com \ * --confirm=RESET_ADMIN_2FA \ * --token="$BREAK_GLASS_TOKEN" \ * --operator=your-name * * Or: npm run phase-b:break-glass-reset-2fa -- --email=... --confirm=RESET_ADMIN_2FA --token=... --operator=... * * Local backend/: * npm run break-glass-reset-2fa -- --email=... --confirm=RESET_ADMIN_2FA --token=... */ import './loadEnv'; import crypto from 'crypto'; import os from 'os'; import { hashForIndex } from '../utils/crypto'; import { query } from '../db/connection'; import * as userRepository from '../repositories/userRepository'; import * as totpRecoveryRepository from '../repositories/totpRecoveryRepository'; import * as refreshTokenRepository from '../repositories/refreshTokenRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import * as roleRepository from '../repositories/roleRepository'; import * as securityNotificationService from '../services/securityNotificationService'; const CONFIRM_PHRASE = 'RESET_ADMIN_2FA'; const COOLDOWN_HOURS = 24; const MIN_TOKEN_LENGTH = 32; type Args = { email: string; confirm: string; token: string; operator: string | null; }; function printUsageAndExit(code = 1): never { console.error(`Usage: node dist/scripts/breakGlassResetAdmin2fa.js \\ --email= \\ --confirm=${CONFIRM_PHRASE} \\ --token= \\ [--operator=] Environment: BREAK_GLASS_TOKEN Required (min ${MIN_TOKEN_LENGTH} chars). Must match --token. `); process.exit(code); } function parseArgs(argv: string[]): Args { const map = new Map(); for (const raw of argv) { if (!raw.startsWith('--')) continue; const eq = raw.indexOf('='); if (eq <= 2) continue; const key = raw.slice(2, eq).trim(); const value = raw.slice(eq + 1).trim(); if (key) map.set(key, value); } const email = (map.get('email') || '').trim().toLowerCase(); const confirm = (map.get('confirm') || '').trim(); const token = (map.get('token') || '').trim(); const operator = (map.get('operator') || '').trim() || null; if (!email || !confirm || !token) printUsageAndExit(1); return { email, confirm, token, operator }; } function timingSafeEqualString(a: string, b: string): boolean { const bufA = Buffer.from(a, 'utf8'); const bufB = Buffer.from(b, 'utf8'); if (bufA.length !== bufB.length) return false; return crypto.timingSafeEqual(bufA, bufB); } async function assertCooldownAllows(): Promise { const rows = await query<{ created_at: Date }[]>( `SELECT created_at FROM audit_logs WHERE action = 'break_glass_admin_2fa_reset' ORDER BY created_at DESC LIMIT 1` ); const last = rows[0]?.created_at ? new Date(rows[0].created_at) : null; if (!last) return; const elapsedMs = Date.now() - last.getTime(); const cooldownMs = COOLDOWN_HOURS * 60 * 60 * 1000; if (elapsedMs < cooldownMs) { const remainH = ((cooldownMs - elapsedMs) / (60 * 60 * 1000)).toFixed(1); throw new Error( `Break-glass cooldown active (${COOLDOWN_HOURS}h). Last reset at ${last.toISOString()}. ` + `Retry in ~${remainH}h, or investigate whether another operator already ran this.` ); } } async function main(): Promise { const args = parseArgs(process.argv.slice(2)); if (args.confirm !== CONFIRM_PHRASE) { throw new Error(`--confirm must be exactly ${CONFIRM_PHRASE}`); } const envToken = (process.env.BREAK_GLASS_TOKEN || '').trim(); if (!envToken || envToken.length < MIN_TOKEN_LENGTH) { throw new Error( `BREAK_GLASS_TOKEN is missing or shorter than ${MIN_TOKEN_LENGTH} characters. ` + 'Set it in .env (and recreate containers) to enable emergency 2FA reset. ' + 'Use a value distinct from JWT_SECRET and INITIAL_SETUP_TOKEN.' ); } if (!timingSafeEqualString(envToken, args.token)) { throw new Error('--token does not match BREAK_GLASS_TOKEN (access denied).'); } await assertCooldownAllows(); const user = await userRepository.findByEmailHash(hashForIndex(args.email)); if (!user || user.deleted_at) { throw new Error(`No active user found for email: ${args.email}`); } const isSuperAdmin = await roleRepository.userHasRole(user.id, 'super_admin'); if (!isSuperAdmin) { throw new Error( `User ${args.email} is not a super_admin. Break-glass only resets Super Admin 2FA.` ); } const hadTotp = Boolean(user.totp_enabled); await userRepository.updateTotp(user.id, null, false); await totpRecoveryRepository.deleteCodesForUser(user.id); await userRepository.incrementTokenVersion(user.id); await refreshTokenRepository.deleteByUserId(user.id); await userRepository.resetFailedLoginState(user.id); // Re-enforce admin 2FA so the panel stays locked until re-enrollment after login. await query( `INSERT INTO system_settings (key, value) VALUES ('require_admin_2fa', 'true') ON CONFLICT (key) DO UPDATE SET value = 'true'` ); const hostname = os.hostname(); const metadata = { channel: 'cli_break_glass', email: args.email, operator: args.operator, hostname, had_totp_enabled: hadTotp, cooldown_hours: COOLDOWN_HOURS, require_admin_2fa: true, }; await auditLogRepository.create({ userId: user.id, action: 'break_glass_admin_2fa_reset', resourceType: 'user', resourceId: user.id, userAgent: `break-glass@${hostname}`, metadata, }); void securityNotificationService.notifyBreakGlassAdmin2faReset(user.id, { operator: args.operator, hostname, }); console.log('Break-glass Super Admin 2FA reset completed.'); console.log(` User: ${args.email} (${user.id})`); console.log(` TOTP was: ${hadTotp ? 'enabled' : 'already disabled'}`); console.log(' Cleared: totp secret, recovery codes, refresh sessions, login lockout'); console.log(' Bumped: token_version (access JWTs invalidated)'); console.log(' Setting: require_admin_2fa=true'); console.log('Next steps:'); console.log(' 1. Log in with email + password only (no authenticator code).'); console.log(' 2. Open Profile → enable 2FA again.'); console.log(' 3. Save the new recovery codes offline.'); console.log(' 4. Prefer creating a second Super Admin when possible.'); } main() .then(() => process.exit(0)) .catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });