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 relay wire rules and the watch: protocol, without Node

review6333c3804694
diff --git a/src/core/watch-link/wire.test.ts b/src/core/watch-link/wire.test.ts
new file mode 100644
index 000000000..522e0581a
--- /dev/null
+++ b/src/core/watch-link/wire.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect } from 'vitest'
+import { hkdfSync } from 'node:crypto'
+import nacl from 'tweetnacl'
+import { encodePtyData, encodeArgs, parseRpcMessage } from '../../shared/rpc'
+import { decrypt, encrypt } from '../relay/e2ee'
+import { hkdfSha256 } from '../../shared/watch-link/hkdf'
+import { sealBox, openBox, withHeader, readHeader, encodePtyFrame, decodePtyFrame, parseTunnelJson, RELAY_SESSION_INFO } from '../../shared/watch-link/wire'
+import { sanitizeChatText, sanitizeChatName, isWatchEndReason, WATCH_CHAT_CAST, WATCH_EVENT_PREFIX } from '../../shared/watch-link/protocol'
+import { utf8 } from '../../shared/watch-link/bytes'
+
+describe('the wire rules match the relay they were copied from', () => {
+ it('HKDF equals node:crypto', async () => {
+ const ikm = nacl.randomBytes(32), salt = nacl.randomBytes(32)
+ const ours = await hkdfSha256(ikm, salt, utf8(RELAY_SESSION_INFO), 32)
+ expect(ours).toEqual(new Uint8Array(hkdfSync('sha256', ikm, salt, utf8(RELAY_SESSION_INFO), 32)))
+ })
+ it('a box sealed here opens with e2ee.decrypt and vice versa', () => {
+ const key = nacl.randomBytes(32), plain = utf8('hello')
+ expect(decrypt(sealBox(plain, key), key)).toEqual(plain)
+ expect(openBox(encrypt(plain, key), key)).toEqual(plain)
+ expect(openBox(Uint8Array.of(1, 2, 3), key)).toBeNull()
+ })
+ it('the header is role, seq high word LE, seq low word LE', () => {
+ const h = withHeader(2, 2 ** 32 + 7, utf8('x'))
+ expect(Array.from(h.slice(0, 9))).toEqual([2, 1, 0, 0, 0, 7, 0, 0, 0])
+ expect(readHeader(h)).toEqual({ role: 2, seq: 2 ** 32 + 7, body: utf8('x') })
+ expect(readHeader(Uint8Array.of(1, 2))).toBeNull()
+ })
+ it('pty frames equal rpc.ts', () => {
+ const sid = 'sess-é', data = 'a\u001b[31mbé'
+ expect(encodePtyFrame(sid, data)).toEqual(encodePtyData(sid, data))
+ expect(decodePtyFrame(encodePtyData(sid, data))).toEqual({ sessionId: sid, data })
+ expect(decodePtyFrame(Uint8Array.of(9))).toBeNull()
+ })
+ it('tunnel JSON parses like parseRpcMessage, undefined slots included', () => {
+ const ev = JSON.stringify({ t: 'ev', channel: 'watch:meta', ...encodeArgs([{ a: 1 }, undefined]) })
+ expect(parseTunnelJson(ev)).toEqual(parseRpcMessage(ev))
+ const cast = JSON.stringify({ t: 'cast', method: 'trust:confirm', args: [] })
+ expect(parseTunnelJson(cast)).toEqual({ t: 'cast', method: 'trust:confirm', args: [] })
+ expect(parseTunnelJson('{"t":"res","id":1,"ok":true,"result":1}')).toBeNull()
+ expect(parseTunnelJson('nope')).toBeNull()
+ })
+})
+
+describe('protocol', () => {
+ it('the viewer cast is not in the host-only owner namespace', () => {
+ expect(WATCH_CHAT_CAST.startsWith('watchLink:')).toBe(false)
+ expect(WATCH_EVENT_PREFIX).toBe('watch:')
+ })
+ it('sanitizes chat text and names', () => {
+ expect(sanitizeChatText(' hi\u0007 there\nfriend \u009b ')).toBe('hi there friend')
+ expect(sanitizeChatText('x'.repeat(600))).toHaveLength(500)
+ expect(sanitizeChatText(' ')).toBeNull()
+ expect(sanitizeChatText(42)).toBeNull()
+ expect(sanitizeChatName('\u001b[31mAda')).toBe('[31mAda')
+ expect(sanitizeChatName('n'.repeat(40))).toHaveLength(32)
+ expect(isWatchEndReason('kicked')).toBe(true)
+ expect(isWatchEndReason('nope')).toBe(false)
+ })
+})
diff --git a/src/shared/watch-link/hkdf.ts b/src/shared/watch-link/hkdf.ts
new file mode 100644
index 000000000..b287307a5
--- /dev/null
+++ b/src/shared/watch-link/hkdf.ts
@@ -0,0 +1,10 @@
+// HKDF-SHA256 over WebCrypto, the browser's equivalent of the relay's `hkdfSync` (e2ee.ts).
+import { webCryptoBytes } from './bytes'
+
+export async function hkdfSha256(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {
+ const subtle = globalThis.crypto.subtle
+ const key = await subtle.importKey('raw', webCryptoBytes(ikm), 'HKDF', false, ['deriveBits'])
+ return new Uint8Array(
+ await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: webCryptoBytes(salt), info: webCryptoBytes(info) }, key, length * 8)
+ )
+}
diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.ts
new file mode 100644
index 000000000..6de7a0196
--- /dev/null
+++ b/src/shared/watch-link/protocol.ts
@@ -0,0 +1,63 @@
+// What travels inside a live link's E2E tunnel, besides raw pty frames and pty:* events.
+// The viewer's namespace is `watch:` on purpose: the OWNER's IPC is `watchLink:`, which the relay
+// host refuses from every peer as host-only BEFORE any policy runs (src/shared/host-control.ts).
+
+export const WATCH_PROTOCOL_VERSION = 1
+export const WATCH_EVENT_PREFIX = 'watch:'
+export const WATCH_EVENT = {
+ meta: 'watch:meta',
+ keyframe: 'watch:keyframe',
+ waiting: 'watch:waiting',
+ chat: 'watch:chat',
+ end: 'watch:end'
+} as const
+/** The one message a viewer may send (Commenter links only). */
+export const WATCH_CHAT_CAST = 'watch:chat'
+
+export type WatchLinkRole = 'viewer' | 'commenter'
+export const WATCH_END_REASONS = ['revoked', 'expired', 'node-gone', 'session-ended', 'host-stopping', 'kicked'] as const
+export type WatchLinkEndReason = (typeof WATCH_END_REASONS)[number]
+export function isWatchEndReason(x: unknown): x is WatchLinkEndReason {
+ return typeof x === 'string' && (WATCH_END_REASONS as readonly string[]).includes(x)
+}
+
+export interface WatchMeta {
+ v: number
+ role: WatchLinkRole
+ /** Sharer-supplied; render as text, marked as set by the sharer. */
+ label: string
+ title: string
+ /** Epoch ms on the host's clock, corrected to the server's. */
+ expiresAt: number
+ cols: number
+ rows: number
+}
+export interface WatchKeyframe {
+ sessionId: string
+ /** The visible screen with SGR, or '' when the backend has no visible-only capture. */
+ screen: string
+ /** tmux paints its client on the alternate screen; the viewer must switch to it BEFORE painting,
+ * or every tmux redraw scrolls into the viewer's history (CLAUDE.md, co-attach seeding). */
+ altScreen: boolean
+}
+export interface WatchChatMessage {
+ id: string
+ name: string
+ text: string
+ at: number
+ from: 'viewer' | 'sharer'
+}
+
+export const CHAT_TEXT_MAX = 500
+export const CHAT_NAME_MAX = 32
+// C0 and C1 controls, DEL, and the ESC that starts every sequence. A newline becomes a space: chat
+// is one line, and a pasted multi-line block must not reflow the owner's popover.
+const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
+
+function clean(raw: unknown, max: number): string | null {
+ if (typeof raw !== 'string') return null
+ const s = raw.replace(/[\r\n\t]+/g, ' ').replace(CONTROLS, '').replace(/\s+/g, ' ').trim().slice(0, max).trim()
+ return s ? s : null
+}
+export const sanitizeChatText = (raw: unknown): string | null => clean(raw, CHAT_TEXT_MAX)
+export const sanitizeChatName = (raw: unknown): string | null => clean(raw, CHAT_NAME_MAX)
diff --git a/src/shared/watch-link/wire.ts b/src/shared/watch-link/wire.ts
new file mode 100644
index 000000000..fa627064c
--- /dev/null
+++ b/src/shared/watch-link/wire.ts
@@ -0,0 +1,82 @@
+// The relay's wire rules, restated without Node so the browser can speak them. The SOURCE of truth
+// is src/core/relay/relay-socket.ts + e2ee.ts + src/shared/rpc.ts; src/core/watch-link/wire.test.ts
+// pins this copy to them byte for byte, so a change there fails there before it can strand the
+// viewer page. (The test lives in core because it imports e2ee.ts, which the web tsconfig project
+// cannot see.)
+//
+// Sealed box: nonce(24) ‖ nacl.box.after(plain). Plain: [role:1][seqHi u32 LE][seqLo u32 LE][tag:1][body].
+import nacl from 'tweetnacl'
+import { concatBytes } from './bytes'
+
+export const TAG_RPC = 0x01
+export const TAG_TUNNEL_TEXT = 0x03
+export const TAG_TUNNEL_BIN = 0x04
+export const ROLE_HOST = 1
+export const ROLE_CLIENT = 2
+export const NONCE_BYTES = 16
+export const RELAY_SESSION_INFO = 'nodeterm-relay-session-v2'
+const HEADER_BYTES = 9
+
+export function sealBox(plain: Uint8Array, key: Uint8Array, nonce: Uint8Array = nacl.randomBytes(nacl.box.nonceLength)): Uint8Array {
+ return concatBytes(nonce, nacl.box.after(plain, nonce, key))
+}
+
+export function openBox(box: Uint8Array, key: Uint8Array): Uint8Array | null {
+ if (box.length < nacl.box.nonceLength + nacl.box.overheadLength) return null
+ return nacl.box.open.after(box.subarray(nacl.box.nonceLength), box.subarray(0, nacl.box.nonceLength), key) ?? null
+}
+
+export function withHeader(role: number, seq: number, body: Uint8Array): Uint8Array {
+ const out = new Uint8Array(HEADER_BYTES + body.length)
+ const view = new DataView(out.buffer)
+ out[0] = role
+ view.setUint32(1, Math.floor(seq / 0x100000000), true)
+ view.setUint32(5, seq >>> 0, true)
+ out.set(body, HEADER_BYTES)
+ return out
+}
+
+export function readHeader(plain: Uint8Array): { role: number; seq: number; body: Uint8Array } | null {
+ if (plain.length < HEADER_BYTES) return null
+ const view = new DataView(plain.buffer, plain.byteOffset, plain.byteLength)
+ return { role: plain[0], seq: view.getUint32(1, true) * 0x100000000 + view.getUint32(5, true), body: plain.subarray(HEADER_BYTES) }
+}
+
+export function encodePtyFrame(sessionId: string, data: string): Uint8Array {
+ const enc = new TextEncoder()
+ const sid = enc.encode(sessionId)
+ const out = new Uint8Array(3 + sid.length)
+ out[0] = 0x01
+ out[1] = (sid.length >> 8) & 0xff
+ out[2] = sid.length & 0xff
+ out.set(sid, 3)
+ return concatBytes(out, enc.encode(data))
+}
+
+export function decodePtyFrame(buf: Uint8Array): { sessionId: string; data: string } | null {
+ if (buf.length < 3 || buf[0] !== 0x01) return null
+ const len = (buf[1] << 8) | buf[2]
+ if (buf.length < 3 + len) return null
+ const dec = new TextDecoder()
+ return { sessionId: dec.decode(buf.subarray(3, 3 + len)), data: dec.decode(buf.subarray(3 + len)) }
+}
+
+export type TunnelMessage =
+ | { t: 'ev'; channel: string; args: unknown[] }
+ | { t: 'cast'; method: string; args: unknown[] }
+
+/** The two message kinds a viewer ever receives. `undef` restores `undefined` slots (rpc.ts). */
+export function parseTunnelJson(json: string): TunnelMessage | null {
+ let m: { t?: unknown; channel?: unknown; method?: unknown; args?: unknown; undef?: unknown }
+ try {
+ m = JSON.parse(json)
+ } catch {
+ return null
+ }
+ if (!m || typeof m !== 'object' || !Array.isArray(m.args)) return null
+ const args = [...m.args]
+ if (Array.isArray(m.undef)) for (const i of m.undef) if (Number.isInteger(i) && i >= 0 && i < args.length) args[i] = undefined
+ if (m.t === 'ev' && typeof m.channel === 'string') return { t: 'ev', channel: m.channel, args }
+ if (m.t === 'cast' && typeof m.method === 'string') return { t: 'cast', method: m.method, args }
+ return null
+}