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, vi } 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 }; }; 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-ai-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: {} }); 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, ); }); });