From b12df1e2d79917347f5a868e90b6d1f959c54e17 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:32:31 +0000 Subject: [PATCH] test(phase-5): add E2E suites for .gcoord.enc backup/CLI, AI assistant/redactor, and mobile bundle/themes --- tests/ai-assistant.test.ts | 414 ++++++++++++++++++++++++++++++++ tests/backup-and-cli.test.ts | 320 ++++++++++++++++++++++++ tests/mobile-and-themes.test.ts | 78 ++++++ 3 files changed, 812 insertions(+) create mode 100644 tests/ai-assistant.test.ts create mode 100644 tests/backup-and-cli.test.ts create mode 100644 tests/mobile-and-themes.test.ts diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts new file mode 100644 index 0000000..8dedbae --- /dev/null +++ b/tests/ai-assistant.test.ts @@ -0,0 +1,414 @@ +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import * as OTPAuth from 'otpauth'; +import { afterEach, describe, expect, it } from 'vitest'; +import WebSocket from 'ws'; +import { createGCoordinatorServer } from '../src/server/app.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('; '); + } +} + +async function openWs(url: string, headers: Record) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + const ws = new WebSocket(url, { headers }); + ws.on('message', (raw) => frames.push(JSON.parse(raw.toString()))); + ws.once('open', () => resolve({ ws, frames })); + ws.once('unexpected-response', (_req, res) => + reject(new Error(`WS_HTTP_${res.statusCode}`)), + ); + ws.once('error', reject); + }); +} + +async function waitFor( + fn: () => T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 25, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const val = fn(); + if (val) return val; + await new Promise((r) => setTimeout(r, intervalMs)); + } + throw new Error('Timed out waiting for condition'); +} + +interface MockAiReq { + url: string; + authorization?: string; + rawBody: string; +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guides, WS Streaming & Zod Validation', () => { + it('stays disabled by default, redacts all secrets across all 5 surfaces, streams/cancels over /ws while Vault is write-locked, and validates Zod drafts', async () => { + const recorded: MockAiReq[] = []; + let abortedSlowCount = 0; + const openSlowResponses = new Set(); + + const mockAiServer = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const rawBody = Buffer.concat(chunks).toString('utf8'); + recorded.push({ + url: req.url ?? '', + authorization: + typeof req.headers.authorization === 'string' ? req.headers.authorization : undefined, + rawBody, + }); + + const bodyObj = JSON.parse(rawBody) as { + stream?: boolean; + messages?: Array<{ role: string; content: string }>; + }; + const userText = bodyObj.messages?.map((m) => m.content).join('\n') ?? ''; + + if (!bodyObj.stream) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + choices: [{ message: { content: 'OK' } }], + }), + ); + return; + } + + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + if (userText.includes('SLOW_STREAM')) { + openSlowResponses.add(res); + res.write( + `data: ${JSON.stringify({ choices: [{ delta: { content: 'Starting slow analysis ' } }] })}\n\n`, + ); + req.on('close', () => { + openSlowResponses.delete(res); + abortedSlowCount += 1; + }); + return; + } + + const draftJson = JSON.stringify({ + id: 'ai-health-check', + name: 'AI Health Check', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log', pinToDashboard: false }, + inputs: [], + steps: [ + { + id: 'check-uptime', + type: 'exec', + target: { all: true }, + command: 'uptime', + }, + ], + }); + const chunksOut = [ + 'Here is a validated workflow draft:\n', + '```json\n', + draftJson, + '\n```', + ]; + let idx = 0; + const timer = setInterval(() => { + if (idx < chunksOut.length) { + res.write( + `data: ${JSON.stringify({ choices: [{ delta: { content: chunksOut[idx++] } }] })}\n\n`, + ); + } else { + clearInterval(timer); + res.write('data: [DONE]\n\n'); + res.end(); + } + }, 10); + }); + }); + + await new Promise((resolve) => mockAiServer.listen(0, '127.0.0.1', resolve)); + const aiAddr = mockAiServer.address() as { port: number }; + const aiBaseUrl = `http://127.0.0.1:${aiAddr.port}`; + cleanups.push(async () => { + for (const r of openSlowResponses) r.destroy(); + await new Promise((resolve) => mockAiServer.close(() => resolve())); + }); + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-ai-')); + 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 }); + }); + + const baseUrl = `http://127.0.0.1:${server.port}`; + const wsUrl = `ws://127.0.0.1:${server.port}/ws`; + 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 }; + }; + + 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-ai-password', + totpCode: totp.generate(), + secretBase32, + initialSafeMode: false, + }, + }); + csrfToken = String(boot.data.csrfToken); + + await api('/api/vault/init', { method: 'POST', body: {} }); + await api('/api/vault/credentials', { + method: 'POST', + body: { + id: 'ai-api-key', + name: 'AI LLM Key', + type: 'api-token', + token: 'sk-vault-ai-secret-55555', + }, + }); + await api('/api/vault/credentials', { + method: 'POST', + body: { + id: 'prod-sudo', + name: 'Prod Sudo', + type: 'sudo-password', + password: 'VaultSudoLeakCheck!99', + }, + }); + + // 1. Strictly opt-in: disabled by default -> 403 AI_DISABLED, zero outbound requests + const disabledChat = await api('/api/ai/chat', { + method: 'POST', + body: { + surface: 'workflows', + messages: [{ role: 'user', content: 'Draft a ping workflow' }], + }, + }); + expect(disabledChat.status).toBe(403); + expect(disabledChat.data.error).toBe('AI_DISABLED'); + expect(recorded).toHaveLength(0); + + // 2. Enable AI in settings.json referencing vaulted secretRef, then write-lock Vault + const settingsRes = await api('/api/config/file?path=settings.json'); + const settingsObj = JSON.parse(String(settingsRes.data.rawContent)); + settingsObj.ai = { + enabled: true, + baseUrl: aiBaseUrl, + model: 'qwen2.5-coder:7b', + secretRef: 'ai-api-key', + maxContextChars: 4000, + }; + expect( + ( + await api('/api/config/file', { + method: 'PUT', + body: { path: 'settings.json', content: JSON.stringify(settingsObj, null, 2) }, + }) + ).status, + ).toBe(200); + + // Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret + expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked'); + + const testEp = await api('/api/ai/test', { method: 'POST', body: {} }); + expect(testEp.status).toBe(200); + expect(testEp.data.ok).toBe(true); + expect(testEp.data.replyPreview).toBe('OK'); + expect(recorded[0]?.url).toBe('/v1/chat/completions'); + expect(recorded[0]?.authorization).toBe('Bearer sk-vault-ai-secret-55555'); + + // 3. Context preview & strict secret redaction across all 5 surfaces + const dirtyContext = [ + '-----BEGIN OPENSSH PRIVATE KEY-----', + 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAA=', + '-----END OPENSSH PRIVATE KEY-----', + 'Authorization: Bearer super-secret-jwt-token-987654', + 'DB_PASSWORD="my-inline-db-password"', + 'Detected password value: VaultSudoLeakCheck!99', + ].join('\n'); + + for (const surface of ['workflows', 'systems', 'snippets', 'logs', 'setup'] as const) { + const prev = await api('/api/ai/context-preview', { + method: 'POST', + body: { surface, contextText: dirtyContext }, + safeMode: true, + }); + expect(prev.status).toBe(200); + expect(Number(prev.data.redactedCount)).toBeGreaterThanOrEqual(4); + const sanitized = String(prev.data.sanitizedContext); + expect(sanitized).toContain('[REDACTED_PRIVATE_KEY]'); + expect(sanitized).toContain('[REDACTED_VAULT_SECRET]'); + expect(sanitized).toContain('[REDACTED_TOKEN]'); + expect(sanitized).toContain('[REDACTED_SECRET]'); + expect(sanitized).not.toContain('b3BlbnNzaC1rZXktdjE'); + expect(sanitized).not.toContain('super-secret-jwt-token-987654'); + expect(sanitized).not.toContain('my-inline-db-password'); + expect(sanitized).not.toContain('VaultSudoLeakCheck!99'); + } + + // 4. Multiplexed /ws ai: streaming (Safe Mode exempt) + draft Zod validation + const { ws, frames } = await openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }); + cleanups.push(() => ws.close()); + + recorded.length = 0; + const chatRes = await api('/api/ai/chat', { + method: 'POST', + safeMode: true, + body: { + surface: 'workflows', + messages: [{ role: 'user', content: 'Draft workflow using DB_PASSWORD=inline_pw' }], + contextText: dirtyContext, + }, + }); + expect(chatRes.status).toBe(202); + const chatId = String(chatRes.data.chatId); + ws.send(JSON.stringify({ type: 'sub', channels: [`ai:${chatId}`] })); + + await waitFor(() => + frames.some((f) => f.type === 'ai:delta' && f.chatId === chatId && f.done === true), + ); + const fullStreamText = frames + .filter((f) => f.type === 'ai:delta' && f.chatId === chatId) + .map((f) => String(f.chunk ?? '')) + .join(''); + expect(fullStreamText).toContain('ai-health-check'); + + // Outbound LLM payload must contain zero raw secrets + const sentRaw = recorded[0]?.rawBody ?? ''; + expect(sentRaw).not.toContain('VaultSudoLeakCheck!99'); + expect(sentRaw).not.toContain('super-secret-jwt-token-987654'); + expect(sentRaw).not.toContain('my-inline-db-password'); + expect(sentRaw).not.toContain('inline_pw'); + expect(sentRaw).not.toContain('b3BlbnNzaC1rZXktdjE'); + + // Draft validation: reject cyclic DAG, accept generated workflow draft + const invalidDraft = await api('/api/ai/validate-draft', { + method: 'POST', + body: { + kind: 'workflow', + jsonText: JSON.stringify({ + id: 'bad-cycle', + name: 'Cycle', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [ + { id: 'a', type: 'exec', dependsOn: ['b'], target: { all: true }, command: 'id' }, + { id: 'b', type: 'exec', dependsOn: ['a'], target: { all: true }, command: 'id' }, + ], + }), + }, + }); + expect(invalidDraft.status).toBe(200); + expect(invalidDraft.data.valid).toBe(false); + expect((invalidDraft.data.issues as unknown[]).length).toBeGreaterThan(0); + + const fenceMatch = /```json\s*\n([\s\S]*?)\n```/.exec(fullStreamText); + const validDraft = await api('/api/ai/validate-draft', { + method: 'POST', + safeMode: true, + body: { kind: 'workflow', jsonText: fenceMatch![1]! }, + }); + expect(validDraft.status).toBe(200); + expect(validDraft.data.valid).toBe(true); + expect(validDraft.data.targetPath).toBe('workflows/ai-health-check.json'); + expect((validDraft.data.diffLines as unknown[]).length).toBeGreaterThan(0); + + // 5. Cancel slow SSE generation mid-stream via WS { type: 'ai:cancel', chatId } + const slowRes = await api('/api/ai/chat', { + method: 'POST', + body: { + surface: 'logs', + messages: [{ role: 'user', content: 'SLOW_STREAM please' }], + }, + }); + const slowId = String(slowRes.data.chatId); + ws.send(JSON.stringify({ type: 'sub', channels: [`ai:${slowId}`] })); + await waitFor(() => + frames.some((f) => f.type === 'ai:delta' && f.chatId === slowId && String(f.chunk).includes('Starting slow')), + ); + ws.send(JSON.stringify({ type: 'ai:cancel', chatId: slowId })); + await waitFor( + () => + frames.some((f) => f.type === 'ai:delta' && f.chatId === slowId && f.done === true) && + abortedSlowCount >= 1, + ); + }); +}); diff --git a/tests/backup-and-cli.test.ts b/tests/backup-and-cli.test.ts new file mode 100644 index 0000000..e6e58e9 --- /dev/null +++ b/tests/backup-and-cli.test.ts @@ -0,0 +1,320 @@ +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 } 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 }; + }; + + 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, + }, + }); + csrfToken = String(boot.data.csrfToken); + + 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']); + }); +}); diff --git a/tests/mobile-and-themes.test.ts b/tests/mobile-and-themes.test.ts new file mode 100644 index 0000000..9195ab7 --- /dev/null +++ b/tests/mobile-and-themes.test.ts @@ -0,0 +1,78 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { describe, expect, it } from 'vitest'; +import { appendBoundedStreamText } from '../src/client/ts/state.js'; +import { SettingsSchema, THEME_IDS } from '../src/shared/schemas/settings.schema.js'; + +describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Optimization', () => { + it('supports all 8 theme presets in SettingsSchema and dist/public/themes.css', () => { + expect(THEME_IDS).toEqual([ + 'phosphor-green', + 'amber-term', + 'nord-dark', + 'gruvbox-dark', + 'paper-light', + 'solarized-dark', + 'tokyo-night', + 'high-contrast', + ]); + + const themesCss = fs.readFileSync(path.resolve('dist/public/themes.css'), 'utf8'); + for (const id of THEME_IDS) { + const parsed = SettingsSchema.parse({ theme: id }); + expect(parsed.theme).toBe(id); + expect(themesCss).toMatch(new RegExp(`\\[data-theme="?${id}"?\\]`)); + } + }); + + it('meets <50KB core gzipped bundle, splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => { + const publicDir = path.resolve('dist/public'); + const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js']; + let totalCoreGzip = 0; + + for (const f of coreFiles) { + const buf = fs.readFileSync(path.join(publicDir, f)); + totalCoreGzip += zlib.gzipSync(buf, { level: 9 }).length; + } + expect(totalCoreGzip).toBeLessThan(50 * 1024); + + // Heavy/optional UI stays code-split out of main.js + const mainJs = fs.readFileSync(path.join(publicDir, 'main.js'), 'utf8'); + expect(mainJs).not.toContain('ai-drawer-dialog'); + expect(mainJs).not.toContain('xterm-helper-textarea'); + + const chunks = fs.readdirSync(path.join(publicDir, 'chunks')); + expect(chunks.some((c) => c.startsWith('ai-drawer-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('terminal-view-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('workflows-view-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('alerts-view-') && c.endsWith('.js'))).toBe(true); + + for (const c of chunks) { + if (c.startsWith('terminal-view-')) continue; + const gzLen = zlib.gzipSync(fs.readFileSync(path.join(publicDir, 'chunks', c)), { + level: 9, + }).length; + expect(gzLen).toBeLessThan(20 * 1024); + } + + const manifest = JSON.parse(fs.readFileSync(path.join(publicDir, 'manifest.json'), 'utf8')) as { + display: string; + }; + expect(manifest.display).toBe('standalone'); + + const baseCss = fs.readFileSync(path.join(publicDir, 'base.css'), 'utf8'); + expect(baseCss).toContain('overscroll-behavior:contain'); + expect(baseCss).toContain('content-visibility:auto'); + expect(baseCss).toContain('min-height:44px'); + + // Long-running log stream buffer remains strictly bounded + const mockPre = { textContent: '' }; + for (let i = 0; i < 40; i++) { + appendBoundedStreamText(mockPre, `line-${i}:${'x'.repeat(200)}\n`, 1024); + } + expect(mockPre.textContent.length).toBeLessThanOrEqual(1024); + expect(mockPre.textContent).toContain('[truncated older stream output]'); + expect(mockPre.textContent).toContain('line-39:'); + }); +});