Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(server): authenticated /ws endpoint routing RPC frames to ServerPlatform

enesc69d4ed2c1d1
diff --git a/src/server/ws.test.ts b/src/server/ws.test.ts
new file mode 100644
index 000000000..2cfdd601e
--- /dev/null
+++ b/src/server/ws.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import http from 'http'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import WebSocket from 'ws'
+import { Auth } from './auth'
+import { ServerPlatform } from './platform-server'
+import { attachWsServer } from './ws'
+import { SESSION_COOKIE } from './http'
+
+let dir: string, server: http.Server, port: number, auth: Auth, platform: ServerPlatform, cookie: string
+
+beforeEach(async () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-ws-'))
+ auth = new Auth(dir)
+ platform = new ServerPlatform({ userDataDir: dir, appVersion: '0.0.0' })
+ server = http.createServer((_q, s) => { s.statusCode = 404; s.end() })
+ attachWsServer(server, { platform, auth })
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ port = (server.address() as { port: number }).port
+ cookie = `${SESSION_COOKIE}=${auth.createSession()}`
+})
+afterEach(async () => {
+ await new Promise((r) => server.close(r))
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+function connect(headers: Record<string, string>): Promise<WebSocket> {
+ return new Promise((resolve, reject) => {
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { headers })
+ ws.on('open', () => resolve(ws))
+ ws.on('error', reject)
+ })
+}
+
+describe('ws endpoint', () => {
+ it('rejects without a valid session cookie and with a cross-site Origin', async () => {
+ await expect(connect({})).rejects.toThrow()
+ await expect(connect({ cookie: `${SESSION_COOKIE}=bogus` })).rejects.toThrow()
+ await expect(
+ connect({ cookie, origin: 'https://evil.example.com' })
+ ).rejects.toThrow()
+ })
+
+ it('accepts a valid cookie (same-host Origin ok), dispatches req and cast, pushes events', async () => {
+ platform.handle('echo:x', (v: string) => `got:${v}`)
+ const casts: unknown[] = []
+ platform.on('fire', (v: unknown) => casts.push(v))
+ const ws = await connect({ cookie, origin: `http://127.0.0.1:${port}` })
+ const messages: string[] = []
+ ws.on('message', (d, isBinary) => { if (!isBinary) messages.push(d.toString()) })
+
+ ws.send(JSON.stringify({ t: 'req', id: 7, method: 'echo:x', args: ['hi'] }))
+ ws.send(JSON.stringify({ t: 'cast', method: 'fire', args: [123] }))
+ await new Promise((r) => setTimeout(r, 200))
+ expect(messages.map((m) => JSON.parse(m))).toContainEqual({
+ t: 'res', id: 7, ok: true, result: 'got:hi'
+ })
+ expect(casts).toEqual([123])
+
+ // server push (JSON event + binary pty frame) reaches the client
+ const bins: Buffer[] = []
+ ws.on('message', (d, isBinary) => { if (isBinary) bins.push(d as Buffer) })
+ platform.broadcast('pty:exit:s9', 0)
+ platform.broadcast('pty:data:s9', 'chunk')
+ await new Promise((r) => setTimeout(r, 200))
+ expect(messages.map((m) => JSON.parse(m))).toContainEqual({
+ t: 'ev', channel: 'pty:exit:s9', args: [0]
+ })
+ expect(bins.length).toBe(1)
+ ws.close()
+ })
+})
diff --git a/src/server/ws.ts b/src/server/ws.ts
new file mode 100644
index 000000000..5c81aff53
--- /dev/null
+++ b/src/server/ws.ts
@@ -0,0 +1,99 @@
+// Authenticated WebSocket endpoint for the Server Edition.
+//
+// Attaches a `WebSocketServer({ noServer: true })` to an existing http.Server and
+// handles the `upgrade` event ONLY for path `/ws`. The upgrade is gated by the
+// session cookie AND (when an Origin header is present) an Origin/Host same-host
+// check that blocks cross-site WebSocket hijacking — native clients (curl/ws)
+// without an Origin still pass the gate but must present a valid cookie.
+//
+// Once connected, each socket attaches to the ServerPlatform as one UI: text
+// frames are parsed as RPC (req → dispatch → response; cast → cast; anything else
+// ignored), and the platform pushes JSON events / binary pty frames back through
+// the sink. Binary client→server frames are ignored in Phase 2 (pty input rides
+// JSON casts). See task-5-brief.md.
+import type http from 'http'
+import type { Duplex } from 'stream'
+import { WebSocketServer, type WebSocket } from 'ws'
+import type { Auth } from './auth'
+import type { ServerPlatform } from './platform-server'
+import { sessionTokenFromCookie } from './http'
+import { parseRpcMessage } from '../shared/rpc'
+
+export interface WsServerOpts {
+ platform: ServerPlatform
+ auth: Auth
+}
+
+/**
+ * Decide whether an upgrade request is allowed. Returns true only when the
+ * session cookie validates AND, if an Origin header is present, its host matches
+ * the Host header. A malformed Origin URL is treated as a rejection (never throws).
+ */
+function upgradeAllowed(req: http.IncomingMessage, auth: Auth): boolean {
+ const token = sessionTokenFromCookie(req.headers['cookie'])
+ if (!auth.validateSession(token)) return false
+
+ const origin = req.headers['origin']
+ if (typeof origin === 'string' && origin.length > 0) {
+ let originHost: string
+ try {
+ originHost = new URL(origin).host
+ } catch {
+ // Malformed Origin → reject, don't throw.
+ return false
+ }
+ if (originHost !== req.headers['host']) return false
+ }
+ return true
+}
+
+export function attachWsServer(server: http.Server, opts: WsServerOpts): void {
+ const { platform, auth } = opts
+ const wss = new WebSocketServer({ noServer: true })
+
+ server.on('upgrade', (req: http.IncomingMessage, socket: Duplex, head: Buffer) => {
+ // Only handle our path; a mismatched path is left for any other upgrade
+ // listener (and, if none, the socket eventually times out / is destroyed by node).
+ const pathname = new URL(req.url || '/', 'http://x').pathname
+ if (pathname !== '/ws') return
+
+ if (!upgradeAllowed(req, auth)) {
+ socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
+ socket.destroy()
+ return
+ }
+
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ wss.emit('connection', ws, req)
+ })
+ })
+
+ wss.on('connection', (ws: WebSocket) => {
+ const uiId = platform.attach({
+ sendText: (json) => ws.send(json),
+ sendBinary: (buf) => ws.send(buf, { binary: true })
+ })
+
+ ws.on('message', (data: unknown, isBinary: boolean) => {
+ // Binary client→server frames are ignored in Phase 2 (pty input rides JSON casts).
+ if (isBinary) return
+ const text = Buffer.isBuffer(data)
+ ? data.toString('utf8')
+ : Array.isArray(data)
+ ? Buffer.concat(data).toString('utf8')
+ : String(data)
+ const m = parseRpcMessage(text)
+ if (!m) return
+ if (m.t === 'req') {
+ void platform.dispatch(uiId, m).then((res) => ws.send(JSON.stringify(res)))
+ } else if (m.t === 'cast') {
+ platform.cast(uiId, m.method, m.args)
+ }
+ // res/ev from a client are ignored.
+ })
+
+ ws.on('close', () => {
+ platform.detach(uiId)
+ })
+ })
+}