|
| 1 | +#!/usr/bin/env node |
| 2 | +import crypto from 'node:crypto'; |
| 3 | +import readline from 'node:readline'; |
| 4 | +import { existsSync } from 'node:fs'; |
| 5 | +import qrcode from 'qrcode'; |
| 6 | +import Database from 'better-sqlite3'; |
| 7 | + |
| 8 | +const RESET = '\x1b[0m'; |
| 9 | +const BOLD = '\x1b[1m'; |
| 10 | +const CYAN = '\x1b[36m'; |
| 11 | +const GREEN = '\x1b[32m'; |
| 12 | +const RED = '\x1b[31m'; |
| 13 | +const DIM = '\x1b[2m'; |
| 14 | +const YELLOW = '\x1b[33m'; |
| 15 | + |
| 16 | +const DB_PATH = process.env.PREFS_DB_PATH ?? '/app/prefs/mintlayer_prefs.sqlite'; |
| 17 | + |
| 18 | +// ── TOTP helpers (mirrors app/src/lib/auth.ts) ────────────────────────────── |
| 19 | + |
| 20 | +function generateTotpSecret() { |
| 21 | + const bytes = crypto.randomBytes(20); |
| 22 | + const alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; |
| 23 | + let result = '', bits = 0, value = 0; |
| 24 | + for (let i = 0; i < bytes.length; i++) { |
| 25 | + value = (value << 8) | bytes[i]; |
| 26 | + bits += 8; |
| 27 | + while (bits >= 5) { |
| 28 | + result += alpha[(value >>> (bits - 5)) & 31]; |
| 29 | + bits -= 5; |
| 30 | + } |
| 31 | + } |
| 32 | + if (bits > 0) result += alpha[(value << (5 - bits)) & 31]; |
| 33 | + return result; |
| 34 | +} |
| 35 | + |
| 36 | +function decodeBase32(input) { |
| 37 | + const alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; |
| 38 | + const str = input.toUpperCase().replace(/=+$/, '').replace(/\s/g, ''); |
| 39 | + let bits = 0, value = 0; |
| 40 | + const out = []; |
| 41 | + for (const ch of str) { |
| 42 | + const idx = alpha.indexOf(ch); |
| 43 | + if (idx === -1) continue; |
| 44 | + value = (value << 5) | idx; |
| 45 | + bits += 5; |
| 46 | + if (bits >= 8) { out.push((value >>> (bits - 8)) & 0xff); bits -= 8; } |
| 47 | + } |
| 48 | + return Buffer.from(out); |
| 49 | +} |
| 50 | + |
| 51 | +function hotpCode(key, counter) { |
| 52 | + const buf = Buffer.alloc(8); |
| 53 | + buf.writeBigUInt64BE(counter); |
| 54 | + const hmac = crypto.createHmac('sha1', key).update(buf).digest(); |
| 55 | + const offset = hmac[hmac.length - 1] & 0x0f; |
| 56 | + const code = |
| 57 | + (((hmac[offset] & 0x7f) << 24) | |
| 58 | + ((hmac[offset + 1] & 0xff) << 16) | |
| 59 | + ((hmac[offset + 2] & 0xff) << 8) | |
| 60 | + (hmac[offset + 3] & 0xff)) % 1_000_000; |
| 61 | + return code.toString().padStart(6, '0'); |
| 62 | +} |
| 63 | + |
| 64 | +function verifyTOTP(code, secret) { |
| 65 | + if (!code || code.length !== 6 || !/^\d{6}$/.test(code)) return false; |
| 66 | + const key = decodeBase32(secret); |
| 67 | + const T = BigInt(Math.floor(Date.now() / 1000 / 30)); |
| 68 | + for (const delta of [-1n, 0n, 1n]) { |
| 69 | + const candidate = hotpCode(key, T + delta); |
| 70 | + if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(code))) return true; |
| 71 | + } |
| 72 | + return false; |
| 73 | +} |
| 74 | + |
| 75 | +// ── Readline helper ────────────────────────────────────────────────────────── |
| 76 | + |
| 77 | +function prompt(rl, question) { |
| 78 | + return new Promise(resolve => rl.question(question, resolve)); |
| 79 | +} |
| 80 | + |
| 81 | +// ── Main ───────────────────────────────────────────────────────────────────── |
| 82 | + |
| 83 | +async function main() { |
| 84 | + console.log(`\n${BOLD}${CYAN}┌─────────────────────────────────────────┐${RESET}`); |
| 85 | + console.log(`${BOLD}${CYAN}│ Mintlayer GUI — Update TOTP Secret │${RESET}`); |
| 86 | + console.log(`${BOLD}${CYAN}└─────────────────────────────────────────┘${RESET}\n`); |
| 87 | + |
| 88 | + if (!existsSync(DB_PATH)) { |
| 89 | + console.error(`${RED}Error: database not found at ${DB_PATH}${RESET}`); |
| 90 | + console.error(`${DIM}Set PREFS_DB_PATH env var to point to mintlayer_prefs.sqlite${RESET}`); |
| 91 | + process.exit(1); |
| 92 | + } |
| 93 | + |
| 94 | + const secret = generateTotpSecret(); |
| 95 | + const issuer = 'Mintlayer'; |
| 96 | + const label = encodeURIComponent('Mintlayer GUI'); |
| 97 | + const uri = `otpauth://totp/${label}?secret=${secret}&issuer=${issuer}`; |
| 98 | + |
| 99 | + // Render QR code |
| 100 | + const qr = await qrcode.toString(uri, { type: 'utf8', errorCorrectionLevel: 'M' }); |
| 101 | + console.log(qr); |
| 102 | + |
| 103 | + console.log(`${BOLD}TOTP Secret (manual entry):${RESET}`); |
| 104 | + console.log(` ${YELLOW}${BOLD}${secret}${RESET}\n`); |
| 105 | + console.log(`${DIM}otpauth URI:${RESET}`); |
| 106 | + console.log(` ${DIM}${uri}${RESET}\n`); |
| 107 | + |
| 108 | + console.log(`${YELLOW}Scan the QR code with your authenticator app before continuing.${RESET}`); |
| 109 | + console.log(`${YELLOW}The current secret will be overwritten and cannot be recovered.${RESET}\n`); |
| 110 | + |
| 111 | + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); |
| 112 | + |
| 113 | + let confirmed = false; |
| 114 | + for (let attempt = 1; attempt <= 3; attempt++) { |
| 115 | + const code = (await prompt(rl, `${BOLD}Enter the 6-digit code from your authenticator: ${RESET}`)).trim(); |
| 116 | + if (verifyTOTP(code, secret)) { |
| 117 | + confirmed = true; |
| 118 | + break; |
| 119 | + } |
| 120 | + console.log(`${RED}Invalid code.${attempt < 3 ? ` ${3 - attempt} attempt(s) remaining.` : ''}${RESET}`); |
| 121 | + } |
| 122 | + |
| 123 | + rl.close(); |
| 124 | + |
| 125 | + if (!confirmed) { |
| 126 | + console.log(`\n${RED}Aborted — TOTP secret was NOT saved.${RESET}\n`); |
| 127 | + process.exit(1); |
| 128 | + } |
| 129 | + |
| 130 | + // Write to SQLite |
| 131 | + const db = new Database(DB_PATH); |
| 132 | + db.prepare("INSERT OR REPLACE INTO prefs (key, value) VALUES ('auth.totp_secret', ?)").run(JSON.stringify(secret)); |
| 133 | + db.close(); |
| 134 | + |
| 135 | + console.log(`\n${GREEN}${BOLD}✓ TOTP secret updated successfully.${RESET}`); |
| 136 | + console.log(`${DIM}Restart the web-gui container if it is currently running.${RESET}\n`); |
| 137 | +} |
| 138 | + |
| 139 | +main().catch(err => { |
| 140 | + console.error(`${RED}Fatal: ${err.message}${RESET}`); |
| 141 | + process.exit(1); |
| 142 | +}); |
0 commit comments