import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; 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, type GCoordinatorInstance } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.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 setupServerWithSsh() { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-pty-sftp-')); 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 } = {}, ) => { 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; 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(() => ({})); return { status: res.status, data: data as Record }; }; 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: 'phase3-test-password-1', 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: 'p3-key', name: 'Phase 3 Key' }, }); const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); const mock = new MockSshServer({ username: 'ops', os: 'Linux', authorizedKeys: [pubKey], }); const sshPort = await mock.start(); cleanups.push(() => mock.close()); await api('/api/servers', { method: 'POST', body: { id: 's1', name: 'Server 1', host: '127.0.0.1', port: sshPort, username: 'ops', credentialId: 'p3-key', pollIntervalSec: 300, }, }); await api('/api/servers/s1/reconnect', { method: 'POST' }); await api('/api/servers/s1/tofu/approve', { method: 'POST', body: { fingerprint: mock.hostFingerprint }, }); return { server, baseUrl, wsUrl, jar, csrfToken, api, mock }; } afterEach(async () => { while (cleanups.length > 0) { await cleanups.pop()!(); } }); describe('Phase 3: Persistent PTYManager & SFTP File Manager + Inline Diff', () => { it('streams PTY I/O over WS, resizes window, replays scrollback on reconnect, exports plain/ANSI, and enforces Safe Mode & Panic Lock', async () => { const ctx = await setupServerWithSsh(); // Open persistent PTY session const created = await ctx.api('/api/terminal/sessions', { method: 'POST', body: { serverId: 's1', cols: 100, rows: 30 }, }); expect(created.status).toBe(201); const session = created.data.session as { sessionId: string }; expect(ctx.mock.lastPtySize).toEqual({ cols: 100, rows: 30 }); const { ws: ws1, frames: f1 } = await openWs(ctx.wsUrl, { Cookie: ctx.jar.header(), Host: `127.0.0.1:${ctx.server.port}`, Origin: ctx.baseUrl, }); ws1.send(JSON.stringify({ type: 'sub', channels: [`pty:${session.sessionId}`] })); ws1.send( JSON.stringify({ type: 'pty:input', sessionId: session.sessionId, data: 'echo phase3-pty-ok\r', }), ); ws1.send( JSON.stringify({ type: 'pty:resize', sessionId: session.sessionId, cols: 132, rows: 42, }), ); await new Promise((r) => setTimeout(r, 100)); expect(ctx.mock.lastPtySize).toEqual({ cols: 132, rows: 42 }); const combined1 = f1 .filter((f) => f.type === 'pty:output' && f.sessionId === session.sessionId) .map((f) => String(f.data)) .join(''); expect(combined1).toContain('phase3-pty-ok'); // Disconnect WS 1, reconnect WS 2 -> receives replay: true with preserved scrollback ws1.close(); const { ws: ws2, frames: f2 } = await openWs(ctx.wsUrl, { Cookie: ctx.jar.header(), Host: `127.0.0.1:${ctx.server.port}`, Origin: ctx.baseUrl, }); ws2.send(JSON.stringify({ type: 'sub', channels: [`pty:${session.sessionId}`] })); await new Promise((r) => setTimeout(r, 80)); const replayFrames = f2.filter( (f) => f.type === 'pty:output' && f.replay === true, ); expect(replayFrames.length).toBeGreaterThan(0); expect(String(replayFrames[0]!.data)).toContain('phase3-pty-ok'); // Export plain (ANSI stripped) vs ANSI const plainRes = await fetch( `${ctx.baseUrl}/api/terminal/sessions/${session.sessionId}/export?format=plain`, { headers: { Cookie: ctx.jar.header() } }, ); const plainText = await plainRes.text(); expect(plainRes.status).toBe(200); expect(plainText).toContain('phase3-pty-ok'); expect(plainText).not.toContain('\x1b['); const ansiRes = await fetch( `${ctx.baseUrl}/api/terminal/sessions/${session.sessionId}/export?format=ansi`, { headers: { Cookie: ctx.jar.header() } }, ); const ansiText = await ansiRes.text(); expect(ansiText).toContain('\x1b[32m'); // Safe Mode blocks new PTY creation & WS pty:input await ctx.api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } }); const blockedCreate = await ctx.api('/api/terminal/sessions', { method: 'POST', body: { serverId: 's1' }, }); expect(blockedCreate.status).toBe(423); ws2.send( JSON.stringify({ type: 'pty:input', sessionId: session.sessionId, data: 'echo blocked\r', }), ); await new Promise((r) => setTimeout(r, 60)); expect(f2.some((f) => f.type === 'error' && f.code === 'SAFE_MODE_ACTIVE')).toBe(true); // Panic Lock closes PTYs and wipes scrollback await ctx.api('/api/security/panic-lock', { method: 'POST' }); expect(ctx.server.ptyManager.listSessions()).toHaveLength(0); expect(ctx.server.ptyManager.getScrollback(session.sessionId)).toBeNull(); }); it('performs SFTP list, streaming upload/download, mkdir, rename, chmod, atomic text edit with 409 conflict guard, and streamed folder archive', async () => { const ctx = await setupServerWithSsh(); // Streaming binary upload & exact download match const binPayload = Buffer.from([0x00, 0x01, 0x7f, 0xff, 0x0a, 0x42, 0x99]); const upRes = await fetch( `${ctx.baseUrl}/api/servers/s1/sftp/upload?path=${encodeURIComponent('/bin.dat')}`, { method: 'POST', headers: { Cookie: ctx.jar.header(), 'X-CSRF-Token': ctx.csrfToken, 'Content-Type': 'application/octet-stream', }, body: binPayload, }, ); expect(upRes.status).toBe(201); const dlRes = await fetch( `${ctx.baseUrl}/api/servers/s1/sftp/download?path=${encodeURIComponent('/bin.dat')}`, { headers: { Cookie: ctx.jar.header() } }, ); expect(dlRes.status).toBe(200); const dlBuf = Buffer.from(await dlRes.arrayBuffer()); expect(dlBuf.equals(binPayload)).toBe(true); // Binary file rejected cleanly from text inline editor const binEditRes = await ctx.api( `/api/servers/s1/sftp/text?path=${encodeURIComponent('/bin.dat')}`, ); expect(binEditRes.status).toBe(400); expect(binEditRes.data.error).toBe('BINARY_FILE_NOT_EDITABLE'); // Mkdir, upload text, chmod, rename, list expect( ( await ctx.api('/api/servers/s1/sftp/mkdir', { method: 'POST', body: { path: '/bundle' }, }) ).status, ).toBe(201); await fetch( `${ctx.baseUrl}/api/servers/s1/sftp/upload?path=${encodeURIComponent('/bundle/raw.conf')}`, { method: 'POST', headers: { Cookie: ctx.jar.header(), 'X-CSRF-Token': ctx.csrfToken, 'Content-Type': 'application/octet-stream', }, body: 'port=8080\n', }, ); expect( ( await ctx.api('/api/servers/s1/sftp/chmod', { method: 'POST', body: { path: '/bundle/raw.conf', mode: '0600' }, }) ).status, ).toBe(200); expect( ( await ctx.api('/api/servers/s1/sftp/rename', { method: 'POST', body: { fromPath: '/bundle/raw.conf', toPath: '/bundle/app.conf' }, }) ).status, ).toBe(200); const list = await ctx.api('/api/servers/s1/sftp/list?path=%2Fbundle'); expect(list.status).toBe(200); const entries = list.data.entries as Array<{ name: string; permissionsOctal: string }>; expect(entries.some((e) => e.name === 'app.conf' && e.permissionsOctal === '0600')).toBe( true, ); // Inline text read + optimistic SHA-256 409 CONFLICT check + atomic write const readText = await ctx.api('/api/servers/s1/sftp/text?path=%2Fbundle%2Fapp.conf'); expect(readText.status).toBe(200); const fileObj = readText.data.file as { content: string; sha256: string }; expect(fileObj.content).toBe('port=8080\n'); const conflictPut = await ctx.api('/api/servers/s1/sftp/text', { method: 'PUT', body: { path: '/bundle/app.conf', content: 'port=9090\n', expectedSha256: 'deadbeef', }, }); expect(conflictPut.status).toBe(409); expect(conflictPut.data.error).toBe('CONFLICT'); const okPut = await ctx.api('/api/servers/s1/sftp/text', { method: 'PUT', body: { path: '/bundle/app.conf', content: 'port=9090\n', expectedSha256: fileObj.sha256, }, }); expect(okPut.status).toBe(200); // Streamed directory .tar.gz download -> verify archive lists bundle/app.conf const archRes = await fetch( `${ctx.baseUrl}/api/servers/s1/sftp/archive?path=${encodeURIComponent('/bundle')}&format=tar.gz`, { headers: { Cookie: ctx.jar.header() } }, ); expect(archRes.status).toBe(200); expect(archRes.headers.get('x-archive-format')).toBe('tar.gz'); const archBuf = Buffer.from(await archRes.arrayBuffer()); const tmpTgz = path.join(os.tmpdir(), `gcoord-arch-${Date.now()}.tar.gz`); fs.writeFileSync(tmpTgz, archBuf); try { const tarList = execFileSync('tar', ['-tzf', tmpTgz], { encoding: 'utf8' }); expect(tarList).toContain('bundle/app.conf'); } finally { fs.rmSync(tmpTgz, { force: true }); } // Recursive delete const delRes = await ctx.api('/api/servers/s1/sftp/entry?path=%2Fbundle&recursive=1', { method: 'DELETE', }); expect(delRes.status).toBe(200); expect(fs.existsSync(path.join(ctx.mock.sftpRootDir, 'bundle'))).toBe(false); }); });