import { execFile } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { promisify } from 'node:util'; import * as OTPAuth from 'otpauth'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { createGCoordinatorServer } from '../src/server/app.js'; import { openDatabase } from '../src/server/db/database.js'; import { VaultService } from '../src/server/security/vault.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; const execFileAsync = promisify(execFile); const CLI_PATH = path.resolve('dist/cli/gcoord.js'); const cleanups: Array<() => Promise | void> = []; class CookieJar { private cookies = new Map(); updateFrom(res: Response): void { const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; for (const line of rawList) { const first = line.split(';')[0] ?? ''; const eq = first.indexOf('='); if (eq > 0) { const name = first.slice(0, eq).trim(); const val = first.slice(eq + 1).trim(); if (val === '') this.cookies.delete(name); else this.cookies.set(name, val); } } } header(): string { return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); } } afterEach(async () => { while (cleanups.length > 0) { await cleanups.pop()!(); } }); describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord CLI)', () => { it('creates, verifies, and restores AES-256-GCM bundles across master-key API and scrypt CLI modes', async () => { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-bkp-src-')); const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-bkp-work-')); const freshRestoreDir = path.join(workDir, 'restored-data'); const server = await createGCoordinatorServer({ dataDir, port: 0, host: '127.0.0.1', publicDir: path.resolve('dist/public'), watchConfig: false, }); cleanups.push(async () => { await server.close(); fs.rmSync(dataDir, { recursive: true, force: true }); fs.rmSync(workDir, { recursive: true, force: true }); }); const baseUrl = `http://127.0.0.1:${server.port}`; const jar = new CookieJar(); let csrfToken = ''; const api = async ( pathname: string, opts: { method?: string; body?: unknown; safeMode?: boolean } = {}, ) => { const headers: Record = {}; if (jar.header()) headers.Cookie = jar.header(); if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; if (csrfToken) headers['X-CSRF-Token'] = csrfToken; if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1'; const res = await fetch(`${baseUrl}${pathname}`, { method: opts.method ?? 'GET', headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, }); jar.updateFrom(res); const data = (await res.json().catch(() => ({}))) as Record; return { status: res.status, data }; }; vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ issuer: 'GCoordinator', label: 'admin', algorithm: 'SHA1', digits: 6, period: 30, secret: OTPAuth.Secret.fromBase32(secretBase32), }); const boot = await api('/api/auth/bootstrap', { method: 'POST', body: { username: 'admin', password: 'phase5-backup-password', totpCode: totp.generate(), secretBase32, initialSafeMode: false, }, }); vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { method: 'POST', body: { id: 'bkp-ssh-key', name: 'Backup SSH Key' }, }); const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); await api('/api/vault/credentials', { method: 'POST', body: { id: 'bkp-api-tok', name: 'Backup API Token', type: 'api-token', token: 'tok-restore-999' }, }); const mock = new MockSshServer({ username: 'ops', os: 'Linux', authorizedKeys: [pubKey], }); const sshPort = await mock.start(); cleanups.push(() => mock.close()); // Register server with itemOverrides activeFiles overlay and approve TOFU -> populates config + known_hosts const reg = await api('/api/servers', { method: 'POST', body: { id: 'app1', name: 'App Backup Server', host: '127.0.0.1', port: sshPort, username: 'ops', credentialId: 'bkp-ssh-key', pollIntervalSec: 3600, systems: [ { systemId: 'docker-compose', enabled: true, params: { rootDirs: ['/opt/stacks'] }, itemOverrides: { webapp: { activeFiles: ['compose.yml', 'compose.prod.yml'] }, }, }, ], }, }); expect(reg.status).toBe(201); await api('/api/servers/app1/reconnect', { method: 'POST' }); const approve = await api('/api/servers/app1/tofu/approve', { method: 'POST', body: { fingerprint: mock.hostFingerprint }, }); expect(approve.status).toBe(200); // Add active alert silence const silRes = await api('/api/alerts/silences', { method: 'POST', body: { scopeType: 'server', targetId: 'app1', durationMinutes: 120, reason: 'Backup test' }, }); expect(silRes.status).toBe(201); // Checkpoint WAL so external CLI sees all SQLite rows cleanly server.db.pragma('wal_checkpoint(TRUNCATE)'); // Re-lock Vault for modifications -> Master-Key export still works via runtime key const relock = await api('/api/vault/lock', { method: 'POST' }); expect(relock.status).toBe(200); expect(relock.data.state).toBe('locked'); expect(relock.data.runtimeReady).toBe(true); // Safe Mode blocks export/restore (423), exempts verify (200) expect( (await api('/api/backup/export', { method: 'POST', body: {}, safeMode: true })).status, ).toBe(423); const exported = await api('/api/backup/export', { method: 'POST', body: {} }); expect(exported.status).toBe(200); const masterBundleB64 = String(exported.data.bundleBase64); const expSummary = exported.data.summary as { valid: boolean; kdf: string; vaultVerified: boolean; knownHostsCount: number; alertSilenceCount: number; overlayCount: number; }; expect(expSummary.valid).toBe(true); expect(expSummary.kdf).toBe('raw-master-key'); expect(expSummary.vaultVerified).toBe(true); expect(expSummary.knownHostsCount).toBe(1); expect(expSummary.alertSilenceCount).toBe(1); expect(expSummary.overlayCount).toBe(1); const verifySafe = await api('/api/backup/verify', { method: 'POST', body: { bundleBase64: masterBundleB64 }, safeMode: true, }); expect(verifySafe.status).toBe(200); expect((verifySafe.data.summary as { valid: boolean }).valid).toBe(true); // --- CLI Passphrase (scrypt) Backup, Verify-Backup, Tamper Reject & Cold Restore --- const passFile = path.join(workDir, 'backup.pass'); fs.writeFileSync(passFile, 'portable-backup-passphrase-2026!\n', { mode: 0o600 }); const passBundlePath = path.join(workDir, 'portable.gcoord.enc'); const vaultKeyPath = path.join(dataDir, 'vault.key'); const bkpOut = await execFileAsync(process.execPath, [ CLI_PATH, 'backup', '--data-dir', dataDir, '--out', passBundlePath, '--passphrase-file', passFile, ]); expect(bkpOut.stdout).toContain('kdf=scrypt'); expect(fs.existsSync(passBundlePath)).toBe(true); const verOut = await execFileAsync(process.execPath, [ CLI_PATH, 'verify-backup', passBundlePath, '--passphrase-file', passFile, '--vault-key-file', vaultKeyPath, '--json', ]); const cliSummary = JSON.parse(verOut.stdout) as typeof expSummary; expect(cliSummary.valid).toBe(true); expect(cliSummary.kdf).toBe('scrypt'); expect(cliSummary.vaultVerified).toBe(true); expect(cliSummary.overlayCount).toBe(1); // Tamper 1 character in GCM tag -> must fail verification const tamperedPath = path.join(workDir, 'tampered.gcoord.enc'); const envObj = JSON.parse(fs.readFileSync(passBundlePath, 'utf8')) as { tag: string; [k: string]: unknown; }; const origTag = Buffer.from(envObj.tag, 'base64'); origTag[0] = origTag[0]! ^ 0xff; envObj.tag = origTag.toString('base64'); fs.writeFileSync(tamperedPath, JSON.stringify(envObj), 'utf8'); await expect( execFileAsync(process.execPath, [ CLI_PATH, 'verify-backup', tamperedPath, '--passphrase-file', passFile, ]), ).rejects.toThrow(); // Restore scrypt bundle into an empty fresh directory const restOut = await execFileAsync(process.execPath, [ CLI_PATH, 'restore', passBundlePath, '--data-dir', freshRestoreDir, '--passphrase-file', passFile, ]); expect(restOut.stdout).toContain('Restored GCoordinator state'); const restoredSrvJson = JSON.parse( fs.readFileSync(path.join(freshRestoreDir, 'config', 'servers', 'app1.json'), 'utf8'), ) as { systems: Array<{ itemOverrides: Record }> }; expect(restoredSrvJson.systems[0]?.itemOverrides.webapp?.activeFiles).toEqual([ 'compose.yml', 'compose.prod.yml', ]); const restoredVault = new VaultService(path.join(freshRestoreDir, 'vault.enc')); restoredVault.unlock(fs.readFileSync(vaultKeyPath, 'utf8').trim()); expect(restoredVault.getSecret('bkp-api-tok')).toMatchObject({ token: 'tok-restore-999' }); const restoredDb = openDatabase(path.join(freshRestoreDir, 'gcoord.db')); try { const hosts = restoredDb.prepare('SELECT host_port, fingerprint FROM known_hosts').all() as Array<{ host_port: string; fingerprint: string; }>; expect(hosts).toHaveLength(1); expect(hosts[0]?.fingerprint).toBe(mock.hostFingerprint); const sils = restoredDb.prepare('SELECT target_id FROM alert_silences').all() as Array<{ target_id: string; }>; expect(sils.some((s) => s.target_id === 'app1')).toBe(true); } finally { restoredDb.close(); } // --- Live API Restore hot-reloads ConfigManager & KnownHosts --- expect((await api('/api/servers/app1', { method: 'DELETE' })).status).toBe(200); expect((await api('/api/servers')).data.servers).toHaveLength(0); expect( (await api('/api/backup/restore', { method: 'POST', body: { bundleBase64: masterBundleB64 }, safeMode: true })).status, ).toBe(423); const liveRestore = await api('/api/backup/restore', { method: 'POST', body: { bundleBase64: masterBundleB64 }, }); expect(liveRestore.status).toBe(200); expect(liveRestore.data.restored).toBe(true); const serversAfter = (await api('/api/servers')).data.servers as Array<{ config: { id: string } }>; expect(serversAfter.map((s) => s.config.id)).toEqual(['app1']); }); });