import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline/promises'; import { parseArgs } from 'node:util'; import { createBackupBundle, restoreBackupBundle, verifyBackupSummaryOnly, } from '../server/security/backup.js'; import { EmergencyRecoveryService } from '../server/security/recovery-store.js'; import { VaultService } from '../server/security/vault.js'; function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) --current-key-file Path to file containing current 32-byte key --new-key-out Optional output file (0600) for generated key backup Create an AES-256-GCM .gcoord.enc portable backup bundle --out Output bundle path (required) --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) --key-file Path to 32-byte Vault master key (default mode) --passphrase-file Path to passphrase file (overrides key-file using scrypt) verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data Backup bundle path (or --bundle ) --key-file Path to 32-byte master key --passphrase-file Path to backup passphrase file --vault-key-file Optional Vault master key to also decrypt/verify vault.enc --json Print verification summary as JSON restore Atomically restore config/, vault.enc, known_hosts, and alert_silences Backup bundle path (or --bundle ) --data-dir Target data directory (default: GCOORD_DATA_DIR or ./data) --key-file Path to 32-byte master key --passphrase-file Path to backup passphrase file --vault-key-file Optional Vault master key if backup used a passphrase `); } async function promptHiddenOrLine(promptText: string): Promise { const rl = readline.createInterface({ input: process.stdin, output: process.stderr, }); try { const answer = await rl.question(promptText); return answer.trim(); } finally { rl.close(); } } async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { if (keyFile) { return fs.readFileSync(keyFile, 'utf8').trim(); } if (process.env.GCOORD_MASTER_KEY?.trim()) { return process.env.GCOORD_MASTER_KEY.trim(); } if (fs.existsSync('/run/secrets/gcoord_master_key')) { return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim(); } if (dataDir) { const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); if (fs.existsSync(localKeyFile)) { return fs.readFileSync(localKeyFile, 'utf8').trim(); } } return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): '); } function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined { if (keyFile) { return fs.readFileSync(keyFile, 'utf8').trim(); } if (process.env.GCOORD_MASTER_KEY?.trim()) { return process.env.GCOORD_MASTER_KEY.trim(); } if (fs.existsSync('/run/secrets/gcoord_master_key')) { return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim(); } if (dataDir) { const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); if (fs.existsSync(localKeyFile)) { return fs.readFileSync(localKeyFile, 'utf8').trim(); } } return undefined; } function readOptionalPassphrase(passphraseFile?: string): string | undefined { if (passphraseFile) { return fs.readFileSync(passphraseFile, 'utf8').trim(); } if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) { return process.env.GCOORD_BACKUP_PASSPHRASE.trim(); } return undefined; } async function runRotateKey(args: string[]): Promise { const parsed = parseArgs({ args, options: { 'data-dir': { type: 'string' }, 'current-key-file': { type: 'string' }, 'new-key-out': { type: 'string' }, }, allowPositionals: false, }); const dataDir = path.resolve( parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', ); const vaultPath = path.join(dataDir, 'vault.enc'); if (!fs.existsSync(vaultPath)) { console.error(`Error: Vault file not found at ${vaultPath}`); return 1; } const currentKey = await readCurrentKey(parsed.values['current-key-file']); const vault = new VaultService(vaultPath); vault.unlock(currentKey); const { generatedKeyHex } = vault.rotateMasterKey(); if (!generatedKeyHex) { console.error('Error: Unexpected empty rotated key'); return 1; } const recovery = new EmergencyRecoveryService(dataDir); if (recovery.readBundle() !== null) { recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' }); } if (parsed.values['new-key-out']) { const outPath = path.resolve(parsed.values['new-key-out']); fs.mkdirSync(path.dirname(outPath), { recursive: true }); fs.writeFileSync(outPath, `${generatedKeyHex}\n`, { mode: 0o600 }); fs.chmodSync(outPath, 0o600); console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); } else { console.log('Vault master key rotated cleanly. Store this new key securely:'); console.log(generatedKeyHex); } return 0; } async function runBackup(args: string[]): Promise { const parsed = parseArgs({ args, options: { out: { type: 'string' }, 'data-dir': { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, }, allowPositionals: true, }); const outRaw = parsed.values.out ?? parsed.positionals[0]; if (!outRaw) { console.error('Error: --out is required'); return 1; } const dataDir = path.resolve( parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', ); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); const masterKey = passphrase ? readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir) : await readCurrentKey(parsed.values['key-file'], dataDir); const result = createBackupBundle({ dataDir, masterKey, passphrase, }); const outPath = path.resolve(outRaw); fs.mkdirSync(path.dirname(outPath), { recursive: true }); const tmpPath = `${outPath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, result.serialized, 'utf8'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } fs.renameSync(tmpPath, outPath); fs.chmodSync(outPath, 0o600); console.log( `Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`, ); return 0; } async function runVerifyBackup(args: string[]): Promise { const parsed = parseArgs({ args, options: { bundle: { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, 'vault-key-file': { type: 'string' }, json: { type: 'boolean', default: false }, }, allowPositionals: true, }); const bundleArg = parsed.values.bundle ?? parsed.positionals[0]; if (!bundleArg) { console.error('Error: backup bundle path is required'); return 1; } const rawBuf = fs.readFileSync(path.resolve(bundleArg)); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']); if (!passphrase && !masterKey) { const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string }; if (rawMeta.kdf === 'scrypt') { throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)'); } masterKey = await readCurrentKey(undefined); } const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']); const summary = verifyBackupSummaryOnly(rawBuf, { masterKey, passphrase, vaultMasterKey, }); if (parsed.values.json) { console.log(JSON.stringify(summary, null, 2)); } else { console.log( `Backup verified cleanly (createdAt=${summary.createdAt}, kdf=${summary.kdf}, configs=${summary.configFileCount}, vault=${summary.hasVault ? (summary.vaultVerified ? `verified(${summary.vaultCredentialCount ?? 0} creds)` : 'unverified') : 'none'}, knownHosts=${summary.knownHostsCount})`, ); } return 0; } async function runRestore(args: string[]): Promise { const parsed = parseArgs({ args, options: { bundle: { type: 'string' }, 'data-dir': { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, 'vault-key-file': { type: 'string' }, }, allowPositionals: true, }); const bundleArg = parsed.values.bundle ?? parsed.positionals[0]; if (!bundleArg) { console.error('Error: backup bundle path is required'); return 1; } const dataDir = path.resolve( parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', ); const rawBuf = fs.readFileSync(path.resolve(bundleArg)); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); if (!passphrase && !masterKey) { masterKey = await readCurrentKey(undefined, dataDir); } const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); const { summary } = restoreBackupBundle(rawBuf, { dataDir, masterKey, passphrase, vaultMasterKey, }); console.log( `Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`, ); return 0; } async function main(): Promise { const [command, ...rest] = process.argv.slice(2); if (!command || command === '-h' || command === '--help') { printUsage(); process.exit(0); } if (command === 'rotate-key') { process.exit(await runRotateKey(rest)); } if (command === 'backup') { process.exit(await runBackup(rest)); } if (command === 'verify-backup') { process.exit(await runVerifyBackup(rest)); } if (command === 'restore') { process.exit(await runRestore(rest)); } console.error(`Unknown command: ${command}`); printUsage(); process.exit(1); } main().catch((err) => { console.error(err instanceof Error ? err.message : String(err)); process.exit(1); });