diff --git a/tests/custom-systems.test.ts b/tests/custom-systems.test.ts new file mode 100644 index 0000000..f587d67 --- /dev/null +++ b/tests/custom-systems.test.ts @@ -0,0 +1,368 @@ +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 } 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); + }); +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & Debug Shell)', () => { + it('runs folder-scan + command discovery, multi-file activeFiles[], TTL caching + invalidation, oneshot/stream/interactive actions, and sudo systems', async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-systems-')); + const mockHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-home-')); + const webappDir = path.join(mockHome, 'My Stacks', 'webapp'); + fs.mkdirSync(webappDir, { recursive: true }); + fs.writeFileSync(path.join(webappDir, 'compose.yml'), 'services:\n web:\n image: nginx\n'); + fs.writeFileSync( + path.join(webappDir, 'compose.prod.yml'), + 'services:\n worker:\n image: alpine\n', + ); + fs.writeFileSync(path.join(webappDir, '.env'), 'PORT=8080\n'); + + let workerHealthy = false; + let composeStatusCalls = 0; + const seenComposeFlags: string[] = []; + + 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(mockHome, { 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-systems-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: 'sys-key', name: 'Sys Key' }, + }); + const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); + + await api('/api/vault/credentials', { + method: 'POST', + body: { + id: 'sys-sudo', + name: 'Sys Sudo', + type: 'sudo-password', + password: 'sudo-secret-pw', + }, + }); + + const mock = new MockSshServer({ + username: 'ops', + os: 'Linux', + sudoPassword: 'sudo-secret-pw', + authorizedKeys: [pubKey], + onExec: (cmd) => { + // Real POSIX /bin/sh execution of generated folder-scan discovery script against mockHome + if (cmd.includes('printf \'D\\t%s\\n\' "$d"') || cmd.includes("printf 'D\\t%s\\n'")) { + const out = execFileSync('/bin/sh', ['-c', cmd], { + env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: mockHome }, + encoding: 'utf8', + }); + return { stdout: out, exitCode: 0 }; + } + + // Compose status check + if (cmd.includes('ps --all --format json')) { + composeStatusCalls += 1; + const m = /GCOORD_COMPOSE_FILES='([^']*)'/.exec(cmd); + if (m?.[1]) seenComposeFlags.push(m[1]); + const rows = [ + JSON.stringify({ Service: 'web', State: 'running' }), + JSON.stringify({ Service: 'worker', State: workerHealthy ? 'running' : 'exited' }), + ]; + return { stdout: `${rows.join('\n')}\n`, exitCode: 0 }; + } + + // Compose oneshot up + if (cmd.includes(' up -d') && !cmd.includes('pull')) { + workerHealthy = true; + return { stdout: 'Container webapp-worker Started\n', exitCode: 0 }; + } + + // Compose streamed logs + if (cmd.includes(' logs -f')) { + return { + stdout: '2026-11-26 webapp log line 1\n2026-11-26 webapp log line 2\n', + exitCode: 0, + }; + } + + // Compose interactive debug-shell + if (cmd.includes(' exec "$GCOORD_SUBITEM"')) { + return { stdout: 'root@webapp-web:/app# \n', exitCode: 0 }; + } + + // systemd discovery & status & sudo action + if (cmd.includes('systemctl list-units')) { + expect(cmd).toContain("GCOORD_PARAM_UNITFILTER='nginx'"); + return { stdout: 'nginx.service\n', exitCode: 0 }; + } + if (cmd.includes('systemctl show')) { + return { + stdout: JSON.stringify({ + Id: 'nginx.service', + LoadState: 'loaded', + ActiveState: 'active', + SubState: 'running', + }), + exitCode: 0, + }; + } + if (cmd.includes('systemctl restart')) { + return { stdout: 'restarted nginx.service\n', exitCode: 0 }; + } + + return null; + }, + }); + const sshPort = await mock.start(); + cleanups.push(() => mock.close()); + + await api('/api/servers', { + method: 'POST', + body: { + id: 'app1', + name: 'App 1', + host: '127.0.0.1', + port: sshPort, + username: 'ops', + credentialId: 'sys-key', + sudoCredentialId: 'sys-sudo', + pollIntervalSec: 300, + }, + }); + await api('/api/servers/app1/reconnect', { method: 'POST' }); + await api('/api/servers/app1/tofu/approve', { + method: 'POST', + body: { fingerprint: mock.hostFingerprint }, + }); + + // Attach docker-compose with space in rootDir path + systemd with filter + expect( + ( + await api('/api/systems/docker-compose/servers/app1/attach', { + method: 'PUT', + body: { params: { rootDirs: ['~/My Stacks'] } }, + }) + ).status, + ).toBe(200); + expect( + ( + await api('/api/systems/systemd/servers/app1/attach', { + method: 'PUT', + body: { params: { unitFilter: 'nginx' } }, + }) + ).status, + ).toBe(200); + + // 1. Discover compose stacks across space-containing dir + verify TTL caching + const sys1 = await api('/api/systems/docker-compose'); + expect(sys1.status).toBe(200); + const snap1 = ( + sys1.data.snapshots as Array<{ + cached: boolean; + systemHealth: string; + items: Array<{ + name: string; + dir: string; + activeFiles: string[]; + selectableFiles: string[]; + editableFiles: string[]; + status: { health: string; subItems: Array<{ name: string; health: string }> }; + }>; + }> + )[0]!; + expect(snap1.cached).toBe(false); + expect(snap1.systemHealth).toBe('down'); + expect(snap1.items).toHaveLength(1); + const item = snap1.items[0]!; + expect(item.name).toBe('webapp'); + expect(item.dir).toBe(webappDir); + expect(item.selectableFiles).toContain('compose.prod.yml'); + expect(item.editableFiles.some((p) => p.endsWith('/.env'))).toBe(true); + expect(item.status.subItems).toHaveLength(2); + const callsAfterFirst = composeStatusCalls; + + // 2nd fetch within TTL hits cache + const sysCached = await api('/api/systems/docker-compose'); + expect((sysCached.data.snapshots as Array<{ cached: boolean }>)[0]!.cached).toBe(true); + expect(composeStatusCalls).toBe(callsAfterFirst); + + // 2. Update multi-file activeFiles[] overlay -> invalidates cache and passes both -f flags + const overlayRes = await api( + '/api/systems/docker-compose/servers/app1/items/webapp/files', + { + method: 'PUT', + body: { activeFiles: ['compose.yml', 'compose.prod.yml'] }, + }, + ); + expect(overlayRes.status).toBe(200); + + const sysAfterOverlay = await api('/api/systems/docker-compose'); + const snapOverlay = (sysAfterOverlay.data.snapshots as Array)[0]!; + expect(snapOverlay.cached).toBe(false); + expect(snapOverlay.items[0]!.activeFiles).toEqual(['compose.yml', 'compose.prod.yml']); + expect(seenComposeFlags.at(-1)).toBe('-f compose.yml -f compose.prod.yml'); + + // 3. Oneshot action 'up' invalidates cache and transitions system health to 'ok' + const upAct = await api('/api/systems/docker-compose/servers/app1/actions/up', { + method: 'POST', + body: { itemName: 'webapp' }, + }); + expect(upAct.status).toBe(200); + expect(upAct.data.mode).toBe('oneshot'); + + const sysHealthy = await api('/api/systems/docker-compose'); + expect((sysHealthy.data.snapshots as Array)[0]!.systemHealth).toBe('ok'); + + // 4. Stream action 'logs' emits WS stream: chunks + exit meta + const { ws, frames } = await openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }); + const streamRes = await api('/api/systems/docker-compose/servers/app1/actions/logs', { + method: 'POST', + body: { itemName: 'webapp' }, + }); + expect(streamRes.status).toBe(200); + expect(streamRes.data.mode).toBe('stream'); + const jobId = String(streamRes.data.jobId); + + ws.send(JSON.stringify({ type: 'sub', channels: [`stream:${jobId}`] })); + await new Promise((r) => setTimeout(r, 120)); + const logChunks = frames + .filter((f) => f.type === 'stream:chunk' && f.jobId === jobId && f.stream === 'stdout') + .map((f) => String(f.data)) + .join(''); + expect(logChunks).toContain('webapp log line 1'); + + // 5. Interactive subitem action 'debug-shell' opens a PTY session in PTYManager + const dbgRes = await api( + '/api/systems/docker-compose/servers/app1/actions/debug-shell', + { + method: 'POST', + body: { itemName: 'webapp', subItemName: 'web', cols: 88, rows: 24 }, + }, + ); + expect(dbgRes.status).toBe(200); + expect(dbgRes.data.mode).toBe('interactive'); + const dbgSess = dbgRes.data.session as { sessionId: string; serverId: string }; + expect(dbgSess.serverId).toBe('app1'); + expect( + server.ptyManager.listSessions().some((s) => s.sessionId === dbgSess.sessionId), + ).toBe(true); + + // 6. systemd preset with command discovery + sudo action + const systemdRes = await api('/api/systems/systemd'); + expect(systemdRes.status).toBe(200); + const sdSnap = (systemdRes.data.snapshots as Array)[0]!; + expect(sdSnap.items[0]!.name).toBe('nginx.service'); + expect(sdSnap.items[0]!.status.health).toBe('ok'); + + const sdRestart = await api('/api/systems/systemd/servers/app1/actions/restart', { + method: 'POST', + body: { itemName: 'nginx.service' }, + }); + expect(sdRestart.status).toBe(200); + expect(mock.lastSudoStdin).toBe('sudo-secret-pw'); + + ws.close(); + }); +}); diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 748d5ff..4507984 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -1,5 +1,9 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; import net from 'node:net'; -import ssh2, { type Connection, type Server } from 'ssh2'; +import os from 'node:os'; +import path from 'node:path'; +import ssh2, { type Attributes, type Connection, type Server } from 'ssh2'; import { computeOpenSshFingerprint } from '../../src/server/security/vault.js'; export interface MockSshOptions { @@ -9,6 +13,7 @@ export interface MockSshOptions { os?: 'Linux' | 'FreeBSD' | 'Darwin'; authorizedKeys?: string[]; allowTcpForward?: boolean; + sftpRootDir?: string; onExec?: ( command: string, stdin: string, @@ -23,24 +28,82 @@ function unquoteSinglePosix(quoted: string): string { return s; } +function toSftpAttrs(st: fs.Stats): Attributes { + return { + mode: st.mode, + uid: st.uid, + gid: st.gid, + size: st.size, + atime: Math.floor(st.atimeMs / 1000), + mtime: Math.floor(st.mtimeMs / 1000), + }; +} + +function mapSftpFlags(flags: number): number { + const M = ssh2.utils.sftp.OPEN_MODE; + const read = (flags & M.READ) !== 0; + const write = (flags & M.WRITE) !== 0; + let out = read && write ? fs.constants.O_RDWR : write ? fs.constants.O_WRONLY : fs.constants.O_RDONLY; + if ((flags & M.CREAT) !== 0) out |= fs.constants.O_CREAT; + if ((flags & M.TRUNC) !== 0) out |= fs.constants.O_TRUNC; + if ((flags & M.APPEND) !== 0) out |= fs.constants.O_APPEND; + if ((flags & M.EXCL) !== 0) out |= fs.constants.O_EXCL; + return out; +} + export class MockSshServer { public port = 0; public hostFingerprint = ''; public authorizedKeys: string[]; public pollCount = 0; public lastSudoStdin = ''; + public lastPtySize: { cols: number; rows: number } | null = null; + public ptyCount = 0; + public readonly sftpRootDir: string; + private readonly ownsSftpRoot: boolean; private hostPrivateKey: string; private server: Server | null = null; private readonly activeConns = new Set(); + private readonly remoteForwarders = new Map(); constructor(public readonly options: MockSshOptions) { this.authorizedKeys = [...(options.authorizedKeys ?? [])]; + if (options.sftpRootDir) { + this.sftpRootDir = path.resolve(options.sftpRootDir); + fs.mkdirSync(this.sftpRootDir, { recursive: true }); + this.ownsSftpRoot = false; + } else { + this.sftpRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mock-ssh-sftp-')); + this.ownsSftpRoot = true; + } const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' }); this.hostPrivateKey = kp.private; this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim()); } + private resolveVirtualPath(vPath: string): { normPosix: string; absPath: string } { + const trimmed = vPath.trim(); + let candidate = trimmed; + if (!candidate || candidate === '.' || candidate === '~') { + candidate = '/'; + } else if (candidate.startsWith('~/')) { + candidate = `/${candidate.slice(2)}`; + } else if (!candidate.startsWith('/')) { + candidate = `/${candidate}`; + } + const normPosix = path.posix.normalize(candidate); + const rel = normPosix === '/' ? '' : normPosix.slice(1); + const absPath = path.resolve(this.sftpRootDir, rel); + if ( + absPath !== this.sftpRootDir && + !absPath.startsWith(`${this.sftpRootDir}${path.sep}`) + ) { + throw new Error(`Path escapes SFTP root: ${vPath}`); + } + return { normPosix, absPath }; + } + async start(listenPort = 0): Promise { if (this.server) return this.port; @@ -74,6 +137,15 @@ export class MockSshServer { } async close(): Promise { + for (const srv of this.remoteForwarders.values()) { + try { + srv.close(); + } catch { + // Ignore close errors + } + } + this.remoteForwarders.clear(); + for (const c of this.activeConns) { try { c.end(); @@ -87,6 +159,9 @@ export class MockSshServer { this.server = null; await new Promise((resolve) => s.close(() => resolve())); } + if (this.ownsSftpRoot) { + fs.rmSync(this.sftpRootDir, { recursive: true, force: true }); + } } get activeConnectionCount(): number { @@ -162,16 +237,135 @@ export class MockSshServer { }); }); + (client as unknown as NodeJS.EventEmitter).on( + 'request', + ( + accept: ((port?: number) => void) | undefined, + reject: (() => void) | undefined, + name: string, + info: { bindAddr: string; bindPort: number }, + ) => { + if (name === 'tcpip-forward') { + if (this.options.allowTcpForward === false) { + reject?.(); + return; + } + const fwdSrv = net.createServer((sock) => { + const addr = fwdSrv.address(); + const boundPort = typeof addr === 'object' && addr ? addr.port : info.bindPort; + client.forwardOut( + info.bindAddr, + boundPort, + sock.remoteAddress ?? '127.0.0.1', + sock.remotePort ?? 0, + (err, channel) => { + if (err) { + sock.destroy(); + return; + } + sock.pipe(channel); + channel.pipe(sock); + sock.on('close', () => channel.destroy()); + channel.on('close', () => sock.destroy()); + }, + ); + }); + fwdSrv.listen(info.bindPort || 0, '127.0.0.1', () => { + const addr = fwdSrv.address(); + const chosenPort = typeof addr === 'object' && addr ? addr.port : info.bindPort; + this.remoteForwarders.set(`${info.bindAddr}:${chosenPort}`, fwdSrv); + accept?.(chosenPort); + }); + return; + } + + if (name === 'cancel-tcpip-forward') { + const key = `${info.bindAddr}:${info.bindPort}`; + const fwdSrv = this.remoteForwarders.get(key); + if (fwdSrv) { + this.remoteForwarders.delete(key); + fwdSrv.close(() => accept?.()); + } else { + accept?.(); + } + } + }, + ); + client.on('session', (accept) => { const session = accept(); + session.on('pty', (acceptPty, _rejectPty, info) => { + this.lastPtySize = { cols: info.cols, rows: info.rows }; + acceptPty?.(); + }); + session.on('window-change', (acceptWin, _rejectWin, info) => { + this.lastPtySize = { cols: info.cols, rows: info.rows }; + acceptWin?.(); + }); + session.on('shell', (acceptShell) => { + this.ptyCount += 1; + const stream = acceptShell(); + let cwd = '/'; + let lineBuf = ''; + stream.write('\x1b[32mmock$\x1b[0m '); + + stream.on('data', (chunk: Buffer) => { + const text = chunk.toString('utf8'); + for (const ch of text) { + if (ch === '\x03') { + lineBuf = ''; + stream.write('^C\r\n\x1b[32mmock$\x1b[0m '); + continue; + } + if (ch === '\r' || ch === '\n') { + const cmd = lineBuf.trim(); + lineBuf = ''; + stream.write('\r\n'); + if (cmd === 'exit') { + stream.exit(0); + stream.end(); + return; + } + if (cmd === 'pwd') { + stream.write(`${cwd}\r\n`); + } else if (cmd.startsWith('cd ')) { + const rawArg = unquoteSinglePosix(cmd.slice(3).replace(/^--\s+/, '').trim()); + cwd = rawArg.startsWith('/') ? path.posix.normalize(rawArg) : path.posix.normalize(path.posix.join(cwd, rawArg)); + } else if (cmd.startsWith('echo ')) { + stream.write(`${cmd.slice(5)}\r\n`); + } else if (cmd) { + stream.write(`ran:${cmd}\r\n`); + } + stream.write('\x1b[32mmock$\x1b[0m '); + continue; + } + lineBuf += ch; + stream.write(ch); + } + }); + }); + session.on('sftp', (acceptSftp) => { + this.attachSftpServer(acceptSftp()); + }); session.on('exec', (acceptExec, _rejectExec, info) => { const stream = acceptExec(); const stdinChunks: Buffer[] = []; - stream.on('data', (chunk: Buffer) => { - stdinChunks.push(chunk); - }); - stream.on('end', () => { + let finished = false; + const finishExec = () => { + if (finished) return; + finished = true; const stdinText = Buffer.concat(stdinChunks).toString('utf8'); + const binaryResult = this.evaluateBinaryCommand(info.command); + if (binaryResult) { + if (!stream.writable || stream.writableEnded) return; + if (binaryResult.stdout.length > 0) stream.write(binaryResult.stdout); + if (binaryResult.stderr && stream.stderr.writable && !stream.stderr.writableEnded) { + stream.stderr.write(binaryResult.stderr); + } + stream.exit(binaryResult.exitCode); + stream.end(); + return; + } const result = this.evaluateCommand(info.command, stdinText); if (!stream.writable || stream.writableEnded) return; if (result.stdout) stream.write(result.stdout); @@ -180,7 +374,17 @@ export class MockSshServer { } stream.exit(result.exitCode); stream.end(); + }; + stream.on('data', (chunk: Buffer) => { + stdinChunks.push(chunk); }); + stream.on('end', finishExec); + // When pty is allocated on exec (e.g. interactive debug-shell), client keeps stdin open until command exits + setTimeout(() => { + if (!finished && stdinChunks.length === 0) { + finishExec(); + } + }, 15); }); }); }); @@ -335,4 +539,273 @@ export class MockSshServer { return { stdout: `ok:${command}\n`, exitCode: 0 }; } + + private evaluateBinaryCommand( + rawCommand: string, + ): { stdout: Buffer; stderr?: string; exitCode: number } | null { + // Support streamed SFTP folder archive command in integration tests + const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( + rawCommand, + ); + if (tarMatch) { + try { + const virtualParent = unquoteSinglePosix(tarMatch[1]!); + const baseName = unquoteSinglePosix(tarMatch[2]!); + const { absPath: absParent } = this.resolveVirtualPath(virtualParent); + const outBuf = execFileSync('tar', ['-C', absParent, '-czf', '-', baseName]); + return { stdout: outBuf, exitCode: 0 }; + } catch (err) { + return { + stdout: Buffer.alloc(0), + stderr: err instanceof Error ? err.message : String(err), + exitCode: 1, + }; + } + } + return null; + } + + private attachSftpServer(sftp: ssh2.SFTPWrapper): void { + const SC = ssh2.utils.sftp.STATUS_CODE; + let nextId = 1; + const files = new Map(); + const dirs = new Map(); + + const makeHandle = (id: number): Buffer => { + const b = Buffer.allocUnsafe(4); + b.writeUInt32BE(id, 0); + return b; + }; + const readId = (h: Buffer): number => h.readUInt32BE(0); + const sendErr = (reqId: number, err: unknown) => { + const code = (err as { code?: string })?.code; + sftp.status(reqId, code === 'ENOENT' ? SC.NO_SUCH_FILE : SC.FAILURE, String(err)); + }; + + sftp.on('REALPATH', (reqId, reqPath) => { + try { + const { normPosix, absPath } = this.resolveVirtualPath(reqPath); + const st = fs.existsSync(absPath) ? fs.statSync(absPath) : fs.statSync(this.sftpRootDir); + sftp.name(reqId, [ + { + filename: normPosix, + longname: normPosix, + attrs: toSftpAttrs(st), + }, + ]); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('STAT', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + sftp.attrs(reqId, toSftpAttrs(fs.statSync(absPath))); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('LSTAT', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + sftp.attrs(reqId, toSftpAttrs(fs.lstatSync(absPath))); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('FSTAT', (reqId, handle) => { + const entry = files.get(readId(handle)); + if (!entry) { + sftp.status(reqId, SC.FAILURE); + return; + } + sftp.attrs(reqId, toSftpAttrs(fs.fstatSync(entry.fd))); + }); + + sftp.on('OPENDIR', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + if (!fs.statSync(absPath).isDirectory()) { + sftp.status(reqId, SC.FAILURE, 'Not a directory'); + return; + } + const id = nextId++; + dirs.set(id, { absPath, done: false }); + sftp.handle(reqId, makeHandle(id)); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('READDIR', (reqId, handle) => { + const entry = dirs.get(readId(handle)); + if (!entry) { + sftp.status(reqId, SC.FAILURE); + return; + } + if (entry.done) { + sftp.status(reqId, SC.EOF); + return; + } + entry.done = true; + try { + const items = fs.readdirSync(entry.absPath); + sftp.name( + reqId, + items.map((name) => { + const st = fs.lstatSync(path.join(entry.absPath, name)); + return { + filename: name, + longname: `${st.isDirectory() ? 'd' : '-'}rwxr-xr-x 1 mock mock ${st.size} Jan 1 00:00 ${name}`, + attrs: toSftpAttrs(st), + }; + }), + ); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('OPEN', (reqId, filename, flags, attrs) => { + try { + const { absPath } = this.resolveVirtualPath(filename); + const mode = attrs?.mode ? attrs.mode & 0o7777 : 0o644; + const fd = fs.openSync(absPath, mapSftpFlags(flags), mode); + const id = nextId++; + files.set(id, { fd, absPath }); + sftp.handle(reqId, makeHandle(id)); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('READ', (reqId, handle, offset, len) => { + const entry = files.get(readId(handle)); + if (!entry) { + sftp.status(reqId, SC.FAILURE); + return; + } + const buf = Buffer.allocUnsafe(len); + const bytesRead = fs.readSync(entry.fd, buf, 0, len, offset); + if (bytesRead === 0) { + sftp.status(reqId, SC.EOF); + return; + } + sftp.data(reqId, buf.subarray(0, bytesRead)); + }); + + sftp.on('WRITE', (reqId, handle, offset, data) => { + const entry = files.get(readId(handle)); + if (!entry) { + sftp.status(reqId, SC.FAILURE); + return; + } + fs.writeSync(entry.fd, data, 0, data.length, offset); + sftp.status(reqId, SC.OK); + }); + + sftp.on('CLOSE', (reqId, handle) => { + const id = readId(handle); + const f = files.get(id); + if (f) { + files.delete(id); + fs.closeSync(f.fd); + sftp.status(reqId, SC.OK); + return; + } + if (dirs.delete(id)) { + sftp.status(reqId, SC.OK); + return; + } + sftp.status(reqId, SC.OK); + }); + + sftp.on('MKDIR', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + fs.mkdirSync(absPath); + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('RMDIR', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + fs.rmdirSync(absPath); + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('REMOVE', (reqId, reqPath) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + fs.unlinkSync(absPath); + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('RENAME', (reqId, oldPath, newPath) => { + try { + const a = this.resolveVirtualPath(oldPath).absPath; + const b = this.resolveVirtualPath(newPath).absPath; + fs.renameSync(a, b); + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('SETSTAT', (reqId, reqPath, attrs) => { + try { + const { absPath } = this.resolveVirtualPath(reqPath); + if (attrs.mode !== undefined) { + fs.chmodSync(absPath, attrs.mode & 0o7777); + } + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + }); + + sftp.on('FSETSTAT', (reqId, handle, attrs) => { + const entry = files.get(readId(handle)); + if (!entry) { + sftp.status(reqId, SC.FAILURE); + return; + } + if (attrs.mode !== undefined) { + fs.fchmodSync(entry.fd, attrs.mode & 0o7777); + } + sftp.status(reqId, SC.OK); + }); + + sftp.on('EXTENDED', (reqId, extName, extData) => { + if (extName === 'posix-rename@openssh.com') { + try { + const len1 = extData.readUInt32BE(0); + const oldPath = extData.subarray(4, 4 + len1).toString('utf8'); + const len2 = extData.readUInt32BE(4 + len1); + const newPath = extData.subarray(8 + len1, 8 + len1 + len2).toString('utf8'); + fs.renameSync( + this.resolveVirtualPath(oldPath).absPath, + this.resolveVirtualPath(newPath).absPath, + ); + sftp.status(reqId, SC.OK); + } catch (err) { + sendErr(reqId, err); + } + return; + } + sftp.status(reqId, SC.OP_UNSUPPORTED); + }); + } } diff --git a/tests/pty-and-sftp.test.ts b/tests/pty-and-sftp.test.ts new file mode 100644 index 0000000..a65c8c6 --- /dev/null +++ b/tests/pty-and-sftp.test.ts @@ -0,0 +1,383 @@ +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); + }); +}); diff --git a/tests/tunnels-and-proxy.test.ts b/tests/tunnels-and-proxy.test.ts new file mode 100644 index 0000000..0d1e9e0 --- /dev/null +++ b/tests/tunnels-and-proxy.test.ts @@ -0,0 +1,343 @@ +import fs from 'node:fs'; +import http from 'node:http'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import * as OTPAuth from 'otpauth'; +import { afterEach, describe, expect, it } from 'vitest'; +import WebSocket, { WebSocketServer } from 'ws'; +import { createGCoordinatorServer } 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 startUpstreamHttpWsServer() { + let sawCookieHeader: string | undefined; + const httpSrv = http.createServer((req, res) => { + sawCookieHeader = req.headers.cookie; + if (req.url === '/hello') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ ok: true, sawCookie: req.headers.cookie ?? null })); + return; + } + if (req.url === '/redir') { + res.writeHead(302, { Location: '/login' }); + res.end(); + return; + } + if (req.url === '/echo' && req.method === 'POST') { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(Buffer.concat(chunks)); + }); + return; + } + res.writeHead(404); + res.end('not found'); + }); + + const wss = new WebSocketServer({ server: httpSrv, path: '/ws' }); + wss.on('connection', (sock) => { + sock.on('message', (msg) => { + sock.send(`echo:${msg.toString()}`); + }); + }); + + await new Promise((resolve) => { + httpSrv.listen(0, '127.0.0.1', () => resolve()); + }); + const addr = httpSrv.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + return { + port, + getLastCookie: () => sawCookieHeader, + close: async () => { + wss.close(); + await new Promise((r) => httpSrv.close(() => r())); + }, + }; +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TCP Forwards', () => { + it('proxies HTTP + WebSocket over SSH behind hub auth & Safe Mode, runs local-tcp & remote-tcp, and tears down on Panic Lock', async () => { + const upstream = await startUpstreamHttpWsServer(); + cleanups.push(() => upstream.close()); + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-tunnels-')); + 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 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-tunnel-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: 'tun-key', name: 'Tunnel 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: 'app1', + name: 'App 1', + host: '127.0.0.1', + port: sshPort, + username: 'ops', + credentialId: 'tun-key', + pollIntervalSec: 300, + }, + }); + await api('/api/servers/app1/reconnect', { method: 'POST' }); + await api('/api/servers/app1/tofu/approve', { + method: 'POST', + body: { fingerprint: mock.hostFingerprint }, + }); + + // 1. Create & start http-proxy tunnel + const createHttpProxy = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'app1', + tunnel: { + id: 'web-ui', + name: 'Upstream Web UI', + mode: 'http-proxy', + targetHost: '127.0.0.1', + targetPort: upstream.port, + autoStart: false, + }, + start: true, + }, + }); + expect(createHttpProxy.status).toBe(201); + + // Unauthenticated /proxy blocked with 401 + const unauthProxy = await fetch(`${baseUrl}/proxy/web-ui/hello`); + expect(unauthProxy.status).toBe(401); + + // Authenticated GET & POST JSON stream through proxy without exposing hub session cookies + const authedHello = await api('/proxy/web-ui/hello'); + expect(authedHello.status).toBe(200); + expect(authedHello.data.ok).toBe(true); + expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid'); + + const authedPost = await api('/proxy/web-ui/echo', { + method: 'POST', + body: { ping: 'tunnel-body-intact' }, + }); + expect(authedPost.status).toBe(200); + expect(authedPost.data.ping).toBe('tunnel-body-intact'); + + const redirRes = await fetch(`${baseUrl}/proxy/web-ui/redir`, { + headers: { Cookie: jar.header() }, + redirect: 'manual', + }); + expect(redirRes.status).toBe(302); + expect(redirRes.headers.get('location')).toBe('/proxy/web-ui/login'); + + // Safe Mode blocks mutating POST through proxy while allowing GET + await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } }); + const safeGet = await api('/proxy/web-ui/hello'); + expect(safeGet.status).toBe(200); + const safePost = await api('/proxy/web-ui/echo', { + method: 'POST', + body: { blocked: true }, + }); + expect(safePost.status).toBe(423); + await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } }); + + // Authenticated WS upgrade through /proxy/web-ui/ws + await new Promise((resolve, reject) => { + const evil = new WebSocket(`ws://127.0.0.1:${server.port}/proxy/web-ui/ws`, { + headers: { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: 'https://evil.example', + }, + }); + evil.once('unexpected-response', (_r, res) => { + expect(res.statusCode).toBe(403); + resolve(); + }); + evil.once('error', reject); + }); + + const proxyWsReply = await new Promise((resolve, reject) => { + const pws = new WebSocket(`ws://127.0.0.1:${server.port}/proxy/web-ui/ws`, { + headers: { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }, + }); + pws.once('open', () => pws.send('ws-through-ssh')); + pws.once('message', (d) => { + pws.close(); + resolve(d.toString()); + }); + pws.once('error', reject); + }); + expect(proxyWsReply).toBe('echo:ws-through-ssh'); + + // 2. Local TCP (L) tunnel + const localTcpRes = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'app1', + tunnel: { + id: 'tcp-local', + name: 'Local TCP Forward', + mode: 'local-tcp', + bindHost: '127.0.0.1', + targetHost: '127.0.0.1', + targetPort: upstream.port, + autoStart: false, + }, + start: true, + }, + }); + expect(localTcpRes.status).toBe(201); + const localTunnel = ( + localTcpRes.data.tunnels as Array<{ + tunnel: { id: string }; + localBoundPort?: number; + }> + ).find((t) => t.tunnel.id === 'tcp-local')!; + expect(localTunnel.localBoundPort).toBeGreaterThan(0); + + const localHttp = await fetch(`http://127.0.0.1:${localTunnel.localBoundPort}/hello`); + expect(localHttp.status).toBe(200); + expect(((await localHttp.json()) as { ok: boolean }).ok).toBe(true); + + // 3. Remote TCP (R) tunnel via forwardIn + const remoteTcpRes = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'app1', + tunnel: { + id: 'tcp-remote', + name: 'Remote TCP Reverse', + mode: 'remote-tcp', + bindHost: '127.0.0.1', + targetHost: '127.0.0.1', + targetPort: upstream.port, + autoStart: false, + }, + start: true, + }, + }); + expect(remoteTcpRes.status).toBe(201); + const remoteTunnel = ( + remoteTcpRes.data.tunnels as Array<{ + tunnel: { id: string }; + remoteBoundPort?: number; + }> + ).find((t) => t.tunnel.id === 'tcp-remote')!; + expect(remoteTunnel.remoteBoundPort).toBeGreaterThan(0); + + const remoteHttp = await fetch(`http://127.0.0.1:${remoteTunnel.remoteBoundPort}/hello`); + expect(remoteHttp.status).toBe(200); + expect(((await remoteHttp.json()) as { ok: boolean }).ok).toBe(true); + + // 4. Panic Lock tears down all active tunnel listeners immediately + await api('/api/security/panic-lock', { method: 'POST' }); + await expect( + new Promise((resolve, reject) => { + const s = net.connect(localTunnel.localBoundPort!, '127.0.0.1', () => { + s.destroy(); + resolve(); + }); + s.once('error', reject); + }), + ).rejects.toThrow(); + }); +});