The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor: migrate terminal paste from JSON to binary frames to ensure end-to-end encrypted delivery and filter SIGINT characters
0xken157ea42ce48c6d
diff --git a/cli/src/lib/terminalBinary.spec.ts b/cli/src/lib/terminalBinary.spec.tsindex d619948db..487daa6c2 100644--- a/cli/src/lib/terminalBinary.spec.ts+++ b/cli/src/lib/terminalBinary.spec.ts@@ -7,6 +7,8 @@ import {parseTerminalBinaryEnvelope,sealTerminalBinary,TerminalBinaryKind,+ TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES,+ TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES,} from './terminalBinary.js'const key = Uint8Array.from({ length: 32 }, (_, index) => index)@@ -84,6 +86,45 @@ describe('terminal binary protocol v3', () => {})).toBeNull()})+ it('round-trips an uncompressed paste at a ceiling far above ordinary input', () => {+ const bytes = new TextEncoder().encode('x'.repeat(200 * 1024))+ const sealed = sealTerminalBinary(key, 8, {+ kind: TerminalBinaryKind.paste,+ streamId,+ seq: 0,+ bytes,+ compressed: false,+ })!+ expect(sealed).not.toBeNull()+ expect(openTerminalBinary(key, sealed)?.frame).toEqual({+ kind: TerminalBinaryKind.paste,+ streamId,+ seq: 0,+ bytes,+ compressed: false,+ })++ // A frame this size is exactly what the old shared ceiling used to reject for every kind —+ // paste needs it, input/output/keyframe/sync do not, so it must stay kind-specific.+ const big = new Uint8Array(TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES + 1)+ expect(sealTerminalBinary(key, 9, { kind: TerminalBinaryKind.paste, streamId, seq: 0, bytes: big, compressed: false })).not.toBeNull()+ expect(sealTerminalBinary(key, 9, { kind: TerminalBinaryKind.output, streamId, seq: 0, bytes: big, compressed: false })).toBeNull()++ // Paste's own ceiling still holds against something absurd.+ const tooBig = new Uint8Array(TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES + 1)+ expect(sealTerminalBinary(key, 9, { kind: TerminalBinaryKind.paste, streamId, seq: 0, bytes: tooBig, compressed: false })).toBeNull()+ })++ it('rejects a compressed paste — nothing on the receiving end inflates it yet', () => {+ expect(sealTerminalBinary(key, 10, {+ kind: TerminalBinaryKind.paste,+ streamId,+ seq: 0,+ bytes: Uint8Array.of(1, 2, 3),+ compressed: true,+ })).toBeNull()+ })+it('rejects tamper, truncation and unsupported flags', () => {const sealed = sealTerminalBinary(key, 1, {kind: TerminalBinaryKind.output,@@ -138,4 +179,33 @@ describe('authenticated loopback terminal framing v1', () => {const badMagic = encoded.slice(); badMagic[0] = 0expect(decodeTerminalLocal(badMagic)).toBeNull()})++ it('carries a paste well past the ordinary local frame ceiling', () => {+ // Comfortably over the 512 KiB ceiling every other kind still has — this is the exact size class+ // that used to make a real paste fail to even reach the daemon over the local loopback socket.+ const bytes = new TextEncoder().encode('y'.repeat(1 * 1024 * 1024))+ const encoded = encodeTerminalLocal({+ kind: TerminalBinaryKind.paste,+ streamId,+ seq: 0,+ bytes,+ compressed: false,+ })+ expect(encoded).not.toBeNull()+ expect(decodeTerminalLocal(encoded!)).toEqual({+ kind: TerminalBinaryKind.paste,+ streamId,+ seq: 0,+ bytes,+ compressed: false,+ })++ expect(encodeTerminalLocal({+ kind: TerminalBinaryKind.output,+ streamId,+ seq: 0,+ bytes,+ compressed: false,+ })).toBeNull()+ })})diff --git a/cli/src/lib/terminalBinary.ts b/cli/src/lib/terminalBinary.tsindex 92bc8137a..dbdb8e630 100644--- a/cli/src/lib/terminalBinary.ts+++ b/cli/src/lib/terminalBinary.ts@@ -9,12 +9,24 @@ export const TERMINAL_HOP_HEADER_BYTES = 24export const TERMINAL_LOCAL_VERSION = 1export const TERMINAL_LOCAL_HEADER_BYTES = 12export const TERMINAL_LOCAL_MAX_PAYLOAD_BYTES = 512 * 1024+// A paste is delivered whole, in one frame — unlike every other kind, which is either a small+// bounded control message (keyframe/sync) or already chunked upstream to stay well under the+// keystroke ceiling (input, ≤8 KiB per frame client-side). Reusing that ceiling for paste made an+// entirely ordinary large clipboard paste (a few hundred KB of real code) bounce off a limit sized+// for a keystroke. This is a sanity ceiling against a broken/malicious client, not a real limit —+// see PASTE_MAX_BYTES's own history in terminalStreamManager.ts.+export const TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES = 6 * 1024 * 1024+export const TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES = 6 * 1024 * 1024export const enum TerminalBinaryKind {input = 1,output = 2,keyframe = 3,sync = 4,+ /** A clipboard paste made directly into the terminal, delivered as one atomic unit — see+ * `pasteRawIntoTmux` in tmux.ts for why this needs its own kind instead of riding `input`. Upload+ * (client→CLI) only; nothing ever sends this back down. */+ paste = 5,}export interface TerminalBinaryClear {@@ -67,19 +79,39 @@ function validKind(value: number): value is TerminalBinaryKind {|| value === TerminalBinaryKind.output|| value === TerminalBinaryKind.keyframe|| value === TerminalBinaryKind.sync+ || value === TerminalBinaryKind.paste}export function terminalBinaryType(kind: TerminalBinaryKind): string {if (kind === TerminalBinaryKind.input) return 'terminal_input'if (kind === TerminalBinaryKind.output) return 'terminal_output'if (kind === TerminalBinaryKind.keyframe) return 'terminal_keyframe'+ if (kind === TerminalBinaryKind.paste) return 'terminal_paste'return 'terminal_sync'}+/** The seal/parse/encode/decode size ceiling for [kind] — paste gets a much larger one; see+ * TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES. */+function maxCiphertextBytesFor(kind: TerminalBinaryKind): number {+ return kind === TerminalBinaryKind.paste+ ? TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES+ : TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES+}++function maxLocalPayloadBytesFor(kind: TerminalBinaryKind): number {+ return kind === TerminalBinaryKind.paste+ ? TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES+ : TERMINAL_LOCAL_MAX_PAYLOAD_BYTES+}+export function encodeTerminalPlain(frame: TerminalBinaryClear): Uint8Array | null {const id = uuidBytes(frame.streamId)if (!id || !Number.isSafeInteger(frame.seq) || frame.seq < 0) return null- if ((frame.kind === TerminalBinaryKind.input || frame.kind === TerminalBinaryKind.sync) && frame.compressed) return null+ // Compression is for the SERVER's own output/keyframe frames, which the client already knows how+ // to inflate. Nothing on this side inflates an incoming frame, so a client-compressed kind (input,+ // sync, and — for now — paste too) would silently hand tmux a compressed blob instead of text.+ if ((frame.kind === TerminalBinaryKind.input || frame.kind === TerminalBinaryKind.sync+ || frame.kind === TerminalBinaryKind.paste) && frame.compressed) return nullif (frame.kind === TerminalBinaryKind.sync && frame.bytes.length !== 0) return nullconst metaBytes = frame.kind === TerminalBinaryKind.keyframe ? 28 : 24const out = new Uint8Array(metaBytes + frame.bytes.length)@@ -98,7 +130,8 @@ export function encodeTerminalPlain(frame: TerminalBinaryClear): Uint8Array | nuexport function decodeTerminalPlain(kind: TerminalBinaryKind, flags: number, plaintext: Uint8Array): TerminalBinaryClear | null {if ((flags & ~FLAG_ZLIB) !== 0- || ((kind === TerminalBinaryKind.input || kind === TerminalBinaryKind.sync) && flags !== 0)) return null+ || ((kind === TerminalBinaryKind.input || kind === TerminalBinaryKind.sync+ || kind === TerminalBinaryKind.paste) && flags !== 0)) return nullconst metaBytes = kind === TerminalBinaryKind.keyframe ? 28 : 24if (plaintext.length < metaBytes || (kind === TerminalBinaryKind.sync && plaintext.length !== metaBytes)) return nullconst view = new DataView(plaintext.buffer, plaintext.byteOffset, plaintext.byteLength)@@ -122,7 +155,7 @@ export function parseTerminalBinaryEnvelope(raw: Uint8Array): TerminalBinaryEnveconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)const counter = safeU64(view, 8)const length = view.getUint32(16, false)- if (counter == null || length < 16 || length > TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES+ if (counter == null || length < 16 || length > maxCiphertextBytesFor(bytes[5])|| bytes.length !== TERMINAL_BINARY_HEADER_BYTES + length) return nullreturn {kind: bytes[5],@@ -146,7 +179,7 @@ export function sealTerminalBinary(key: Uint8Array, counter: number, frame: Termconst view = new DataView(header.buffer)view.setBigUint64(8, BigInt(counter), false)const ciphertext = aeadSeal(key, counter, header.subarray(0, 16), plaintext)- if (ciphertext.length > TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES) return null+ if (ciphertext.length > maxCiphertextBytesFor(frame.kind)) return nullview.setUint32(16, ciphertext.length, false)const out = new Uint8Array(header.length + ciphertext.length)out.set(header)@@ -166,7 +199,7 @@ export function openTerminalBinary(key: Uint8Array, raw: Uint8Array): { counter:/** Plain terminal framing for the authenticated loopback desktop transport. */export function encodeTerminalLocal(frame: TerminalBinaryClear): Uint8Array | null {const payload = encodeTerminalPlain(frame)- if (!payload || payload.length > TERMINAL_LOCAL_MAX_PAYLOAD_BYTES) return null+ if (!payload || payload.length > maxLocalPayloadBytesFor(frame.kind)) return nullconst flags = frame.compressed ? FLAG_ZLIB : 0const header = new Uint8Array(TERMINAL_LOCAL_HEADER_BYTES)header.set(LOCAL_MAGIC, 0)@@ -191,7 +224,7 @@ export function decodeTerminalLocal(raw: Uint8Array): TerminalBinaryClear | nullif (bytes[4] !== TERMINAL_LOCAL_VERSION || !validKind(kind) || bytes[7] !== 0) return nullconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)const length = view.getUint32(8, false)- if (length > TERMINAL_LOCAL_MAX_PAYLOAD_BYTES || bytes.length !== TERMINAL_LOCAL_HEADER_BYTES + length) return null+ if (length > maxLocalPayloadBytesFor(kind) || bytes.length !== TERMINAL_LOCAL_HEADER_BYTES + length) return nullreturn decodeTerminalPlain(kind, flags, bytes.slice(TERMINAL_LOCAL_HEADER_BYTES))}diff --git a/cli/src/lib/terminalP2p.ts b/cli/src/lib/terminalP2p.tsindex 3bf214987..0ef66e894 100644--- a/cli/src/lib/terminalP2p.ts+++ b/cli/src/lib/terminalP2p.ts@@ -38,7 +38,9 @@ export const TERMINAL_P2P_SIGNAL_TYPES = new Set([export const TERMINAL_P2P_DOWN_TYPES = new Set(['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack','terminal_input', 'terminal_resize', 'terminal_resync', 'terminal_close', 'terminal_scroll',- 'terminal_paste',+ // Deliberately no 'terminal_paste' here: it travels as a binary TerminalBinaryKind.paste frame,+ // not JSON, so it needs no entry in this JSON-type forwarding list — the binary channel already+ // crosses the P2P data channel on its own.])export const TERMINAL_P2P_UP_TYPES = new Set([diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex bd6da16e7..c9fbfb478 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -180,35 +180,41 @@ describe('TerminalStreamManager', () => {expect(sent.at(-1)?.payload.code).toBe('TERMINAL_SCROLL_INVALID')})- it('routes terminal_paste to pasteRaw as one unit, never through writeRaw', async () => {+ it('routes a binary paste kind to pasteRaw as one unit, never through writeRaw', async () => {await manager.handleFrame('web-1', 'terminal_open', {requestId: 'open-paste', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,})const streamId = sent[0].payload.streamId as string+ const paste = (text: string): TerminalBinaryClear => ({+ kind: TerminalBinaryKind.paste, streamId, seq: 0, compressed: false,+ bytes: new TextEncoder().encode(text),+ })++ // JSON is refused outright — a paste must ride the binary/AEAD channel, same reason terminal_input+ // does — so a stray legacy JSON paste never silently goes nowhere.+ await manager.handleFrame('web-1', 'terminal_paste', { streamId })+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_BINARY_REQUIRED')+ expect(stream.pastes).toHaveLength(0)const longPaste = Array.from({ length: 200 }, (_, i) => `line ${i}`).join('\n')- await manager.handleFrame('web-1', 'terminal_paste', { streamId, text: longPaste })+ await manager.handleBinary('web-1', paste(longPaste))expect(stream.pastes).toEqual([longPaste])expect(stream.writes).toHaveLength(0)- // Ctrl+C pasted alongside real content is forwarded like any other byte, same as input().- await manager.handleFrame('web-1', 'terminal_paste', { streamId, text: 'a\x03b' })- expect(stream.pastes.at(-1)).toBe('a\x03b')+ // Same reason as input(): the engine in the pane has no job-control fallback for an uncaught+ // SIGINT, so a stray 0x03 pasted alongside real content must never reach it.+ await manager.handleBinary('web-1', paste('a\x03b'))+ expect(stream.pastes.at(-1)).toBe('ab')- await manager.handleFrame('web-1', 'terminal_paste', { streamId, text: '' })- expect(sent.at(-1)?.payload.code).toBe('TERMINAL_PASTE_INVALID')+ await manager.handleBinary('web-1', paste(''))expect(stream.pastes).toHaveLength(2)// A real paste of ordinary code (tens/hundreds of KB) must not bounce off a limit sized for one// keystroke chunk — this is the exact regression that froze a real terminal over a normal paste.const ordinaryLargePaste = 'x'.repeat(200 * 1024)- await manager.handleFrame('web-1', 'terminal_paste', { streamId, text: ordinaryLargePaste })+ await manager.handleBinary('web-1', paste(ordinaryLargePaste))expect(stream.pastes.at(-1)).toBe(ordinaryLargePaste)expect(stream.pastes).toHaveLength(3)-- await manager.handleFrame('web-1', 'terminal_paste', { streamId, text: 'x'.repeat(5 * 1024 * 1024) })- expect(sent.at(-1)?.payload.code).toBe('TERMINAL_PASTE_INVALID')- expect(stream.pastes).toHaveLength(3)})it('does not replay pre-snapshot repaint bytes after the authoritative keyframe', async () => {diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex e9172d550..bc1fa7df6 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -15,13 +15,6 @@ const SYNC_INTERVAL_MS = 5_000const OUTPUT_FLUSH_MS = 8const OUTPUT_CHUNK_BYTES = 32 * 1024const INPUT_MAX_BYTES = 64 * 1024-// A paste is delivered whole, in one frame, unlike ordinary typed input — which the client already-// caps at 8 KiB per binary frame before INPUT_MAX_BYTES ever matters. Reusing INPUT_MAX_BYTES here-// made a large-but-entirely-normal clipboard paste (a few hundred lines of real code, tens of KB)-// bounce off a limit sized for keystrokes and fail the WHOLE stream ("TERMINAL FROZEN") over-// something that never touched tmux. `tmux paste-buffer`'s stdin-loaded buffer has no comparable-// size constraint — this is a sanity ceiling against a broken/malicious client, not a real limit.-const PASTE_MAX_BYTES = 4 * 1024 * 1024const PAUSE_HIGH_WATERMARK_BYTES = 384 * 1024const RESUME_LOW_WATERMARK_BYTES = 128 * 1024const RENDER_STALL_TIMEOUT_MS = 10_000@@ -157,7 +150,10 @@ export class TerminalStreamManager {await this.resize(connId, payload)return truecase 'terminal_paste':- await this.paste(connId, payload)+ // Same reason as terminal_input: a paste is a binary frame (TerminalBinaryKind.paste) so it+ // rides the same AEAD channel every other terminal byte does, which is what makes it safe to+ // deliver over a relayed (E2EE) connection. Nothing sends this as JSON.+ this.sendError(connId, 'TERMINAL_BINARY_REQUIRED', { streamId: typeof payload.streamId === 'string' ? payload.streamId : undefined })return truecase 'terminal_scroll':await this.scroll(connId, payload)@@ -174,9 +170,13 @@ export class TerminalStreamManager {}async handleBinary(connId: string, frame: TerminalBinaryClear): Promise<void> {- if (frame.kind !== TerminalBinaryKind.input) return+ if (frame.kind !== TerminalBinaryKind.input && frame.kind !== TerminalBinaryKind.paste) returnconst state = this.streams.get(frame.streamId)if (!state || state.connId !== connId || state.closing) return+ if (frame.kind === TerminalBinaryKind.paste) {+ await this.paste(state, frame.bytes)+ return+ }await this.input(state, frame.seq, frame.bytes)}@@ -419,27 +419,36 @@ export class TerminalStreamManager {}/**- * A clipboard paste made directly into the terminal (not the composer), delivered whole via- * `TerminalStreamHandle.pasteRaw` instead of the chunked `writeRaw`/`send-keys -H` keystroke path —- * see `pasteRawIntoTmux` for why the two cannot share a pipe. No seq/ordering guard, unlike `input()`:- * a paste is one self-contained unit, not part of an ordered keystroke stream.+ * A clipboard paste made directly into the terminal (not the composer), delivered whole as a+ * `TerminalBinaryKind.paste` frame via `TerminalStreamHandle.pasteRaw` instead of the chunked+ * `writeRaw`/`send-keys -H` keystroke path — see `pasteRawIntoTmux` for why the two cannot share a+ * pipe. Binary, not JSON: this is what lets a paste travel over a relayed (E2EE) connection safely+ * — it rides the same AEAD-wrapped channel `input`/`output` already do, with no allowlist of its+ * own to keep in step with the pairwise-crypto "interop keystone" (e2ee/core.ts) three other+ * codebases also implement.+ *+ * No seq/ordering guard, unlike `input()`: a paste is one self-contained unit, not part of an+ * ordered keystroke stream. Size is already bounded by the wire format itself+ * (TERMINAL_*_PASTE_MAX_*_BYTES in terminalBinary.ts) — anything over that never decodes into a+ * frame at all, so there is nothing left to check here.*/- private async paste(connId: string, payload: FramePayload): Promise<void> {- const state = this.streamFor(connId, payload)- if (!state) return- const text = payload.text- if (typeof text !== 'string' || text.length === 0) {- this.sendError(connId, 'TERMINAL_PASTE_INVALID', { streamId: state.streamId })- return- }- if (Buffer.byteLength(text, 'utf8') > PASTE_MAX_BYTES) {- this.sendError(connId, 'TERMINAL_PASTE_INVALID', { streamId: state.streamId, message: 'paste too large' })+ private async paste(state: ActiveStream, bytes: Uint8Array): Promise<void> {+ if (bytes.length === 0) return+ let text: string+ try {+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)+ } catch {+ this.sendError(state.connId, 'TERMINAL_PASTE_INVALID', { streamId: state.streamId, message: 'paste was not valid UTF-8' })return}+ // Same reason as input(): the engine in the pane has no job-control fallback for an uncaught+ // SIGINT, so a stray 0x03 pasted alongside real content must never reach it.+ if (text.includes('\x03')) text = text.replaceAll('\x03', '')+ if (text.length === 0) returnstate.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MSconst result = await state.handle.pasteRaw(text)if (result.state !== 'succeeded') {- this.sendError(connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })+ this.sendError(state.connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state)}}diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 6fe9ec754..a18ed0654 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -3,13 +3,23 @@ import type http from 'node:http'import type { Socket } from 'node:net'import { WebSocket, WebSocketServer, type RawData } from 'ws'import type { Frame, LocalClientSink } from './backendSocket.js'-import { decodeTerminalLocal, TERMINAL_BINARY_VERSION, type TerminalBinaryClear } from './lib/terminalBinary.js'+import {+ decodeTerminalLocal,+ TERMINAL_BINARY_VERSION,+ TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES,+ type TerminalBinaryClear,+} from './lib/terminalBinary.js'import { RelayConnectError, type RelaySession, type RemoteRelayPool } from './lib/remoteRelay.js'export const LOCAL_WS_PATH = '/api/local-ws'export const LOCAL_WS_PROTOCOL_VERSION = 1const MAX_JSON_BYTES = 512 * 1024+// The `ws` library enforces this on EVERY message on this socket, JSON or binary — so it has to+// cover the largest binary frame this transport carries, not just JSON control frames. That is a+// paste (see TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES in terminalBinary.ts), plus a little slack for+// the local frame header; ordinary JSON frames stay bounded by MAX_JSON_BYTES regardless.+const MAX_WS_MESSAGE_BYTES = TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES + 4_096const HEARTBEAT_MS = 20_000export interface LocalWsBackend {@@ -124,7 +134,7 @@ function binaryBytes(raw: RawData): Uint8Array {export function attachLocalWsServer(server: http.Server, options: LocalWsServerOptions): LocalWsServer {const wss = new WebSocketServer({noServer: true,- maxPayload: MAX_JSON_BYTES,+ maxPayload: MAX_WS_MESSAGE_BYTES,// The loopback endpoint deliberately has no credential. Echo a protocol only for generic WS// clients that insist on proposing one; it carries no authority and is never inspected.handleProtocols: (protocols) => [...protocols][0] ?? false,