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(watch-link): the watcher role refuses everything but chat and sees only its session

reviewee0337d38bd5
diff --git a/src/core/watch-link/watcher-policy.test.ts b/src/core/watch-link/watcher-policy.test.ts
new file mode 100644
index 000000000..732184c36
--- /dev/null
+++ b/src/core/watch-link/watcher-policy.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect } from 'vitest'
+import { IPC } from '../../shared/ipc'
+import { encodePtyData, decodePtyData } from '../../shared/rpc'
+import { WATCH_CHAT_CAST, WATCH_EVENT } from '../../shared/watch-link/protocol'
+import { watcherAccess, watcherEventAllowed, wrapWatcherSink, WATCHER_BUFFER_LIMIT } from './watcher-policy'
+import { createStreamFilter, type StreamFilter } from './stream-filter'
+import { createTokenBucket } from './token-bucket'
+import type { UiSink } from '../ui-sink-registry'
+
+const channelValues = (): string[] =>
+ (Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string')
+
+describe('watcherAccess', () => {
+ it('refuses every IPC channel as a request and as a cast, for both roles', () => {
+ for (const ch of channelValues()) {
+ for (const role of ['viewer', 'commenter'] as const) {
+ expect(watcherAccess('req', ch, role).allow).toBe(false)
+ expect(watcherAccess('cast', ch, role).allow).toBe(false)
+ }
+ }
+ })
+ it('allows the chat cast only for a commenter link, and never as a request', () => {
+ expect(watcherAccess('cast', WATCH_CHAT_CAST, 'commenter')).toEqual({ allow: true })
+ expect(watcherAccess('cast', WATCH_CHAT_CAST, 'viewer').allow).toBe(false)
+ expect(watcherAccess('req', WATCH_CHAT_CAST, 'commenter').allow).toBe(false)
+ })
+})
+
+describe('watcherEventAllowed', () => {
+ it('passes watch:* and this session\'s pty lifecycle events only', () => {
+ expect(watcherEventAllowed(WATCH_EVENT.meta, null)).toBe(true)
+ expect(watcherEventAllowed(IPC.ptySize('s1'), 's1')).toBe(true)
+ expect(watcherEventAllowed(IPC.ptyResync('s1'), 's1')).toBe(true)
+ expect(watcherEventAllowed(IPC.ptySize('s2'), 's1')).toBe(false)
+ expect(watcherEventAllowed(IPC.ptySize('s1'), null)).toBe(false)
+ })
+ it('refuses every broadcast channel in IPC', () => {
+ for (const ch of channelValues()) expect(watcherEventAllowed(ch, 's1')).toBe(false)
+ })
+})
+
+function harness(
+ o: { streaming?: boolean; buffered?: number; rate?: number; burst?: number; filter?: StreamFilter } = {}
+) {
+ const text: string[] = []
+ const bin: string[] = []
+ const base: UiSink = {
+ sendText: (j) => text.push(j),
+ sendBinary: (b) => bin.push(decodePtyData(b)!.data),
+ bufferedAmount: () => o.buffered ?? 0
+ }
+ const calls = { over: 0, life: [] as string[] }
+ let streaming = o.streaming ?? true
+ const sink = wrapWatcherSink(base, {
+ sessionId: () => 's1',
+ streaming: () => streaming,
+ filter: o.filter ?? createStreamFilter(),
+ bucket: createTokenBucket({ ratePerSec: o.rate ?? 1e9, burst: o.burst ?? o.rate ?? 1e9, now: () => 0 }),
+ onOverBudget: () => { calls.over++ },
+ onLifecycle: (k) => { calls.life.push(k) }
+ })
+ return { sink, text, bin, calls, setStreaming: (v: boolean) => { streaming = v } }
+}
+const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })
+
+describe('wrapWatcherSink', () => {
+ it('drops broadcast events and another session\'s data', () => {
+ const h = harness()
+ h.sink.sendText(ev('canvas:mut', 'p1', {}))
+ h.sink.sendText(ev('presence:sync', []))
+ h.sink.sendBinary(encodePtyData('s2', 'other'))
+ expect(h.text).toEqual([])
+ expect(h.bin).toEqual([])
+ })
+ it('filters the stream and keeps the parser fed while not streaming', () => {
+ const h = harness({ streaming: false })
+ h.sink.sendBinary(encodePtyData('s1', 'x\x1b]52;c;c2Vj'))
+ h.setStreaming(true)
+ h.sink.sendBinary(encodePtyData('s1', 'cmV0\x07visible'))
+ expect(h.bin).toEqual(['visible'])
+ })
+ it('reports lifecycle events for its session', () => {
+ const h = harness()
+ h.sink.sendText(ev(IPC.ptyExit('s1'), 0))
+ h.sink.sendText(ev(IPC.ptyRecycled('s1'), { ready: true }))
+ expect(h.calls.life).toEqual(['exit', 'recycled'])
+ })
+ it('goes over budget when the socket backs up or the bucket is empty', () => {
+ const backed = harness({ buffered: WATCHER_BUFFER_LIMIT + 1 })
+ backed.sink.sendBinary(encodePtyData('s1', 'a'))
+ expect(backed.bin).toEqual([])
+ expect(backed.calls.over).toBe(1)
+ const poor = harness({ rate: 5 })
+ poor.sink.sendBinary(encodePtyData('s1', 'this is more than five bytes'))
+ expect(poor.bin).toEqual([])
+ expect(poor.calls.over).toBe(1)
+ })
+ it('keeps bufferedAmount pointing at the base sink', () => {
+ expect(harness({ buffered: 42 }).sink.bufferedAmount?.()).toBe(42)
+ })
+
+ // A viewer that co-attaches to a RUNNING session is handed a `midStream` filter by the link host.
+ // Its first frame may start inside an OSC 52 (tmux emits one per copy): the clipboard's base64
+ // must not reach the viewer as text, however it is split across frames.
+ it('forwards no payload byte when joined mid-OSC-52 with a midStream filter', () => {
+ const secret = ['c2VjcmV0', 'LXBhc3N3b3Jk', 'LWZvci10aGUtY2xpcGJvYXJk']
+ const frames = [secret[0], secret[1], `${secret[2]}\x07`, '\x1b[0mvisible']
+ const h = harness({ filter: createStreamFilter({ midStream: true }) })
+ for (const f of frames) h.sink.sendBinary(encodePtyData('s1', f))
+ expect(h.bin).toEqual(['\x1b[0mvisible'])
+ for (const part of secret) expect(h.bin.join('')).not.toContain(part)
+ // Control: the same join through a filter that assumes it saw the stream from the start is
+ // exactly the leak `midStream` exists to close.
+ const naive = harness()
+ for (const f of frames) naive.sink.sendBinary(encodePtyData('s1', f))
+ expect(naive.bin.join('')).toContain(secret[0])
+ })
+
+ // A pty frame is coalesced up to 256 K UTF-16 units plus one read chunk, so a frame can be larger
+ // than the bucket's burst and can then NEVER be taken. It goes over budget (the link host repaints
+ // with a keyframe) instead of throwing, and it drains nothing: the next frame still passes.
+ it('sends a frame larger than the burst over budget, forwards nothing, and does not throw', () => {
+ const burst = 1024 * 1024
+ const h = harness({ rate: 256 * 1024, burst })
+ const huge = 'a'.repeat(burst + 1)
+ expect(() => h.sink.sendBinary(encodePtyData('s1', huge))).not.toThrow()
+ expect(h.calls.over).toBe(1)
+ expect(h.bin).toEqual([])
+ h.sink.sendBinary(encodePtyData('s1', 'small'))
+ expect(h.bin).toEqual(['small'])
+ })
+})
diff --git a/src/core/watch-link/watcher-policy.ts b/src/core/watch-link/watcher-policy.ts
new file mode 100644
index 000000000..0db7f170c
--- /dev/null
+++ b/src/core/watch-link/watcher-policy.ts
@@ -0,0 +1,94 @@
+// The `watcher` relay role, as two RelayHostHooks pieces. It deliberately does NOT go through
+// access-policy.ts's `decideAccess`: that function evaluates any non-editor role against the whole
+// VIEW table (files, git, presence, board log), and a live link may reach none of it.
+// - Inbound: every request and cast is refused, except a Commenter link's chat cast.
+// - Outbound: only `watch:*` events and this viewer's own pty session; every broadcast is dropped
+// (a second layer: the watcher is also a QUIET client, absent from broadcast() and clientIds()).
+import { IPC } from '../../shared/ipc'
+import { decodePtyData, encodePtyData } from '../../shared/rpc'
+import { WATCH_CHAT_CAST, WATCH_EVENT_PREFIX, type WatchLinkRole } from '../../shared/watch-link/protocol'
+import type { AccessDecision } from '../relay/relay-host'
+import type { UiSink } from '../ui-sink-registry'
+import type { StreamFilter } from './stream-filter'
+import type { TokenBucket } from './token-bucket'
+
+export const WATCHER_REFUSAL = 'A live link can only watch this terminal.'
+export const WATCHER_BUFFER_LIMIT = 512 * 1024
+export const WATCHER_RESUME_BELOW = 256 * 1024
+
+export function watcherAccess(kind: 'req' | 'cast', method: string, role: WatchLinkRole): AccessDecision {
+ if (kind === 'cast' && method === WATCH_CHAT_CAST && role === 'commenter') return { allow: true }
+ return { allow: false, message: WATCHER_REFUSAL }
+}
+
+export function watcherEventAllowed(channel: string, sessionId: string | null): boolean {
+ if (channel.startsWith(WATCH_EVENT_PREFIX)) return true
+ if (!sessionId) return false
+ return (
+ channel === IPC.ptySize(sessionId) ||
+ channel === IPC.ptyExit(sessionId) ||
+ channel === IPC.ptyClosed(sessionId) ||
+ channel === IPC.ptyRecycled(sessionId) ||
+ channel === IPC.ptyResync(sessionId)
+ )
+}
+
+export type PtyLifecycle = 'exit' | 'closed' | 'recycled'
+
+export interface WatcherSinkDeps {
+ sessionId(): string | null
+ /** False until the keyframe for the current session was sent, and while throttled. */
+ streaming(): boolean
+ /** Per viewer, created by the link host: `{ midStream: true }` for a join to a running session. */
+ filter: StreamFilter
+ /** Counts encoded BYTES (the frame as it goes on the wire), not characters. */
+ bucket: TokenBucket
+ onOverBudget(): void
+ onLifecycle(kind: PtyLifecycle): void
+}
+
+function channelOf(json: string): string | null {
+ try {
+ const m = JSON.parse(json) as { t?: unknown; channel?: unknown }
+ return m && m.t === 'ev' && typeof m.channel === 'string' ? m.channel : null
+ } catch {
+ return null
+ }
+}
+
+export function wrapWatcherSink(base: UiSink, d: WatcherSinkDeps): UiSink {
+ return {
+ sendText: (json) => {
+ const channel = channelOf(json)
+ const sid = d.sessionId()
+ if (channel === null || !watcherEventAllowed(channel, sid)) return
+ if (sid && channel === IPC.ptyExit(sid)) d.onLifecycle('exit')
+ else if (sid && channel === IPC.ptyClosed(sid)) d.onLifecycle('closed')
+ else if (sid && channel === IPC.ptyRecycled(sid)) d.onLifecycle('recycled')
+ base.sendText(json)
+ },
+ sendBinary: (buf) => {
+ const frame = decodePtyData(buf)
+ const sid = d.sessionId()
+ if (!frame || !sid || frame.sessionId !== sid) return
+ // Always parse, even when nothing is forwarded (see stream-filter.ts).
+ const text = d.filter.push(frame.data)
+ if (!d.streaming() || !text) return
+ if ((base.bufferedAmount?.() ?? 0) > WATCHER_BUFFER_LIMIT) {
+ d.onOverBudget()
+ return
+ }
+ const out = encodePtyData(sid, text)
+ // `out.length` is encoded BYTES. A pty frame is coalesced up to MAX_BUF_BYTES (256 K UTF-16
+ // units, pty-manager.ts) plus one read chunk, so it can exceed the bucket's burst, and such a
+ // take can never succeed: it goes over budget like any other refusal (the link host repaints
+ // with a keyframe), and a refused take drains nothing.
+ if (!d.bucket.take(out.length)) {
+ d.onOverBudget()
+ return
+ }
+ base.sendBinary(out)
+ },
+ bufferedAmount: () => base.bufferedAmount?.() ?? 0
+ }
+}