From 9a27525defe4f7707ae3c1d7dbccca32b977c00f Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:37:20 +0000 Subject: [PATCH] feat(audit,backup,cli): upgrade Audit Log, harden async Backup + scheduled backups & CLI tools --- src/cli/gcoord.ts | 655 +++++++++++++++++++++--- src/server/api/routes/audit.routes.ts | 68 ++- src/server/api/routes/backup.routes.ts | 158 ++++-- src/server/app.ts | 37 +- src/server/security/audit.ts | 166 +++++- src/server/security/backup-scheduler.ts | 275 ++++++++++ src/server/security/backup.ts | 441 +++++++++++++--- src/server/security/vault.ts | 12 + 8 files changed, 1590 insertions(+), 222 deletions(-) create mode 100644 src/server/security/backup-scheduler.ts diff --git a/src/cli/gcoord.ts b/src/cli/gcoord.ts index ef67f22..c38df01 100644 --- a/src/cli/gcoord.ts +++ b/src/cli/gcoord.ts @@ -1,7 +1,16 @@ +import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline/promises'; import { parseArgs } from 'node:util'; +import argon2 from 'argon2'; +import Database from 'better-sqlite3'; +import * as OTPAuth from 'otpauth'; +import { openDatabase } from '../server/db/database.js'; +import { + encryptTotpSecret, + loadOrCreateDbKey, +} from '../server/security/auth.js'; import { createBackupBundle, restoreBackupBundle, @@ -9,24 +18,42 @@ import { } from '../server/security/backup.js'; import { EmergencyRecoveryService } from '../server/security/recovery-store.js'; import { VaultService } from '../server/security/vault.js'; +import { SettingsSchema } from '../shared/schemas/settings.schema.js'; function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: + status Inspect GCoordinator data directory state (read-only) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --json Print status summary as JSON + + panic-lock Engage Panic Lock offline: mark vault locked and revoke all sessions + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + + reset-2fa Reset TOTP authenticators offline (re-enroll new TOTP or disable 2FA) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --disable Disable requireTotpOnLogin and switch stepUpMethod to password + --json Print new secret & otpauth URI as JSON + + reset-password Reset the admin password offline (revokes all sessions & clears lockouts) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --password-file Read new password (>= 10 chars) from file instead of prompt + 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 + --new-key-out Exclusive output file (0600, O_EXCL) 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) + --passphrase-file Path to passphrase file (>= 12 chars, uses scrypt) verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data Backup bundle path (or --bundle ) + --data-dir Data directory fallback for vault.key lookup --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 @@ -41,7 +68,153 @@ Commands: `); } +function readRegularFileStrict(filePath: string): string { + const abs = path.resolve(filePath); + const stat = fs.lstatSync(abs); + if (stat.isSymbolicLink() || !stat.isFile()) { + throw new Error(`Refusing symlink or non-file path: ${abs}`); + } + return fs.readFileSync(abs, 'utf8').trim(); +} + +function writeAtomicSecureFile(targetPath: string, content: string): void { + const abs = path.resolve(targetPath); + try { + const stat = fs.lstatSync(abs); + if (stat.isSymbolicLink()) { + throw new Error(`Refusing to overwrite symlink at ${abs}`); + } + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err; + } + + fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); + const tmpPath = `${abs}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + const fd = fs.openSync(tmpPath, 'w', 0o600); + try { + fs.writeFileSync(fd, content, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + try { + fs.renameSync(tmpPath, abs); + fs.chmodSync(abs, 0o600); + } catch (err) { + try { + fs.unlinkSync(tmpPath); + } catch { + // Ignore cleanup error + } + throw err; + } +} + +function writeExclusiveSecureFile(targetPath: string, content: string): void { + const abs = path.resolve(targetPath); + fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); + const fd = fs.openSync( + abs, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + try { + fs.writeFileSync(fd, content, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } +} + +function isPidAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function withDataDirLock(dataDir: string, fn: () => Promise): Promise { + const absDir = path.resolve(dataDir); + fs.mkdirSync(absDir, { recursive: true, mode: 0o700 }); + const lockPath = path.join(absDir, 'gcoord.lock'); + + const tryAcquire = (): number => + fs.openSync( + lockPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + + let fd: number; + try { + fd = tryAcquire(); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') throw err; + const raw = fs.readFileSync(lockPath, 'utf8'); + const existingPid = Number.parseInt(raw.split(/\r?\n/)[0] ?? '', 10); + if (isPidAlive(existingPid)) { + throw new Error(`Another gcoord CLI command (PID ${existingPid}) holds ${lockPath}`); + } + fs.rmSync(lockPath, { force: true }); + fd = tryAcquire(); + } + + try { + fs.writeFileSync(fd, `${process.pid}\n${Date.now()}\n`, 'utf8'); + fs.closeSync(fd); + return await fn(); + } finally { + fs.rmSync(lockPath, { force: true }); + } +} + async function promptHiddenOrLine(promptText: string): Promise { + if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') { + process.stderr.write(promptText); + const wasRaw = Boolean(process.stdin.isRaw); + process.stdin.setRawMode(true); + process.stdin.resume(); + + return new Promise((resolve, reject) => { + let buf = ''; + const cleanup = () => { + process.stdin.off('data', onData); + try { + process.stdin.setRawMode(wasRaw); + } catch { + // Ignore restore error + } + process.stdin.pause(); + }; + const onData = (chunk: Buffer) => { + const text = chunk.toString('utf8'); + for (const ch of text) { + if (ch === '\u0003') { + cleanup(); + process.stderr.write('\n'); + reject(new Error('Aborted by user')); + return; + } + if (ch === '\r' || ch === '\n') { + cleanup(); + process.stderr.write('\n'); + resolve(buf.trim()); + return; + } + if (ch === '\u007f' || ch === '\b') { + if (buf.length > 0) buf = buf.slice(0, -1); + continue; + } + buf += ch; + } + }; + process.stdin.on('data', onData); + }); + } + const rl = readline.createInterface({ input: process.stdin, output: process.stderr, @@ -56,18 +229,19 @@ async function promptHiddenOrLine(promptText: string): Promise { async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { if (keyFile) { - return fs.readFileSync(keyFile, 'utf8').trim(); + return readRegularFileStrict(keyFile); } 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(); + const secretPath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; + if (fs.existsSync(secretPath)) { + return readRegularFileStrict(secretPath); } if (dataDir) { const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); if (fs.existsSync(localKeyFile)) { - return fs.readFileSync(localKeyFile, 'utf8').trim(); + return readRegularFileStrict(localKeyFile); } } return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): '); @@ -75,18 +249,19 @@ async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { + const settingsPath = path.join(dataDir, 'config', 'settings.json'); + if (!fs.existsSync(settingsPath)) return SettingsSchema.parse({}); + return SettingsSchema.parse(JSON.parse(readRegularFileStrict(settingsPath))); +} + +async function runStatus(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + json: { type: 'boolean', default: false }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + const vaultPath = path.join(dataDir, 'vault.enc'); + const vaultKeyPath = path.join(dataDir, 'vault.key'); + const dbKeyPath = path.join(dataDir, 'db.key'); + const panicMarkerPath = `${vaultPath}.panic-locked`; + + const status: Record = { + dataDir, + dataDirExists: fs.existsSync(dataDir), + vaultInitialized: fs.existsSync(vaultPath), + panicLocked: fs.existsSync(panicMarkerPath), + localVaultKeyFile: fs.existsSync(vaultKeyPath), + localDbKeyFile: fs.existsSync(dbKeyPath), + dbInitialized: fs.existsSync(dbPath), + }; + + if (fs.existsSync(dbPath)) { + const roDb = new Database(dbPath, { readonly: true }); + try { + const admin = roDb + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + const now = Date.now(); + const pwCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_passwords').get() as { cnt: number }).cnt; + const totpCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_totps').get() as { cnt: number }).cnt; + const passkeyCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as { cnt: number }).cnt; + const activeSessions = ( + roDb.prepare('SELECT COUNT(*) AS cnt FROM sessions WHERE expires_at > ?').get(now) as { cnt: number } + ).cnt; + const auditCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM audit_log').get() as { cnt: number }).cnt; + let activeLockouts = 0; + try { + activeLockouts = ( + roDb.prepare('SELECT COUNT(*) AS cnt FROM rate_limits WHERE locked_until > ?').get(now) as { cnt: number } + ).cnt; + } catch { + activeLockouts = 0; + } + + Object.assign(status, { + bootstrapped: Boolean(admin), + username: admin?.username ?? null, + passwordCount: pwCount, + totpCount, + passkeyCount, + activeSessions, + activeLockouts, + auditLogRows: auditCount, + }); + } finally { + roDb.close(); + } + } + + if (parsed.values.json) { + console.log(JSON.stringify(status, null, 2)); + } else { + console.log( + `GCoordinator status (${dataDir}): vault=${status.vaultInitialized ? (status.panicLocked ? 'panic-locked' : 'present') : 'uninitialized'}, db=${status.dbInitialized ? 'present' : 'missing'}, bootstrapped=${Boolean(status.bootstrapped)}, sessions=${String(status.activeSessions ?? 0)}, auditRows=${String(status.auditLogRows ?? 0)}`, + ); + } + return 0; +} + +async function runPanicLock(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + if (!fs.existsSync(dataDir)) { + console.error(`Error: Data directory not found at ${dataDir}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const markerPath = path.join(dataDir, 'vault.enc.panic-locked'); + writeAtomicSecureFile(markerPath, `${Date.now()}\n`); + + const dbPath = path.join(dataDir, 'gcoord.db'); + let revoked = 0; + if (fs.existsSync(dbPath)) { + const db = openDatabase(dbPath); + try { + revoked = db.prepare('DELETE FROM sessions').run().changes; + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', + ).run(Date.now(), 'security.cli_panic_lock', 'cli', 'vault', 'ok', JSON.stringify({ revoked })); + } finally { + db.close(); + } + } + + console.log(`Panic Lock engaged cleanly (marker=${markerPath}, revokedSessions=${revoked}).`); + return 0; + }); +} + +async function runReset2fa(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + disable: { type: 'boolean', default: false }, + json: { type: 'boolean', default: false }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + if (!fs.existsSync(dbPath)) { + console.error(`Error: Database not found at ${dbPath}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const db = openDatabase(dbPath); + try { + const admin = db + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + if (!admin) { + console.error('Error: Admin account is not bootstrapped yet'); + return 1; + } + + if (parsed.values.disable) { + const settingsPath = path.join(dataDir, 'config', 'settings.json'); + const settings = loadSettingsObject(dataDir) as { + security?: Record; + [k: string]: unknown; + }; + const updated = SettingsSchema.parse({ + ...settings, + security: { + ...(settings.security ?? {}), + requireTotpOnLogin: false, + stepUpMethod: 'password', + }, + }); + writeAtomicSecureFile(settingsPath, `${JSON.stringify(updated, null, 2)}\n`); + + db.transaction(() => { + db.prepare('DELETE FROM admin_totps').run(); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', + ).run(Date.now(), 'auth.cli_reset_2fa_disable', 'cli', admin.username, 'ok'); + })(); + + console.log('TOTP 2FA disabled offline. Sessions revoked and rate limits cleared.'); + return 0; + } + + const dbKey = loadOrCreateDbKey({ dataDir, envDbKey: process.env.GCOORD_DB_KEY }); + const secret = new OTPAuth.Secret({ size: 20 }); + const id = `totp-${crypto.randomBytes(4).toString('hex')}`; + const enc = encryptTotpSecret(dbKey, id, secret.base32); + const now = Date.now(); + const otpauthUri = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: `${admin.username} (CLI Reset)`, + algorithm: 'SHA1', + digits: 6, + period: 30, + secret, + }).toString(); + + db.transaction(() => { + db.prepare('DELETE FROM admin_totps').run(); + db.prepare( + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, 'CLI Reset Authenticator', '', ?, NULL, NULL, NULL, ?)`, + ).run(id, enc, now); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', + ).run(now, 'auth.cli_reset_2fa', 'cli', admin.username, 'ok', JSON.stringify({ totpId: id })); + })(); + + if (parsed.values.json) { + console.log( + JSON.stringify({ + reset: true, + username: admin.username, + totpId: id, + secretBase32: secret.base32, + otpauthUri, + }), + ); + } else { + console.log(`TOTP reset cleanly for "${admin.username}". Enroll this new authenticator secret:`); + console.log(`Secret (Base32): ${secret.base32}`); + console.log(`otpauth URI: ${otpauthUri}`); + } + return 0; + } finally { + db.close(); + } + }); +} + +async function runResetPassword(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + 'password-file': { type: 'string' }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + if (!fs.existsSync(dbPath)) { + console.error(`Error: Database not found at ${dbPath}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const newPassword = parsed.values['password-file'] + ? readRegularFileStrict(parsed.values['password-file']) + : await promptHiddenOrLine('Enter new admin password (>= 10 characters): '); + + if (newPassword.length < 10 || newPassword.length > 256) { + console.error('Error: Password must be between 10 and 256 characters'); + return 1; + } + + const db = openDatabase(dbPath); + try { + const admin = db + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + if (!admin) { + console.error('Error: Admin account is not bootstrapped yet'); + return 1; + } + + const hash = await argon2.hash(newPassword, { + type: argon2.argon2id, + memoryCost: 32768, + timeCost: 3, + parallelism: 1, + }); + const now = Date.now(); + + db.transaction(() => { + db.prepare('DELETE FROM admin_passwords').run(); + db.prepare( + 'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)', + ).run('pw-primary', 'Primary Password', hash, now); + db.prepare("UPDATE admin_users SET password_hash = '', updated_at = ? WHERE id = 1").run( + now, + ); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', + ).run(now, 'auth.cli_reset_password', 'cli', admin.username, 'ok'); + })(); + + console.log( + `Admin password reset cleanly for "${admin.username}". All active sessions revoked.`, + ); + return 0; + } finally { + db.close(); + } + }); +} + async function runRotateKey(args: string[]): Promise { const parsed = parseArgs({ args, @@ -122,32 +601,40 @@ async function runRotateKey(args: string[]): Promise { return 1; } - const currentKey = await readCurrentKey(parsed.values['current-key-file']); - const vault = new VaultService(vaultPath); - vault.unlock(currentKey); - const { generatedKeyHex } = vault.rotateMasterKey(); + return withDataDirLock(dataDir, async () => { + const currentKey = await readCurrentKey(parsed.values['current-key-file'], dataDir); + const vault = new VaultService(vaultPath, { + keyFilePath: path.join(dataDir, 'vault.key'), + }); + vault.unlock(currentKey); + const { generatedKeyHex } = vault.rotateMasterKey(); - if (!generatedKeyHex) { - console.error('Error: Unexpected empty rotated key'); - return 1; - } + 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' }); - } + const recovery = new EmergencyRecoveryService(dataDir); + const settings = loadSettingsObject(dataDir) as { + security?: { enableEmergencySecretsBackup?: boolean }; + }; + if ( + settings.security?.enableEmergencySecretsBackup && + 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; + if (parsed.values['new-key-out']) { + const outPath = path.resolve(parsed.values['new-key-out']); + writeExclusiveSecureFile(outPath, `${generatedKeyHex}\n`); + 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 { @@ -183,17 +670,7 @@ async function runBackup(args: string[]): Promise { }); 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); + writeAtomicSecureFile(outPath, result.serialized); console.log( `Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`, @@ -206,6 +683,7 @@ async function runVerifyBackup(args: string[]): Promise { args, options: { bundle: { type: 'string' }, + 'data-dir': { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, 'vault-key-file': { type: 'string' }, @@ -220,17 +698,26 @@ async function runVerifyBackup(args: string[]): Promise { return 1; } - const rawBuf = fs.readFileSync(path.resolve(bundleArg)); + const dataDir = parsed.values['data-dir'] + ? path.resolve(parsed.values['data-dir']) + : process.env.GCOORD_DATA_DIR + ? path.resolve(process.env.GCOORD_DATA_DIR) + : undefined; + + const bundlePath = path.resolve(bundleArg); + const rawBuf = Buffer.from(readRegularFileStrict(bundlePath), 'utf8'); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); - let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']); + let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); 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)'); + throw new Error( + 'Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)', + ); } - masterKey = await readCurrentKey(undefined); + masterKey = await readCurrentKey(undefined, dataDir); } - const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']); + const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); const summary = verifyBackupSummaryOnly(rawBuf, { masterKey, @@ -270,25 +757,28 @@ async function runRestore(args: string[]): Promise { 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, + return withDataDirLock(dataDir, async () => { + const rawBuf = Buffer.from(readRegularFileStrict(bundleArg), 'utf8'); + 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; }); - - console.log( - `Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`, - ); - return 0; } async function main(): Promise { @@ -298,22 +788,25 @@ async function main(): Promise { 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)); + const handlers: Record Promise> = { + status: runStatus, + 'panic-lock': runPanicLock, + 'reset-2fa': runReset2fa, + 'reset-password': runResetPassword, + 'rotate-key': runRotateKey, + backup: runBackup, + 'verify-backup': runVerifyBackup, + restore: runRestore, + }; + + const handler = handlers[command]; + if (!handler) { + console.error(`Unknown command: ${command}`); + printUsage(); + process.exit(1); } - console.error(`Unknown command: ${command}`); - printUsage(); - process.exit(1); + process.exit(await handler(rest)); } main().catch((err) => { diff --git a/src/server/api/routes/audit.routes.ts b/src/server/api/routes/audit.routes.ts index 48b66a5..1194bcc 100644 --- a/src/server/api/routes/audit.routes.ts +++ b/src/server/api/routes/audit.routes.ts @@ -1,8 +1,33 @@ import { Router } from 'express'; -import type { AuditService } from '../../security/audit.js'; +import { z } from 'zod'; +import type { AuditListOptions, AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { requireAuth } from '../../security/guards.js'; +const AuditQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(200).optional(), + offset: z.coerce.number().int().min(0).optional(), + action: z.string().trim().min(1).max(128).optional(), + actionPrefix: z.string().trim().min(1).max(64).optional(), + status: z.enum(['ok', 'denied', 'error']).optional(), + ip: z.string().trim().min(1).max(64).optional(), + target: z.string().trim().min(1).max(128).optional(), + q: z.string().trim().min(1).max(128).optional(), + from: z.coerce.number().int().min(0).optional(), + to: z.coerce.number().int().min(0).optional(), + format: z.enum(['csv', 'ndjson']).optional(), +}); + +function pickFilterOptions(raw: Record): AuditListOptions & { format?: 'csv' | 'ndjson' } { + const cleaned: Record = {}; + for (const [k, v] of Object.entries(raw)) { + if (typeof v === 'string' && v.trim() === '') continue; + cleaned[k] = v; + } + const parsed = AuditQuerySchema.safeParse(cleaned); + return parsed.success ? parsed.data : {}; +} + export function createAuditRouter( authService: AuthService, auditService: AuditService, @@ -10,20 +35,37 @@ export function createAuditRouter( const router = Router(); router.get('/', requireAuth(authService), (req, res) => { - const limit = req.query.limit ? Number(req.query.limit) : 50; - const offset = req.query.offset ? Number(req.query.offset) : 0; - const action = - typeof req.query.action === 'string' && req.query.action.trim() - ? req.query.action.trim() - : undefined; + const opts = pickFilterOptions(req.query as Record); + const result = auditService.list(opts); + res.json({ + ...result, + actions: auditService.listActions(), + }); + }); - res.json( - auditService.list({ - limit: Number.isFinite(limit) ? limit : 50, - offset: Number.isFinite(offset) ? offset : 0, - action, - }), + router.get('/export', requireAuth(authService), (req, res) => { + const opts = pickFilterOptions(req.query as Record); + const format = opts.format ?? 'ndjson'; + const content = auditService.exportRecords(opts, format); + + auditService.log({ + action: 'audit.export', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: format, + status: 'ok', + }); + + res.setHeader('Cache-Control', 'no-store'); + res.setHeader( + 'Content-Type', + format === 'csv' ? 'text/csv; charset=utf-8' : 'application/x-ndjson; charset=utf-8', ); + res.setHeader( + 'Content-Disposition', + `attachment; filename="gcoordinator-audit-export.${format === 'csv' ? 'csv' : 'ndjson'}"`, + ); + res.send(content); }); return router; diff --git a/src/server/api/routes/backup.routes.ts b/src/server/api/routes/backup.routes.ts index 70aff8a..a4ba2b1 100644 --- a/src/server/api/routes/backup.routes.ts +++ b/src/server/api/routes/backup.routes.ts @@ -1,17 +1,21 @@ import type Database from 'better-sqlite3'; -import { Router, type RequestHandler } from 'express'; +import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express'; import { z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; +import type { RuntimeLimits } from '../../config/runtime-limits.js'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { - createBackupBundle, - restoreBackupBundle, - verifyBackupSummaryOnly, + BackupBusyError, + createBackupBundleAsync, + restoreBackupBundleAsync, + verifyBackupSummaryOnlyAsync, type BackupInnerPayload, type BackupVerificationSummary, } from '../../security/backup.js'; +import type { BackupScheduler } from '../../security/backup-scheduler.js'; import { + asyncHandler, enforceSafeMode, requireAuth, requireCsrf, @@ -26,6 +30,8 @@ export interface BackupRouterDeps { configManager: ConfigManager; auditService: AuditService; stepUpGuard: RequestHandler; + getRuntimeLimits?: () => RuntimeLimits; + backupScheduler?: BackupScheduler; onRestored: (info: { summary: BackupVerificationSummary; inner: BackupInnerPayload; @@ -54,6 +60,8 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { configManager, auditService, stepUpGuard, + getRuntimeLimits, + backupScheduler, onRestored, } = deps; @@ -63,7 +71,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - (req, res) => { + asyncHandler(async (req, res) => { const parsed = ExportBackupBodySchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); @@ -81,11 +89,13 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { } try { - const result = createBackupBundle({ + const limits = getRuntimeLimits?.(); + const result = await createBackupBundleAsync({ dataDir, db, masterKey, passphrase, + scryptConcurrency: limits?.scryptConcurrency, }); const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); const filename = `gcoordinator-backup-${stamp}.gcoord.enc`; @@ -109,38 +119,73 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { summary: result.summary, }); } catch (err) { + if (err instanceof BackupBusyError) throw err; res.status(400).json({ error: 'BACKUP_EXPORT_ERROR', message: err instanceof Error ? err.message : 'Unable to create backup bundle', }); } - }, + }), ); - // Read-only verification: exempt from enforceSafeMode - router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => { - const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + // Read-only verification: exempt from enforceSafeMode, still requires step-up and writes audit entry + router.post( + '/verify', + requireAuth(authService), + requireCsrf, + stepUpGuard, + asyncHandler(async (req, res) => { + const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - try { + const limits = getRuntimeLimits?.(); + const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); - const summary = verifyBackupSummaryOnly(rawBuf, { - masterKey: - parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined, - passphrase: parsed.data.passphrase?.trim() || undefined, - vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined, - }); - res.json({ summary }); - } catch (err) { - res.status(400).json({ - error: 'BACKUP_INVALID', - message: err instanceof Error ? err.message : 'Backup verification failed', - }); - } - }); + if (rawBuf.length > maxBodyBytes) { + res.status(413).json({ + error: 'PAYLOAD_TOO_LARGE', + message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, + }); + return; + } + + try { + const summary = await verifyBackupSummaryOnlyAsync(rawBuf, { + masterKey: + parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined, + passphrase: parsed.data.passphrase?.trim() || undefined, + vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined, + scryptConcurrency: limits?.scryptConcurrency, + maxGunzipBytes: limits?.backupMaxGunzipBytes, + }); + auditService.log({ + action: 'backup.verify', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: summary.kdf, + status: 'ok', + details: { configFileCount: summary.configFileCount, vaultVerified: summary.vaultVerified }, + }); + res.json({ summary }); + } catch (err) { + if (err instanceof BackupBusyError) throw err; + auditService.log({ + action: 'backup.verify', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'error', + details: { message: err instanceof Error ? err.message : 'Verification failed' }, + }); + res.status(400).json({ + error: 'BACKUP_INVALID', + message: err instanceof Error ? err.message : 'Backup verification failed', + }); + } + }), + ); router.post( '/restore', @@ -148,14 +193,24 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(async (req, res) => { const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; } + const limits = getRuntimeLimits?.(); + const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); + if (rawBuf.length > maxBodyBytes) { + res.status(413).json({ + error: 'PAYLOAD_TOO_LARGE', + message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, + }); + return; + } + const passphrase = parsed.data.passphrase?.trim() || undefined; const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined; const masterKey = parsed.data.masterKey?.trim() || runtimeKey; @@ -163,12 +218,14 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { const wasWatching = await configManager.pauseWatcher(); try { - const restored = restoreBackupBundle(rawBuf, { + const restored = await restoreBackupBundleAsync(rawBuf, { dataDir, db, masterKey, passphrase, vaultMasterKey, + scryptConcurrency: limits?.scryptConcurrency, + maxGunzipBytes: limits?.backupMaxGunzipBytes, }); await onRestored({ @@ -192,6 +249,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { res.json({ restored: true, summary: restored.summary }); } catch (err) { + if (err instanceof BackupBusyError) throw err; auditService.log({ action: 'backup.restore', actorIp: req.clientIp ?? 'unknown', @@ -209,8 +267,44 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { await configManager.resumeWatcher(); } } - }, + }), ); + router.get('/schedule', requireAuth(authService), (_req, res) => { + if (!backupScheduler) { + res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); + return; + } + res.json({ schedule: backupScheduler.getStatus() }); + }); + + router.post( + '/schedule/run', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + asyncHandler(async (_req, res) => { + if (!backupScheduler) { + res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); + return; + } + const outcome = await backupScheduler.runNow('manual'); + res.status(outcome.ok ? 200 : 400).json({ + ...outcome, + schedule: backupScheduler.getStatus(), + }); + }), + ); + + router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { + if (err instanceof BackupBusyError) { + res.setHeader('Retry-After', '2'); + res.status(503).json({ error: err.code, message: err.message }); + return; + } + next(err); + }); + return router; } diff --git a/src/server/app.ts b/src/server/app.ts index 2b889a8..2b2c901 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -17,6 +17,7 @@ import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; +import { BackupScheduler } from './security/backup-scheduler.js'; import { DEFAULT_TRUSTED_PROXY_CIDRS, RateLimiter, @@ -88,6 +89,7 @@ export interface GCoordinatorInstance { customSystemsEngine: CustomSystemsEngine; serverInspector: ServerInspector; monitoringService: MonitoringService; + backupScheduler: BackupScheduler; transferEngine: TransferEngine; workflowEngine: WorkflowEngine; broadcastService: BroadcastService; @@ -231,6 +233,15 @@ export async function createGCoordinatorServer( wsHub, auditService, ); + const backupScheduler = new BackupScheduler( + dataDir, + db, + configManager, + vaultService, + sftpService, + auditService, + getRuntimeLimits, + ); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); @@ -319,11 +330,16 @@ export async function createGCoordinatorServer( app.use('/proxy', createProxyRouter({ authService, tunnelManager })); const jsonParser = express.json({ limit: '2mb' }); + const backupJsonParser = express.json({ limit: '16mb' }); app.use((req, res, next) => { if (req.path.endsWith('/sftp/upload')) { next(); return; } + if (req.path.startsWith('/api/backup/')) { + backupJsonParser(req, res, next); + return; + } jsonParser(req, res, next); }); @@ -356,9 +372,12 @@ export async function createGCoordinatorServer( customSystemsEngine.syncBackgroundChecks(); workflowEngine.start(); alertEngine.start(); + backupScheduler.start(); + auditService.pruneOlderThan(configManager.getSettings().auditRetentionDays); vaultService.onSeal(() => { aiService.cancelAll(); + backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -372,6 +391,7 @@ export async function createGCoordinatorServer( vaultService.onPanicLock(() => { aiService.cancelAll(); + backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -421,6 +441,7 @@ export async function createGCoordinatorServer( monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); + backupScheduler.sync(); void tunnelManager.syncAutoStart(); } }); @@ -461,6 +482,7 @@ export async function createGCoordinatorServer( monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); + backupScheduler.sync(); void tunnelManager.syncAutoStart(); }, onVaultChanged: (snapshotReason) => { @@ -480,18 +502,27 @@ export async function createGCoordinatorServer( configManager, auditService, stepUpGuard, + getRuntimeLimits, + backupScheduler, onRestored: async ({ inner, vaultKeyCandidate }) => { if (inner.vaultEnvelopeRaw !== null) { try { vaultService.reloadFromDisk(vaultKeyCandidate); } catch { - // Keep existing runtime state untouched if backup vault used a different key + // Avoid keeping an old runtime master key unlocked against a newly restored foreign vault + vaultService.seal(); + vaultService.dropLocalKeyFile(); } } knownHosts.replaceAllKnownHosts(inner.knownHosts); configManager.reloadAllFromDisk(); sshPool.syncWithConfig(); - if (authService.isBootstrapped() && vaultService.isRuntimeReady) { + backupScheduler.sync(); + if ( + authService.isBootstrapped() && + vaultService.isRuntimeReady && + configManager.getSettings().security.enableEmergencySecretsBackup + ) { authService.syncRecovery({ snapshotReason: 'backup-restore' }); } wsHub.broadcastAll({ @@ -620,6 +651,7 @@ export async function createGCoordinatorServer( customSystemsEngine, serverInspector, monitoringService, + backupScheduler, transferEngine, workflowEngine, broadcastService, @@ -629,6 +661,7 @@ export async function createGCoordinatorServer( port: actualPort, async close() { aiService.close(); + backupScheduler.close(); alertEngine.close(); workflowEngine.close(); broadcastService.cancelAll(); diff --git a/src/server/security/audit.ts b/src/server/security/audit.ts index e63d78d..c7146e5 100644 --- a/src/server/security/audit.ts +++ b/src/server/security/audit.ts @@ -20,6 +20,28 @@ export interface AuditLogRecord { details: string | null; } +export interface AuditListOptions { + limit?: number; + offset?: number; + action?: string; + actionPrefix?: string; + status?: 'ok' | 'denied' | 'error'; + ip?: string; + target?: string; + q?: string; + from?: number; + to?: number; +} + +function escapeLike(input: string): string { + return input.replace(/[\\%_]/g, '\\$&'); +} + +function sanitizeCsvCell(value: string): string { + const safe = /^[ \t]*[=+\-@\t\r]/.test(value) ? `'${value}` : value; + return `"${safe.replace(/"/g, '""')}"`; +} + export class AuditService { private readonly insertStmt; @@ -49,33 +71,143 @@ export class AuditService { ); } - list(options: { limit?: number; offset?: number; action?: string } = {}): { + private buildWhereClause(options: AuditListOptions): { sql: string; params: Array } { + const clauses: string[] = []; + const params: Array = []; + + if (options.action) { + clauses.push('action = ?'); + params.push(options.action); + } else if (options.actionPrefix) { + clauses.push("action LIKE ? ESCAPE '\\'"); + params.push(`${escapeLike(options.actionPrefix)}%`); + } + + if (options.status) { + clauses.push('status = ?'); + params.push(options.status); + } + + if (options.ip) { + clauses.push('actor_ip = ?'); + params.push(options.ip); + } + + if (options.target) { + clauses.push("target LIKE ? ESCAPE '\\'"); + params.push(`%${escapeLike(options.target)}%`); + } + + if (typeof options.from === 'number' && Number.isFinite(options.from)) { + clauses.push('ts >= ?'); + params.push(options.from); + } + if (typeof options.to === 'number' && Number.isFinite(options.to)) { + clauses.push('ts <= ?'); + params.push(options.to); + } + + if (options.q) { + const needle = `%${escapeLike(options.q)}%`; + clauses.push( + "(action LIKE ? ESCAPE '\\' OR actor_ip LIKE ? ESCAPE '\\' OR COALESCE(target, '') LIKE ? ESCAPE '\\' OR COALESCE(details, '') LIKE ? ESCAPE '\\')", + ); + params.push(needle, needle, needle, needle); + } + + return { + sql: clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '', + params, + }; + } + + list(options: AuditListOptions = {}): { total: number; items: AuditLogRecord[]; } { const limit = Math.max(1, Math.min(200, options.limit ?? 50)); const offset = Math.max(0, options.offset ?? 0); - - if (options.action) { - const countRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?') - .get(options.action) as { cnt: number }; - const items = this.db - .prepare( - 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', - ) - .all(options.action, limit, offset) as AuditLogRecord[]; - return { total: countRow.cnt, items }; - } + const where = this.buildWhereClause(options); const countRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM audit_log') - .get() as { cnt: number }; + .prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`) + .get(...where.params) as { cnt: number }; + const items = this.db .prepare( - 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', + `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details + FROM audit_log ${where.sql} + ORDER BY ts DESC, id DESC + LIMIT ? OFFSET ?`, ) - .all(limit, offset) as AuditLogRecord[]; + .all(...where.params, limit, offset) as AuditLogRecord[]; + return { total: countRow.cnt, items }; } + + listActions(): string[] { + const rows = this.db + .prepare('SELECT DISTINCT action FROM audit_log ORDER BY action ASC LIMIT 200') + .all() as Array<{ action: string }>; + return rows.map((r) => r.action); + } + + exportRecords( + options: AuditListOptions, + format: 'csv' | 'ndjson', + maxRows = 10_000, + ): string { + const cap = Math.max(1, Math.min(50_000, maxRows)); + const where = this.buildWhereClause(options); + const rows = this.db + .prepare( + `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details + FROM audit_log ${where.sql} + ORDER BY ts DESC, id DESC + LIMIT ?`, + ) + .all(...where.params, cap) as AuditLogRecord[]; + + if (format === 'ndjson') { + return `${rows + .map((r) => + JSON.stringify({ + id: r.id, + ts: r.ts, + isoTime: new Date(r.ts).toISOString(), + action: r.action, + status: r.status, + actorIp: r.actor_ip, + target: r.target, + sessionIdHash: r.session_id_hash, + details: r.details, + }), + ) + .join('\n')}\n`; + } + + const lines = [ + 'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details', + ...rows.map((r) => + [ + String(r.id), + String(r.ts), + sanitizeCsvCell(new Date(r.ts).toISOString()), + sanitizeCsvCell(r.action), + sanitizeCsvCell(r.status), + sanitizeCsvCell(r.actor_ip), + sanitizeCsvCell(r.target ?? ''), + sanitizeCsvCell(r.session_id_hash ?? ''), + sanitizeCsvCell(r.details ?? ''), + ].join(','), + ), + ]; + return `${lines.join('\n')}\n`; + } + + pruneOlderThan(retentionDays: number): number { + const days = Math.max(1, retentionDays); + const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; + return this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(cutoff).changes; + } } diff --git a/src/server/security/backup-scheduler.ts b/src/server/security/backup-scheduler.ts new file mode 100644 index 0000000..abd4409 --- /dev/null +++ b/src/server/security/backup-scheduler.ts @@ -0,0 +1,275 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { Readable } from 'node:stream'; +import type Database from 'better-sqlite3'; +import { Cron } from 'croner'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; +import type { SftpService } from '../ssh/sftp-service.js'; +import type { AuditService } from './audit.js'; +import { createBackupBundleAsync } from './backup.js'; +import type { VaultService } from './vault.js'; + +export interface ScheduledBackupStatus { + enabled: boolean; + cron: string; + timezone: string; + destination: 'local' | 'sftp'; + running: boolean; + lastRunAt: number | null; + lastStatus: 'never' | 'ok' | 'error' | 'skipped'; + lastFilename: string | null; + lastError: string | null; + nextRunAt: number | null; + localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; +} + +function resolveSafeLocalBackupDir(dataDir: string, rawLocalDir: string): string { + const baseDir = path.resolve(dataDir); + const rel = rawLocalDir.trim() || 'backups'; + if (path.isAbsolute(rel) || rel.includes('..') || rel.includes('\\')) { + throw new Error(`Unsafe local backup directory: ${rawLocalDir}`); + } + const targetDir = path.resolve(baseDir, rel); + if (targetDir === baseDir || !targetDir.startsWith(`${baseDir}${path.sep}`)) { + throw new Error(`Local backup directory must stay inside dataDir: ${rawLocalDir}`); + } + return targetDir; +} + +export class BackupScheduler { + private job: Cron | null = null; + private running = false; + private closed = false; + private lastRunAt: number | null = null; + private lastStatus: ScheduledBackupStatus['lastStatus'] = 'never'; + private lastFilename: string | null = null; + private lastError: string | null = null; + + constructor( + private readonly dataDir: string, + private readonly db: Database.Database, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sftpService: SftpService, + private readonly auditService: AuditService, + private readonly getRuntimeLimits: () => RuntimeLimits, + ) {} + + start(): void { + this.sync(); + } + + stop(): void { + if (this.job) { + this.job.stop(); + this.job = null; + } + } + + close(): void { + this.closed = true; + this.stop(); + } + + sync(): void { + this.stop(); + if (this.closed || !this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { + return; + } + const cfg = this.configManager.getSettings().scheduledBackup; + if (!cfg?.enabled) { + return; + } + try { + this.job = new Cron( + cfg.cron, + { + timezone: cfg.timezone || 'UTC', + protect: true, + }, + () => { + void this.runNow('cron'); + }, + ); + } catch (err) { + this.lastStatus = 'error'; + this.lastError = err instanceof Error ? err.message : 'Invalid backup cron expression'; + } + } + + getStatus(): ScheduledBackupStatus { + const cfg = this.configManager.getSettings().scheduledBackup; + let localFiles: ScheduledBackupStatus['localFiles'] = []; + try { + const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); + if (fs.existsSync(dir) && !fs.lstatSync(dir).isSymbolicLink()) { + localFiles = fs + .readdirSync(dir) + .filter((name) => name.endsWith('.gcoord.enc')) + .map((name) => { + const p = path.join(dir, name); + const st = fs.lstatSync(p); + return !st.isSymbolicLink() && st.isFile() + ? { name, sizeBytes: st.size, mtimeMs: st.mtimeMs } + : null; + }) + .filter((v): v is NonNullable => v !== null) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + } + } catch { + localFiles = []; + } + + const nextDate = this.job?.nextRun() ?? null; + return { + enabled: Boolean(cfg.enabled), + cron: cfg.cron, + timezone: cfg.timezone, + destination: cfg.destination, + running: this.running, + lastRunAt: this.lastRunAt, + lastStatus: this.lastStatus, + lastFilename: this.lastFilename, + lastError: this.lastError, + nextRunAt: nextDate ? nextDate.getTime() : null, + localFiles, + }; + } + + async runNow(trigger: 'cron' | 'manual' = 'manual'): Promise<{ + ok: boolean; + filename?: string; + message?: string; + }> { + if (this.closed) { + return { ok: false, message: 'Scheduler stopped' }; + } + if (this.running) { + return { ok: false, message: 'Scheduled backup already in progress' }; + } + if (!this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { + this.lastRunAt = Date.now(); + this.lastStatus = 'skipped'; + this.lastError = 'Vault is sealed'; + return { ok: false, message: 'Vault is sealed' }; + } + + const cfg = this.configManager.getSettings().scheduledBackup; + this.running = true; + try { + let passphrase: string | undefined; + if (cfg.passphraseSecretRef) { + const cred = this.vaultService.getSecret(cfg.passphraseSecretRef); + if (!cred) { + throw new Error(`Backup passphrase secret "${cfg.passphraseSecretRef}" not found in Vault`); + } + passphrase = + cred.type === 'api-token' + ? cred.token + : cred.type === 'webhook-secret' + ? cred.secret + : undefined; + if (!passphrase) { + throw new Error( + `Credential "${cfg.passphraseSecretRef}" must be an api-token or webhook-secret`, + ); + } + } + + const masterKey = this.vaultService.exportMasterKeyHex() ?? undefined; + const limits = this.getRuntimeLimits(); + const result = await createBackupBundleAsync({ + dataDir: this.dataDir, + db: this.db, + masterKey, + passphrase, + scryptConcurrency: limits.scryptConcurrency, + }); + + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `gcoord-sched-${stamp}.gcoord.enc`; + + if (cfg.destination === 'sftp') { + if (!cfg.remoteServerId || !cfg.remotePath) { + throw new Error('SFTP scheduled backup requires remoteServerId and remotePath'); + } + const remoteDir = path.posix.normalize(cfg.remotePath).replace(/\/+$/, '') || '/'; + const remoteFile = path.posix.join(remoteDir, filename); + const buf = Buffer.from(result.serialized, 'utf8'); + await this.sftpService.uploadStream(cfg.remoteServerId, remoteFile, Readable.from([buf])); + try { + const listing = await this.sftpService.listDirectory(cfg.remoteServerId, remoteDir); + const oldFiles = listing.entries + .filter( + (e) => + e.type === 'file' && + e.name.startsWith('gcoord-sched-') && + e.name.endsWith('.gcoord.enc'), + ) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + for (const stale of oldFiles.slice(cfg.retentionCount)) { + await this.sftpService.deletePath(cfg.remoteServerId, stale.path, false); + } + } catch { + // Best-effort remote retention pruning + } + } else { + const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const outPath = path.join(dir, filename); + const tmpPath = `${outPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + 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); + + const existing = fs + .readdirSync(dir) + .filter((n) => n.startsWith('gcoord-sched-') && n.endsWith('.gcoord.enc')) + .map((n) => ({ + path: path.join(dir, n), + mtime: fs.lstatSync(path.join(dir, n)).mtimeMs, + })) + .sort((a, b) => b.mtime - a.mtime); + for (const stale of existing.slice(cfg.retentionCount)) { + fs.rmSync(stale.path, { force: true }); + } + } + + this.lastRunAt = Date.now(); + this.lastStatus = 'ok'; + this.lastFilename = filename; + this.lastError = null; + this.auditService.log({ + action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', + actorIp: 'system', + target: filename, + status: 'ok', + details: { destination: cfg.destination, kdf: result.summary.kdf }, + }); + return { ok: true, filename }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + this.lastRunAt = Date.now(); + this.lastStatus = 'error'; + this.lastError = message; + this.auditService.log({ + action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', + actorIp: 'system', + target: cfg.destination, + status: 'error', + details: { message }, + }); + return { ok: false, message }; + } finally { + this.running = false; + } + } +} diff --git a/src/server/security/backup.ts b/src/server/security/backup.ts index f6daf45..1967ff3 100644 --- a/src/server/security/backup.ts +++ b/src/server/security/backup.ts @@ -21,6 +21,13 @@ export const BackupEnvelopeSchema = z.object({ alg: z.literal('aes-256-gcm'), kdf: z.enum(['raw-master-key', 'scrypt']), salt: z.string().optional(), + kdfParams: z + .object({ + N: z.number().int().min(16384).max(65536), + r: z.number().int().min(4).max(16), + p: z.number().int().min(1).max(4), + }) + .optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -76,9 +83,62 @@ export interface BackupVerificationSummary { overlayCount: number; } +export class BackupBusyError extends Error { + readonly code = 'BACKUP_KDF_BUSY'; + constructor(message = 'Backup encryption worker queue is busy; try again shortly') { + super(message); + this.name = 'BackupBusyError'; + } +} + const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; -const MAX_GUNZIP_BYTES = 32 * 1024 * 1024; +const DEFAULT_MAX_GUNZIP_BYTES = 32 * 1024 * 1024; const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const; +const BACKUP_AAD = Buffer.from('gcoord-backup-v1', 'utf8'); +const MIN_BACKUP_PASSPHRASE_LEN = 12; +const MAX_SCRYPT_QUEUE = 8; + +let scryptActive = 0; +const scryptWaiters: Array<() => void> = []; + +async function runScryptAsync( + password: string, + salt: Buffer, + params: { N: number; r: number; p: number; maxmem: number }, + concurrency = 1, +): Promise { + const limit = Math.max(1, concurrency); + if (scryptActive >= limit) { + if (scryptWaiters.length >= MAX_SCRYPT_QUEUE) { + throw new BackupBusyError(); + } + await new Promise((resolve) => { + scryptWaiters.push(resolve); + }); + } + scryptActive += 1; + try { + return await new Promise((resolve, reject) => { + crypto.scrypt(password, salt, 32, params, (err, derived) => { + if (err) reject(err); + else resolve(derived); + }); + }); + } finally { + scryptActive -= 1; + const next = scryptWaiters.shift(); + if (next) next(); + } +} + +function isRegularNonSymlink(filePath: string): boolean { + try { + const stat = fs.lstatSync(filePath); + return !stat.isSymbolicLink() && stat.isFile(); + } catch { + return false; + } +} function validateAndParseConfigEntry( relPath: string, @@ -147,18 +207,23 @@ function collectConfigFilesFromDisk(configDir: string): Record { for (const name of ['settings.json', 'alerts.json', 'snippets.json']) { const abs = path.join(configDir, name); - if (fs.existsSync(abs)) { + if (isRegularNonSymlink(abs)) { out[name] = fs.readFileSync(abs, 'utf8'); } } for (const folder of ['servers', 'systems', 'workflows']) { const dir = path.join(configDir, folder); - if (!fs.existsSync(dir)) continue; + try { + const dirStat = fs.lstatSync(dir); + if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue; + } catch { + continue; + } for (const entry of fs.readdirSync(dir).sort()) { if (!entry.endsWith('.json') || entry.includes('.tmp')) continue; const rel = `${folder}/${entry}`; const abs = path.join(dir, entry); - if (fs.statSync(abs).isFile()) { + if (isRegularNonSymlink(abs)) { out[rel] = fs.readFileSync(abs, 'utf8'); } } @@ -166,6 +231,17 @@ function collectConfigFilesFromDisk(configDir: string): Record { return out; } +function validateEncryptPassphrase(passphrase?: string): string | undefined { + const pass = passphrase?.trim(); + if (!pass || pass.length === 0) return undefined; + if (pass.length < MIN_BACKUP_PASSPHRASE_LEN) { + throw new Error( + `Backup passphrase must be at least ${MIN_BACKUP_PASSPHRASE_LEN} characters`, + ); + } + return pass; +} + function deriveEnvelopeKeyForEncrypt(opts: { masterKey?: string; passphrase?: string; @@ -173,12 +249,18 @@ function deriveEnvelopeKeyForEncrypt(opts: { key: Buffer; kdf: 'raw-master-key' | 'scrypt'; saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; } { - const pass = opts.passphrase?.trim(); - if (pass && pass.length > 0) { + const pass = validateEncryptPassphrase(opts.passphrase); + if (pass) { const salt = crypto.randomBytes(16); const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); - return { key, kdf: 'scrypt', saltB64: salt.toString('base64') }; + return { + key, + kdf: 'scrypt', + saltB64: salt.toString('base64'), + kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, + }; } if (!opts.masterKey || !opts.masterKey.trim()) { throw new Error('Either Vault master key or backup passphrase is required'); @@ -186,40 +268,92 @@ function deriveEnvelopeKeyForEncrypt(opts: { return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' }; } +async function deriveEnvelopeKeyForEncryptAsync(opts: { + masterKey?: string; + passphrase?: string; + scryptConcurrency?: number; +}): Promise<{ + key: Buffer; + kdf: 'raw-master-key' | 'scrypt'; + saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; +}> { + const pass = validateEncryptPassphrase(opts.passphrase); + if (pass) { + const salt = crypto.randomBytes(16); + const key = await runScryptAsync(pass, salt, SCRYPT_PARAMS, opts.scryptConcurrency); + return { + key, + kdf: 'scrypt', + saltB64: salt.toString('base64'), + kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, + }; + } + if (!opts.masterKey || !opts.masterKey.trim()) { + throw new Error('Either Vault master key or backup passphrase is required'); + } + return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' }; +} + +function getDecryptScryptInputs( + envelope: BackupEnvelope, + opts: { masterKey?: string; passphrase?: string }, +): { pass: string; salt: Buffer; params: { N: number; r: number; p: number; maxmem: number } } { + const pass = opts.passphrase?.trim(); + if (!pass) { + throw new Error('This backup is encrypted with a passphrase; provide backup passphrase'); + } + if (!envelope.salt) { + throw new Error('Backup envelope is missing scrypt salt'); + } + const salt = Buffer.from(envelope.salt, 'base64'); + if (salt.length < 8) { + throw new Error('Backup envelope contains an invalid scrypt salt'); + } + const p = envelope.kdfParams; + const params = p + ? { N: p.N, r: p.r, p: p.p, maxmem: 128 * 1024 * 1024 } + : SCRYPT_PARAMS; + return { pass, salt, params }; +} + function deriveEnvelopeKeyForDecrypt( envelope: BackupEnvelope, opts: { masterKey?: string; passphrase?: string }, ): Buffer { if (envelope.kdf === 'scrypt') { - const pass = opts.passphrase?.trim(); - if (!pass) { - throw new Error('This backup is encrypted with a passphrase; provide backup passphrase'); - } - if (!envelope.salt) { - throw new Error('Backup envelope is missing scrypt salt'); - } - const salt = Buffer.from(envelope.salt, 'base64'); - if (salt.length < 8) { - throw new Error('Backup envelope contains an invalid scrypt salt'); - } - return crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); + const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); + return crypto.scryptSync(pass, salt, 32, params); } - if (!opts.masterKey || !opts.masterKey.trim()) { throw new Error('This backup requires the 32-byte Vault master key to decrypt'); } return parseMasterKey(opts.masterKey); } -export function createBackupBundle(opts: { +async function deriveEnvelopeKeyForDecryptAsync( + envelope: BackupEnvelope, + opts: { masterKey?: string; passphrase?: string; scryptConcurrency?: number }, +): Promise { + if (envelope.kdf === 'scrypt') { + const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); + return runScryptAsync(pass, salt, params, opts.scryptConcurrency); + } + if (!opts.masterKey || !opts.masterKey.trim()) { + throw new Error('This backup requires the 32-byte Vault master key to decrypt'); + } + return parseMasterKey(opts.masterKey); +} + +function prepareBackupInner(opts: { dataDir: string; db?: Database.Database; masterKey?: string; - passphrase?: string; }): { - serialized: string; - envelope: BackupEnvelope; - summary: BackupVerificationSummary; + inner: BackupInnerPayload; + vaultVerified: boolean; + vaultCredentialCount?: number; + overlayCount: number; } { const dataDir = path.resolve(opts.dataDir); const configDir = path.join(dataDir, 'config'); @@ -232,7 +366,7 @@ export function createBackupBundle(opts: { overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; } - const vaultEnvelopeRaw = fs.existsSync(vaultPath) + const vaultEnvelopeRaw = isRegularNonSymlink(vaultPath) ? fs.readFileSync(vaultPath, 'utf8') : null; let vaultVerified = false; @@ -249,7 +383,7 @@ export function createBackupBundle(opts: { let localDb: Database.Database | null = null; const db = opts.db ?? - (fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null); + (isRegularNonSymlink(dbPath) ? (localDb = openDatabase(dbPath)) : null); let knownHosts: Array> = []; let alertSilences: Array> = []; @@ -257,7 +391,7 @@ export function createBackupBundle(opts: { if (db) { knownHosts = db .prepare( - 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC', ) .all() as Array>; @@ -286,17 +420,29 @@ export function createBackupBundle(opts: { knownHosts, dbMeta: { alertSilences }, }; + return { inner, vaultVerified, vaultCredentialCount, overlayCount }; +} - const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({ - masterKey: opts.masterKey, - passphrase: opts.passphrase, - }); - +function finalizeBackupEnvelope( + prepared: ReturnType, + keyInfo: { + key: Buffer; + kdf: 'raw-master-key' | 'scrypt'; + saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; + }, +): { + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +} { + const { inner, vaultVerified, vaultCredentialCount, overlayCount } = prepared; const plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8'); const compressed = zlib.gzipSync(plaintextJson, { level: 9 }); try { const iv = crypto.randomBytes(12); - const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); + const cipher = crypto.createCipheriv('aes-256-gcm', keyInfo.key, iv); + cipher.setAAD(BACKUP_AAD); const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); const tag = cipher.getAuthTag(); @@ -304,63 +450,115 @@ export function createBackupBundle(opts: { magic: 'GCOORD_BACKUP_V1', version: 1, alg: 'aes-256-gcm', - kdf, - ...(saltB64 ? { salt: saltB64 } : {}), + kdf: keyInfo.kdf, + ...(keyInfo.saltB64 ? { salt: keyInfo.saltB64 } : {}), + ...(keyInfo.kdfParams ? { kdfParams: keyInfo.kdfParams } : {}), iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), - createdAt, + createdAt: inner.createdAt, }; - const fileList = Object.keys(configFiles).sort(); + const fileList = Object.keys(inner.configFiles).sort(); return { serialized: `${JSON.stringify(envelope, null, 2)}\n`, envelope, summary: { valid: true, - createdAt, - kdf, + createdAt: inner.createdAt, + kdf: keyInfo.kdf, configFileCount: fileList.length, configFiles: fileList, - hasVault: vaultEnvelopeRaw !== null, + hasVault: inner.vaultEnvelopeRaw !== null, vaultVerified, vaultCredentialCount, - knownHostsCount: knownHosts.length, - alertSilenceCount: alertSilences.length, + knownHostsCount: inner.knownHosts.length, + alertSilenceCount: inner.dbMeta.alertSilences.length, overlayCount, }, }; } finally { - key.fill(0); + keyInfo.key.fill(0); plaintextJson.fill(0); compressed.fill(0); } } -export function verifyBackupBundle( - rawTextOrBuf: string | Buffer, - keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, -): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { - const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8'); - const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr)); +export function createBackupBundle(opts: { + dataDir: string; + db?: Database.Database; + masterKey?: string; + passphrase?: string; +}): { + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +} { + const keyInfo = deriveEnvelopeKeyForEncrypt({ + masterKey: opts.masterKey, + passphrase: opts.passphrase, + }); + try { + const prepared = prepareBackupInner(opts); + return finalizeBackupEnvelope(prepared, keyInfo); + } catch (err) { + keyInfo.key.fill(0); + throw err; + } +} +export async function createBackupBundleAsync(opts: { + dataDir: string; + db?: Database.Database; + masterKey?: string; + passphrase?: string; + scryptConcurrency?: number; +}): Promise<{ + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +}> { + const keyInfo = await deriveEnvelopeKeyForEncryptAsync(opts); + try { + const prepared = prepareBackupInner(opts); + return finalizeBackupEnvelope(prepared, keyInfo); + } catch (err) { + keyInfo.key.fill(0); + throw err; + } +} + +function decryptVerifiedInner( + envelope: BackupEnvelope, + key: Buffer, + keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, + maxGunzipBytes = DEFAULT_MAX_GUNZIP_BYTES, +): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { const iv = Buffer.from(envelope.iv, 'base64'); const tag = Buffer.from(envelope.tag, 'base64'); const ciphertext = Buffer.from(envelope.ciphertext, 'base64'); - if (iv.length !== 12 || tag.length !== 16) { - throw new Error('Invalid AES-256-GCM parameters inside backup envelope'); - } - - const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts); let compressed: Buffer | null = null; let plaintext: Buffer | null = null; let inner: BackupInnerPayload; try { - const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); - decipher.setAuthTag(tag); - compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); - plaintext = zlib.gunzipSync(compressed, { maxOutputLength: MAX_GUNZIP_BYTES }); + const decryptOnce = (useAad: boolean): Buffer => { + const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + if (useAad) decipher.setAAD(BACKUP_AAD); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]); + }; + + try { + compressed = decryptOnce(true); + } catch (aadErr) { + if (envelope.kdfParams) { + throw aadErr; + } + compressed = decryptOnce(false); + } + + plaintext = zlib.gunzipSync(compressed, { maxOutputLength: maxGunzipBytes }); inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8'))); } finally { key.fill(0); @@ -404,16 +602,75 @@ export function verifyBackupBundle( }; } +function parseBackupEnvelopeForVerify(rawTextOrBuf: string | Buffer): BackupEnvelope { + const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8'); + const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr)); + const iv = Buffer.from(envelope.iv, 'base64'); + const tag = Buffer.from(envelope.tag, 'base64'); + if (iv.length !== 12 || tag.length !== 16) { + throw new Error('Invalid AES-256-GCM parameters inside backup envelope'); + } + return envelope; +} + +export function verifyBackupBundle( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + maxGunzipBytes?: number; + }, +): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { + const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); + const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts); + return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); +} + +export async function verifyBackupBundleAsync( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + scryptConcurrency?: number; + maxGunzipBytes?: number; + }, +): Promise<{ summary: BackupVerificationSummary; inner: BackupInnerPayload }> { + const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); + const key = await deriveEnvelopeKeyForDecryptAsync(envelope, keyOpts); + return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); +} + export function verifyBackupSummaryOnly( rawTextOrBuf: string | Buffer, - keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + maxGunzipBytes?: number; + }, ): BackupVerificationSummary { return verifyBackupBundle(rawTextOrBuf, keyOpts).summary; } +export async function verifyBackupSummaryOnlyAsync( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + scryptConcurrency?: number; + maxGunzipBytes?: number; + }, +): Promise { + const res = await verifyBackupBundleAsync(rawTextOrBuf, keyOpts); + return res.summary; +} + function writeAtomicPrivateFile(targetPath: string, content: string): void { fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`; + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -436,7 +693,7 @@ function writeAtomicPrivateFile(targetPath: string, content: string): void { function swapConfigDirectoryAtomic(configDir: string, configFiles: Record): void { const parent = path.dirname(configDir); - const rand = crypto.randomBytes(5).toString('hex'); + const rand = crypto.randomBytes(6).toString('hex'); const stageDir = path.join(parent, `config.restore-${rand}`); const bakDir = path.join(parent, `config.bak-${rand}`); @@ -474,22 +731,10 @@ function swapConfigDirectoryAtomic(configDir: string, configFiles: Record { + const verified = await verifyBackupBundleAsync(rawTextOrBuf, { + masterKey: opts.masterKey, + passphrase: opts.passphrase, + vaultMasterKey: opts.vaultMasterKey, + scryptConcurrency: opts.scryptConcurrency, + maxGunzipBytes: opts.maxGunzipBytes, + }); + return applyVerifiedRestoreToDisk(verified, opts); +} diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 5207c67..5bbc402 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -471,6 +471,18 @@ export class VaultService { } } + dropLocalKeyFile(): void { + if (!this.keyFilePath) return; + try { + const stat = fs.lstatSync(this.keyFilePath); + if (stat.isFile() || stat.isSymbolicLink()) { + fs.unlinkSync(this.keyFilePath); + } + } catch { + // Ignore missing or unreadable key file + } + } + unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault');