diff --git a/src/cli/gcoord.ts b/src/cli/gcoord.ts index ad4a3f8..ef67f22 100644 --- a/src/cli/gcoord.ts +++ b/src/cli/gcoord.ts @@ -2,6 +2,11 @@ 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'; @@ -9,17 +14,47 @@ function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: - rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key + 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 -Phase 5 commands (scheduled): - backup | verify-backup | restore + 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 readCurrentKey(keyFile?: string): Promise { +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(); } @@ -29,16 +64,42 @@ async function readCurrentKey(keyFile?: string): Promise { if (fs.existsSync('/run/secrets/gcoord_master_key')) { return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim(); } - const rl = readline.createInterface({ - input: process.stdin, - output: process.stderr, - }); - try { - const answer = await rl.question('Enter current 32-byte vault master key (hex or base64): '); - return answer.trim(); - } finally { - rl.close(); + 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 { @@ -89,6 +150,147 @@ async function runRotateKey(args: string[]): Promise { 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') { @@ -99,10 +301,14 @@ async function main(): Promise { if (command === 'rotate-key') { process.exit(await runRotateKey(rest)); } - - if (command === 'backup' || command === 'verify-backup' || command === 'restore') { - console.error(`Command "${command}" is scheduled for Phase 5 (.gcoord.enc portable backup).`); - process.exit(2); + 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}`); diff --git a/src/server/api/routes/backup.routes.ts b/src/server/api/routes/backup.routes.ts new file mode 100644 index 0000000..70aff8a --- /dev/null +++ b/src/server/api/routes/backup.routes.ts @@ -0,0 +1,216 @@ +import type Database from 'better-sqlite3'; +import { Router, type RequestHandler } from 'express'; +import { z } from 'zod'; +import type { ConfigManager } from '../../config/config-manager.js'; +import type { AuditService } from '../../security/audit.js'; +import type { AuthService } from '../../security/auth.js'; +import { + createBackupBundle, + restoreBackupBundle, + verifyBackupSummaryOnly, + type BackupInnerPayload, + type BackupVerificationSummary, +} from '../../security/backup.js'; +import { + enforceSafeMode, + requireAuth, + requireCsrf, +} from '../../security/guards.js'; +import type { VaultService } from '../../security/vault.js'; + +export interface BackupRouterDeps { + dataDir: string; + db: Database.Database; + authService: AuthService; + vaultService: VaultService; + configManager: ConfigManager; + auditService: AuditService; + stepUpGuard: RequestHandler; + onRestored: (info: { + summary: BackupVerificationSummary; + inner: BackupInnerPayload; + vaultKeyCandidate?: string; + }) => void | Promise; +} + +const ExportBackupBodySchema = z.object({ + passphrase: z.string().max(256).optional(), +}); + +const VerifyBackupBodySchema = z.object({ + bundleBase64: z.string().min(1), + passphrase: z.string().max(256).optional(), + masterKey: z.string().max(256).optional(), + vaultMasterKey: z.string().max(256).optional(), +}); + +export function createBackupRouter(deps: BackupRouterDeps): Router { + const router = Router(); + const { + dataDir, + db, + authService, + vaultService, + configManager, + auditService, + stepUpGuard, + onRestored, + } = deps; + + router.post( + '/export', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const parsed = ExportBackupBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const passphrase = parsed.data.passphrase?.trim() || undefined; + const masterKey = vaultService.exportMasterKeyHex() ?? undefined; + if (!passphrase && !masterKey) { + res.status(423).json({ + error: 'VAULT_LOCKED', + message: 'Vault is sealed; unlock Vault or provide a backup passphrase.', + }); + return; + } + + try { + const result = createBackupBundle({ + dataDir, + db, + masterKey, + passphrase, + }); + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `gcoordinator-backup-${stamp}.gcoord.enc`; + + auditService.log({ + action: 'backup.export', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: filename, + status: 'ok', + details: { + kdf: result.summary.kdf, + configFileCount: result.summary.configFileCount, + knownHostsCount: result.summary.knownHostsCount, + }, + }); + + res.json({ + filename, + bundleBase64: Buffer.from(result.serialized, 'utf8').toString('base64'), + summary: result.summary, + }); + } catch (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; + } + + try { + 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', + }); + } + }); + + router.post( + '/restore', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + 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 rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); + const passphrase = parsed.data.passphrase?.trim() || undefined; + const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined; + const masterKey = parsed.data.masterKey?.trim() || runtimeKey; + const vaultMasterKey = parsed.data.vaultMasterKey?.trim() || undefined; + + const wasWatching = await configManager.pauseWatcher(); + try { + const restored = restoreBackupBundle(rawBuf, { + dataDir, + db, + masterKey, + passphrase, + vaultMasterKey, + }); + + await onRestored({ + summary: restored.summary, + inner: restored.inner, + vaultKeyCandidate: vaultMasterKey || masterKey, + }); + + auditService.log({ + action: 'backup.restore', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'data', + status: 'ok', + details: { + configFileCount: restored.summary.configFileCount, + knownHostsCount: restored.summary.knownHostsCount, + vaultVerified: restored.summary.vaultVerified, + }, + }); + + res.json({ restored: true, summary: restored.summary }); + } catch (err) { + auditService.log({ + action: 'backup.restore', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'data', + status: 'error', + details: { message: err instanceof Error ? err.message : String(err) }, + }); + res.status(400).json({ + error: 'BACKUP_RESTORE_FAILED', + message: err instanceof Error ? err.message : 'Backup restore failed', + }); + } finally { + if (wasWatching) { + await configManager.resumeWatcher(); + } + } + }, + ); + + return router; +} diff --git a/src/server/app.ts b/src/server/app.ts index 54358a6..4aba4d8 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -31,6 +31,7 @@ import { CustomSystemsEngine } from './systems/systems-engine.js'; import { createAlertsRouter } from './api/routes/alerts.routes.js'; import { createAuditRouter } from './api/routes/audit.routes.js'; import { createAuthRouter } from './api/routes/auth.routes.js'; +import { createBackupRouter } from './api/routes/backup.routes.js'; import { createConfigRouter } from './api/routes/config.routes.js'; import { createServersRouter } from './api/routes/servers.routes.js'; import { createSftpRouter } from './api/routes/sftp.routes.js'; @@ -384,6 +385,39 @@ export async function createGCoordinatorServer( app.use('/api/vault', vaultRouter); app.use('/api/security', panicLockHandler); + app.use( + '/api/backup', + createBackupRouter({ + dataDir, + db, + authService, + vaultService, + configManager, + auditService, + stepUpGuard, + 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 + } + } + knownHosts.replaceAllKnownHosts(inner.knownHosts); + configManager.reloadAllFromDisk(); + sshPool.syncWithConfig(); + if (authService.isBootstrapped() && vaultService.isRuntimeReady) { + authService.syncRecovery({ snapshotReason: 'backup-restore' }); + } + wsHub.broadcastAll({ + type: 'vault:state', + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + isPanicLocked: vaultService.isPanicLocked, + }); + }, + }), + ); app.use('/api/terminal', createTerminalRouter({ authService, configManager, auditService, ptyManager })); app.use( '/api/tunnels', diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index e8a1463..14bed4c 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -133,6 +133,58 @@ export class ConfigManager { } } + get configDirPath(): string { + return this.configDir; + } + + async pauseWatcher(): Promise { + const wasWatching = this.watcher !== null; + for (const timer of this.debounceTimers.values()) { + clearTimeout(timer); + } + this.debounceTimers.clear(); + + if (this.watcher) { + await this.watcher.close(); + this.watcher = null; + } + return wasWatching; + } + + async resumeWatcher(): Promise { + if (!this.watcher) { + await this.startWatcher(); + } + } + + reloadAllFromDisk(): void { + this.servers.clear(); + this.systems.clear(); + this.workflows.clear(); + this.errors.clear(); + this.knownFiles.clear(); + this.snippets = SnippetsFileSchema.parse({}); + this.alerts = AlertsFileSchema.parse({}); + this.settings = SettingsSchema.parse({}); + + const seeded = seedDefaultConfigs(this.configDir); + const seededSet = new Set(seeded); + + const files = this.discoverAllConfigPaths(); + for (const relPath of files) { + this.knownFiles.add(relPath); + this.loadFileFromDisk(relPath, seededSet.has(relPath) ? 'seed' : 'disk', false); + } + + this.recomputeWarnings(); + this.emitChange({ + entityType: 'all', + relPath: '*', + warnings: structuredClone(this.warnings), + errors: [...this.errors.values()].map((e) => structuredClone(e)), + }); + } + onChange(listener: (event: ConfigChangeEvent) => void): () => void { this.changeListeners.add(listener); return () => { diff --git a/src/server/security/backup.ts b/src/server/security/backup.ts new file mode 100644 index 0000000..f6daf45 --- /dev/null +++ b/src/server/security/backup.ts @@ -0,0 +1,534 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import type Database from 'better-sqlite3'; +import { z } from 'zod'; +import { + AlertsFileSchema, + ServerConfigSchema, + SettingsSchema, + SnippetsFileSchema, + SystemConfigSchema, + WorkflowConfigSchema, +} from '../../shared/schemas/index.js'; +import { openDatabase } from '../db/database.js'; +import { parseMasterKey, verifyVaultEnvelopeText } from './vault.js'; + +export const BackupEnvelopeSchema = z.object({ + magic: z.literal('GCOORD_BACKUP_V1'), + version: z.literal(1), + alg: z.literal('aes-256-gcm'), + kdf: z.enum(['raw-master-key', 'scrypt']), + salt: z.string().optional(), + iv: z.string().min(1), + tag: z.string().min(1), + ciphertext: z.string().min(1), + createdAt: z.string(), +}); + +export type BackupEnvelope = z.infer; + +const KnownHostRowSchema = z.object({ + hostPort: z.string().min(1), + algorithm: z.string().min(1), + fingerprint: z.string().min(1), + trustedAt: z.number().int(), + updatedAt: z.number().int(), +}); + +const AlertSilenceRowSchema = z.object({ + id: z.string().min(1), + scopeType: z.enum(['all', 'rule', 'server', 'tag']), + targetId: z.string().min(1), + reason: z.string().nullable(), + createdAt: z.number().int(), + expiresAt: z.number().int(), +}); + +export const BackupInnerPayloadSchema = z.object({ + format: z.literal('gcoord-backup'), + version: z.literal(1), + createdAt: z.string(), + configFiles: z.record(z.string(), z.string()), + vaultEnvelopeRaw: z.string().nullable(), + knownHosts: z.array(KnownHostRowSchema).default([]), + dbMeta: z + .object({ + alertSilences: z.array(AlertSilenceRowSchema).default([]), + }) + .default({ alertSilences: [] }), +}); + +export type BackupInnerPayload = z.infer; + +export interface BackupVerificationSummary { + valid: true; + createdAt: string; + kdf: 'raw-master-key' | 'scrypt'; + configFileCount: number; + configFiles: string[]; + hasVault: boolean; + vaultVerified: boolean; + vaultCredentialCount?: number; + knownHostsCount: number; + alertSilenceCount: number; + overlayCount: number; +} + +const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; +const MAX_GUNZIP_BYTES = 32 * 1024 * 1024; +const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const; + +function validateAndParseConfigEntry( + relPath: string, + rawJson: string, +): { overlayCount: number } { + if (!relPath || relPath.includes('\\') || relPath.includes('..') || relPath.startsWith('/')) { + throw new Error(`Unsafe config path inside backup: ${relPath}`); + } + const obj = JSON.parse(rawJson); + + if (relPath === 'settings.json') { + SettingsSchema.parse(obj); + return { overlayCount: 0 }; + } + if (relPath === 'alerts.json') { + AlertsFileSchema.parse(obj); + return { overlayCount: 0 }; + } + if (relPath === 'snippets.json') { + SnippetsFileSchema.parse(obj); + return { overlayCount: 0 }; + } + + const parts = relPath.split('/'); + if (parts.length !== 2 || !parts[1]?.endsWith('.json')) { + throw new Error(`Unrecognized config path in backup: ${relPath}`); + } + const [folder, fileName] = parts; + const expectedId = fileName.slice(0, -5); + if (!SLUG_ID_RE.test(expectedId)) { + throw new Error(`Invalid config entity ID in path: ${relPath}`); + } + + if (folder === 'servers') { + const parsed = ServerConfigSchema.parse(obj); + if (parsed.id !== expectedId) { + throw new Error(`Config server id "${parsed.id}" does not match filename "${relPath}"`); + } + let overlayCount = 0; + for (const sys of parsed.systems) { + overlayCount += Object.keys(sys.itemOverrides).length; + } + return { overlayCount }; + } + if (folder === 'systems') { + const parsed = SystemConfigSchema.parse(obj); + if (parsed.id !== expectedId) { + throw new Error(`Config system id "${parsed.id}" does not match filename "${relPath}"`); + } + return { overlayCount: 0 }; + } + if (folder === 'workflows') { + const parsed = WorkflowConfigSchema.parse(obj); + if (parsed.id !== expectedId) { + throw new Error(`Config workflow id "${parsed.id}" does not match filename "${relPath}"`); + } + return { overlayCount: 0 }; + } + + throw new Error(`Unsupported config folder "${folder}" inside backup`); +} + +function collectConfigFilesFromDisk(configDir: string): Record { + const out: Record = {}; + if (!fs.existsSync(configDir)) return out; + + for (const name of ['settings.json', 'alerts.json', 'snippets.json']) { + const abs = path.join(configDir, name); + if (fs.existsSync(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; + 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()) { + out[rel] = fs.readFileSync(abs, 'utf8'); + } + } + } + return out; +} + +function deriveEnvelopeKeyForEncrypt(opts: { + masterKey?: string; + passphrase?: string; +}): { + key: Buffer; + kdf: 'raw-master-key' | 'scrypt'; + saltB64?: string; +} { + const pass = opts.passphrase?.trim(); + if (pass && pass.length > 0) { + const salt = crypto.randomBytes(16); + const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); + return { key, kdf: 'scrypt', saltB64: salt.toString('base64') }; + } + 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 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); + } + + 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: { + dataDir: string; + db?: Database.Database; + masterKey?: string; + passphrase?: string; +}): { + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +} { + const dataDir = path.resolve(opts.dataDir); + const configDir = path.join(dataDir, 'config'); + const vaultPath = path.join(dataDir, 'vault.enc'); + const dbPath = path.join(dataDir, 'gcoord.db'); + + const configFiles = collectConfigFilesFromDisk(configDir); + let overlayCount = 0; + for (const [relPath, rawJson] of Object.entries(configFiles)) { + overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; + } + + const vaultEnvelopeRaw = fs.existsSync(vaultPath) + ? fs.readFileSync(vaultPath, 'utf8') + : null; + let vaultVerified = false; + let vaultCredentialCount: number | undefined; + if (vaultEnvelopeRaw) { + const vCheck = verifyVaultEnvelopeText( + vaultEnvelopeRaw, + opts.masterKey?.trim() || undefined, + ); + vaultVerified = vCheck.decrypted; + vaultCredentialCount = vCheck.credentialCount; + } + + let localDb: Database.Database | null = null; + const db = + opts.db ?? + (fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null); + + let knownHosts: Array> = []; + let alertSilences: Array> = []; + try { + 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', + ) + .all() as Array>; + + const nowMs = Date.now(); + alertSilences = db + .prepare( + `SELECT id, scope_type AS scopeType, target_id AS targetId, reason, + created_at AS createdAt, expires_at AS expiresAt + FROM alert_silences + WHERE expires_at > ? + ORDER BY created_at DESC`, + ) + .all(nowMs) as Array>; + } + } finally { + localDb?.close(); + } + + const createdAt = new Date().toISOString(); + const inner: BackupInnerPayload = { + format: 'gcoord-backup', + version: 1, + createdAt, + configFiles, + vaultEnvelopeRaw, + knownHosts, + dbMeta: { alertSilences }, + }; + + const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({ + masterKey: opts.masterKey, + passphrase: opts.passphrase, + }); + + 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 ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); + const tag = cipher.getAuthTag(); + + const envelope: BackupEnvelope = { + magic: 'GCOORD_BACKUP_V1', + version: 1, + alg: 'aes-256-gcm', + kdf, + ...(saltB64 ? { salt: saltB64 } : {}), + iv: iv.toString('base64'), + tag: tag.toString('base64'), + ciphertext: ciphertext.toString('base64'), + createdAt, + }; + + const fileList = Object.keys(configFiles).sort(); + return { + serialized: `${JSON.stringify(envelope, null, 2)}\n`, + envelope, + summary: { + valid: true, + createdAt, + kdf, + configFileCount: fileList.length, + configFiles: fileList, + hasVault: vaultEnvelopeRaw !== null, + vaultVerified, + vaultCredentialCount, + knownHostsCount: knownHosts.length, + alertSilenceCount: alertSilences.length, + overlayCount, + }, + }; + } finally { + 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)); + + 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 }); + inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8'))); + } finally { + key.fill(0); + compressed?.fill(0); + plaintext?.fill(0); + } + + let overlayCount = 0; + for (const [relPath, rawJson] of Object.entries(inner.configFiles)) { + overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; + } + + let vaultVerified = false; + let vaultCredentialCount: number | undefined; + if (inner.vaultEnvelopeRaw !== null) { + const effectiveVaultKey = keyOpts.vaultMasterKey?.trim() || keyOpts.masterKey?.trim(); + const res = verifyVaultEnvelopeText(inner.vaultEnvelopeRaw, effectiveVaultKey || undefined); + vaultVerified = res.decrypted; + vaultCredentialCount = res.credentialCount; + if (envelope.kdf === 'raw-master-key' && !keyOpts.vaultMasterKey && !vaultVerified) { + throw new Error('Vault integrity check failed with master key'); + } + } + + const configFiles = Object.keys(inner.configFiles).sort(); + return { + inner, + summary: { + valid: true, + createdAt: inner.createdAt, + kdf: envelope.kdf, + configFileCount: configFiles.length, + configFiles, + hasVault: inner.vaultEnvelopeRaw !== null, + vaultVerified, + vaultCredentialCount, + knownHostsCount: inner.knownHosts.length, + alertSilenceCount: inner.dbMeta.alertSilences.length, + overlayCount, + }, + }; +} + +export function verifyBackupSummaryOnly( + rawTextOrBuf: string | Buffer, + keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, +): BackupVerificationSummary { + return verifyBackupBundle(rawTextOrBuf, keyOpts).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 fd = fs.openSync(tmpPath, 'w', 0o600); + try { + fs.writeFileSync(fd, content, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + try { + fs.renameSync(tmpPath, targetPath); + fs.chmodSync(targetPath, 0o600); + } catch (err) { + try { + fs.unlinkSync(tmpPath); + } catch { + // Ignore cleanup error + } + throw err; + } +} + +function swapConfigDirectoryAtomic(configDir: string, configFiles: Record): void { + const parent = path.dirname(configDir); + const rand = crypto.randomBytes(5).toString('hex'); + const stageDir = path.join(parent, `config.restore-${rand}`); + const bakDir = path.join(parent, `config.bak-${rand}`); + + fs.mkdirSync(stageDir, { recursive: true, mode: 0o700 }); + try { + for (const [relPath, content] of Object.entries(configFiles)) { + const dest = path.resolve(stageDir, relPath); + if (!dest.startsWith(`${stageDir}${path.sep}`)) { + throw new Error(`Unsafe restore target path: ${relPath}`); + } + fs.mkdirSync(path.dirname(dest), { recursive: true, mode: 0o700 }); + fs.writeFileSync(dest, content, { encoding: 'utf8', mode: 0o600 }); + } + + const hadExisting = fs.existsSync(configDir); + if (hadExisting) { + fs.renameSync(configDir, bakDir); + } + try { + fs.renameSync(stageDir, configDir); + } catch (err) { + if (hadExisting && fs.existsSync(bakDir) && !fs.existsSync(configDir)) { + fs.renameSync(bakDir, configDir); + } + throw err; + } + if (hadExisting && fs.existsSync(bakDir)) { + fs.rmSync(bakDir, { recursive: true, force: true }); + } + } catch (err) { + if (fs.existsSync(stageDir)) { + fs.rmSync(stageDir, { recursive: true, force: true }); + } + throw err; + } +} + +export function restoreBackupBundle( + rawTextOrBuf: string | Buffer, + opts: { + dataDir: string; + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + db?: Database.Database; + }, +): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { + const verified = verifyBackupBundle(rawTextOrBuf, { + masterKey: opts.masterKey, + passphrase: opts.passphrase, + vaultMasterKey: opts.vaultMasterKey, + }); + + const dataDir = path.resolve(opts.dataDir); + fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); + + swapConfigDirectoryAtomic(path.join(dataDir, 'config'), verified.inner.configFiles); + + const vaultPath = path.join(dataDir, 'vault.enc'); + if (verified.inner.vaultEnvelopeRaw !== null) { + writeAtomicPrivateFile(vaultPath, verified.inner.vaultEnvelopeRaw); + if (verified.summary.vaultVerified) { + fs.rmSync(`${vaultPath}.panic-locked`, { force: true }); + } + } + + let localDb: Database.Database | null = null; + const db = opts.db ?? (localDb = openDatabase(path.join(dataDir, 'gcoord.db'))); + try { + const tx = db.transaction(() => { + db.prepare('DELETE FROM known_hosts').run(); + const insHost = db.prepare( + `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ); + for (const h of verified.inner.knownHosts) { + insHost.run(h.hostPort, h.algorithm, h.fingerprint, h.trustedAt, h.updatedAt); + } + + db.prepare('DELETE FROM alert_silences').run(); + const insSilence = db.prepare( + `INSERT INTO alert_silences (id, scope_type, target_id, reason, created_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ); + for (const s of verified.inner.dbMeta.alertSilences) { + insSilence.run(s.id, s.scopeType, s.targetId, s.reason, s.createdAt, s.expiresAt); + } + }); + tx(); + } finally { + localDb?.close(); + } + + return verified; +} diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 82794d5..26811a3 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -12,7 +12,7 @@ import { } from '../../shared/schemas/vault.schema.js'; import type { VaultState } from '../../shared/ws-protocol.js'; -const VaultEnvelopeSchema = z.object({ +export const VaultEnvelopeSchema = z.object({ version: z.literal(1), alg: z.literal('aes-256-gcm'), iv: z.string().min(1), @@ -21,7 +21,7 @@ const VaultEnvelopeSchema = z.object({ updatedAt: z.string(), }); -type VaultEnvelope = z.infer; +export type VaultEnvelope = z.infer; export function parseMasterKey(raw: string): Buffer { const trimmed = raw.trim(); @@ -77,6 +77,37 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload { } } +export function verifyVaultEnvelopeText( + rawText: string, + masterKeyInput?: string, +): { + envelopeValid: boolean; + decrypted: boolean; + credentialCount?: number; + updatedAt: string; +} { + const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); + if (!masterKeyInput || !masterKeyInput.trim()) { + return { + envelopeValid: true, + decrypted: false, + updatedAt: envelope.updatedAt, + }; + } + const keyBuf = parseMasterKey(masterKeyInput); + try { + const payload = decryptEnvelope(envelope, keyBuf); + return { + envelopeValid: true, + decrypted: true, + credentialCount: Object.keys(payload.credentials).length, + updatedAt: envelope.updatedAt, + }; + } finally { + keyBuf.fill(0); + } +} + export function computeOpenSshFingerprint(publicKeyLine: string): string { const parsed = ssh2.utils.parseKey(publicKeyLine.trim()); if (parsed instanceof Error) { @@ -375,6 +406,40 @@ export class VaultService { this.writeUnlocked = false; } + reloadFromDisk(masterKeyInput?: string): boolean { + if (!fs.existsSync(this.vaultFilePath)) { + this.credentials.clear(); + return false; + } + + let candidateKey: Buffer | null = null; + if (masterKeyInput && masterKeyInput.trim().length > 0) { + candidateKey = parseMasterKey(masterKeyInput); + } else if (this.masterKey !== null) { + candidateKey = Buffer.from(this.masterKey); + } else { + return false; + } + + try { + const rawText = fs.readFileSync(this.vaultFilePath, 'utf8'); + const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); + const payload = decryptEnvelope(envelope, candidateKey); + const wasUnlocked = this.writeUnlocked; + this.zeroizeMasterKey(); + this.masterKey = candidateKey; + this.credentials = new Map(Object.entries(payload.credentials)); + this.writeUnlocked = wasUnlocked; + this.autoInitializedEmpty = false; + this.setPanicLockMarker(false); + this.persistKeyFileIfConfigured(candidateKey); + return true; + } catch (err) { + candidateKey.fill(0); + throw err; + } + } + panicLock(): void { this.zeroizeMasterKey(); this.credentials.clear(); diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index a3148f3..0fc21ee 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -243,6 +243,35 @@ export class KnownHostsService { .all() as KnownHostRecord[]; } + replaceAllKnownHosts( + records: Array< + Pick & + Partial> + >, + ): void { + const now = Date.now(); + const tx = this.db.transaction(() => { + this.db.prepare('DELETE FROM known_hosts').run(); + const ins = this.db.prepare( + `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ); + for (const r of records) { + ins.run( + r.hostPort, + r.algorithm, + r.fingerprint, + r.trustedAt ?? now, + r.updatedAt ?? now, + ); + } + }); + tx(); + this.pendingTofu.clear(); + this.pendingMismatches.clear(); + this.emitChange(); + } + deleteKnownHost(hostPort: string): boolean { const res = this.db .prepare('DELETE FROM known_hosts WHERE host_port = ?')