games_app/backend/dist-test-faq/scripts/breakGlassResetAdmin2fa.js

204 lines
8.6 KiB
JavaScript

"use strict";
/**
* 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=...
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("./loadEnv");
const crypto_1 = __importDefault(require("crypto"));
const os_1 = __importDefault(require("os"));
const crypto_2 = require("../utils/crypto");
const connection_1 = require("../db/connection");
const userRepository = __importStar(require("../repositories/userRepository"));
const totpRecoveryRepository = __importStar(require("../repositories/totpRecoveryRepository"));
const refreshTokenRepository = __importStar(require("../repositories/refreshTokenRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const roleRepository = __importStar(require("../repositories/roleRepository"));
const securityNotificationService = __importStar(require("../services/securityNotificationService"));
const CONFIRM_PHRASE = 'RESET_ADMIN_2FA';
const COOLDOWN_HOURS = 24;
const MIN_TOKEN_LENGTH = 32;
function printUsageAndExit(code = 1) {
console.error(`Usage:
node dist/scripts/breakGlassResetAdmin2fa.js \\
--email=<super-admin-email> \\
--confirm=${CONFIRM_PHRASE} \\
--token=<BREAK_GLASS_TOKEN> \\
[--operator=<name>]
Environment:
BREAK_GLASS_TOKEN Required (min ${MIN_TOKEN_LENGTH} chars). Must match --token.
`);
process.exit(code);
}
function parseArgs(argv) {
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, b) {
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length)
return false;
return crypto_1.default.timingSafeEqual(bufA, bufB);
}
async function assertCooldownAllows() {
const rows = await (0, connection_1.query)(`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() {
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((0, crypto_2.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 (0, connection_1.query)(`INSERT INTO system_settings (key, value) VALUES ('require_admin_2fa', 'true')
ON CONFLICT (key) DO UPDATE SET value = 'true'`);
const hostname = os_1.default.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);
});
//# sourceMappingURL=breakGlassResetAdmin2fa.js.map