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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): namespace relay pty output and gate it to sessions the tab opened
review0ebdb31ca4da
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex f55e4753f..210503d5d 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -74,6 +74,7 @@ function world(opts: WorldOpts = {}) {detach: (id) => { sinks.delete(id) },dispatch: async (_id, req) => {dispatched.push(req.method)+ if (req.method === IPC.ptyCreate) return { t: 'res', id: req.id, ok: true, result: { sessionId: 'sess-shared', fresh: false } }if (req.method === IPC.agentSubagentSnapshot) {return { t: 'res', id: req.id, ok: true, result: [{ nodeId: 'n-shared', task: 'shared task' }, { nodeId: 'n-other', task: 'SECRET other task' }] }}@@ -675,6 +676,12 @@ describe('hosted service — unshare stops a terminal a viewer is already watchiconst eSink = [...w.sinks.values()].at(-1)!const size = (n: number) => JSON.stringify({ t: 'ev', channel: IPC.ptySize('sess-shared'), args: [{ cols: n, rows: n }] })const exit = JSON.stringify({ t: 'ev', channel: IPC.ptyExit('sess-shared'), args: [0] })+ // Both opened the shared terminal: the relay client delivers output only for a session its own+ // `pty:create` answer named (shared/relay-pty-channel.ts).+ for (const [g, id] of [[viewer, 50], [editor, 60]] as const) {+ g.req(id, IPC.ptyCreate, [{ persistKey: 'n-shared', cols: 80, rows: 24 }])+ await vi.waitFor(() => expect(g.res(id)?.result?.sessionId).toBe('sess-shared'))+ }// Both are watching the shared terminal (the PtyManager sends to its subscribers' sinks).for (const s of [vSink, eSink]) {s.sendBinary(encodePtyData('sess-shared', 'before'))diff --git a/src/core/relay/relay-client.ts b/src/core/relay/relay-client.tsindex ca966484b..4c6d71142 100644--- a/src/core/relay/relay-client.ts+++ b/src/core/relay/relay-client.ts@@ -35,6 +35,7 @@ import {} from './relay-trust'import type { KeyPair } from './e2ee'import { decodePtyData } from '../../shared/rpc'+import { createRelayPtyGate } from '../../shared/relay-pty-channel'export interface RelayClientSession {/** The 6-digit SAS both humans compare, or null before the key is derived. */@@ -70,7 +71,10 @@ export interface ConnectRelayClientOptions {/** An inbound rpc.ts TEXT frame from the host (a `res`/`ev`) → forward to the renderer. Trust frames* are consumed by the gate BEFORE this and never delivered here. */onFrame(json: string): void- /** An inbound pty:data BINARY frame → forward as pty output (mirrors the ws-bridge binary path). */+ /** An inbound pty:data BINARY frame → forward as pty output (mirrors the ws-bridge binary path).+ * Only ever called for a HOST session id this connection created (its `pty:create` answer named+ * it); output for any other id is dropped here. The id is the HOST's: the caller must never+ * deliver it on a local per-session channel as-is (see shared/relay-pty-channel.ts). */onPtyData(sessionId: string, data: string): void/** The relay socket dropped (host/relay gone). */onClose(): void@@ -107,6 +111,9 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient// refuses the swap — this is the second, independent check.let sessionPeerKey: string | null = nulllet keySwapped = false+ // The host sessions this connection opened. A hostile host can name ANY session id in a binary+ // frame; only the ids a `pty:create` answer handed us are delivered (shared/relay-pty-channel.ts).+ const ptyGate = createRelayPtyGate()const session: RelayClientSession = {sas: () => gate?.sas() ?? null,@@ -123,6 +130,7 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient},send: (json) => {if (!opened || closed || !socket) return false+ ptyGate.noteOutbound(json)return socket.sendTunnelText(json)},isOpen: () => opened,@@ -166,7 +174,9 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClientif (kind === 'binary') {// Binary is pty output only (mirrors the ws-bridge binary path). Anything undecodable is dropped.const decoded = decodePtyData(payload)- if (decoded) opts.onPtyData(decoded.sessionId, decoded.data)+ // Dropped unless this connection opened that session — a frame for any other id (a local-+ // shaped `pty-1`, a session another guest opened) never leaves this function.+ if (decoded && opened && ptyGate.allows(decoded.sessionId)) opts.onPtyData(decoded.sessionId, decoded.data)return}const json = new TextDecoder().decode(payload)@@ -179,6 +189,7 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient}// Trust frames are consumed here and NEVER forwarded to the renderer's RPC client.if (gate?.onTunnelText(json)) return+ ptyGate.noteInbound(json)opts.onFrame(json)}diff --git a/src/main/index.ts b/src/main/index.tsindex 1f3a4d20b..9a77a697e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -339,6 +339,7 @@ import { createRevoker } from './remote/revocation'import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './remote/approved-devices'import { publicKeyToB64 } from './remote/e2ee'import { connectRelayClient, type RelayClientSession } from './remote/relay-client'+import { relayPtyDataKey } from '../shared/relay-pty-channel'import { decodeOffer } from './remote/pairing'import { isJoinCode } from '../core/relay/join-code'import { connectHostedTeam, removeHostedBookmark } from './remote/hosted-join'@@ -4331,8 +4332,10 @@ app.whenReady().then(async () => {onApproved: () => sendTo(IPC.relayClientApproved(connectionId)),// An inbound rpc frame from the host (res/ev) → the renderer's RpcClient.onFrame: (json) => sendTo(IPC.relayClientFrame(connectionId), json),- // pty output arrives on the SAME per-session channel a local pty uses (ws-bridge binary path).- onPtyData: (sessionId, data) => sendTo(IPC.ptyData(sessionId), data),+ // pty output rides a NAMESPACED per-session channel, never the bare host id: host ids are+ // `pty-<n>` like local ones, and a bare id would land the host's output in a LOCAL xterm+ // (shared/relay-pty-channel.ts). The relay tab subscribes on the same key.+ onPtyData: (sessionId, data) => sendTo(IPC.ptyData(relayPtyDataKey(connectionId, sessionId)), data),onClose: () => {relayClients.delete(connectionId)sendTo(IPC.relayClientClosed(connectionId))diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex 91b5ae835..b792cef6b 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -19,6 +19,7 @@ import { transportPair } from '../../core/relay/transport-pair'import type { PeerAttach } from '../../core/relay/relay-host'import type { RelayTransport } from '../../core/relay/relay-socket'import { IPC } from '../../shared/ipc'+import { relayPtyDataKey } from '../../shared/relay-pty-channel'const tmpDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-join-'))const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)@@ -385,8 +386,10 @@ describe('connectHostedTeam (the relay:client:connect leg for a join code)', ()[IPC.relayClientSas('c1'), '123 456'],[IPC.relayClientApproved('c1')],[IPC.relayClientFrame('c1'), '{"t":"res"}'],- [IPC.ptyData('p1'), 'out']+ // NAMESPACED: the host's `p1` must never land on a local pty's `pty:data:p1` channel.+ [IPC.ptyData(relayPtyDataKey('c1', 'p1')), 'out']])+ expect(x.sent.some(([ch]) => ch === IPC.ptyData('p1'))).toBe(false)})it('a close carries the host\'s refusal reason and unregisters the session', async () => {diff --git a/src/main/remote/hosted-join.ts b/src/main/remote/hosted-join.tsindex f8d32f527..c551105cd 100644--- a/src/main/remote/hosted-join.ts+++ b/src/main/remote/hosted-join.ts@@ -40,6 +40,7 @@ import type { BookmarkStore, RelayBookmark } from './relay-bookmarks'import { IPC } from '../../shared/ipc'import type { RelayClosedReason } from '../../shared/types'import { retryAfterTag, type JoinErrorCode } from '../../shared/relay-join-errors'+import { relayPtyDataKey } from '../../shared/relay-pty-channel'/** What a hosted join hands the relay client: never a pin store. */export type HostedConnectOptions = Omit<ConnectRelayClientOptions, 'pins' | 'transport'>@@ -347,8 +348,9 @@ export async function connectHostedTeam(codeText: string, deps: HostedJoinDeps,onSas: (sas) => io.send(IPC.relayClientSas(connectionId), sas),onApproved: () => io.send(IPC.relayClientApproved(connectionId)),onFrame: (json) => io.send(IPC.relayClientFrame(connectionId), json),- // pty output arrives on the SAME per-session channel a local pty uses.- onPtyData: (sessionId, data) => io.send(IPC.ptyData(sessionId), data),+ // pty output rides a NAMESPACED channel, never the bare host id (shared/relay-pty-channel.ts):+ // the host's `pty-3` is not this machine's `pty-3`.+ onPtyData: (sessionId, data) => io.send(IPC.ptyData(relayPtyDataKey(connectionId, sessionId)), data),onClosed: (reason) => {ended = trueio.sessions.delete(connectionId)diff --git a/src/main/remote/relay-client.test.ts b/src/main/remote/relay-client.test.tsindex 575805816..8ec3b04f9 100644--- a/src/main/remote/relay-client.test.ts+++ b/src/main/remote/relay-client.test.ts@@ -278,9 +278,22 @@ describe('relay client — the frame pipe (tunnel ↔ renderer)', () => {)})+ /** Open a session through the host the way a relay tab does: a `pty:create` req whose answer+ * names the host session id. Only such ids are delivered to onPtyData. */+ const createOnHost = async (p: ReturnType<typeof pairHostAndClient>, reqId: number, sessionId: string) => {+ p.client.send(JSON.stringify({ t: 'req', id: reqId, method: 'pty:create', args: [{ cols: 80, rows: 24 }] }))+ await vi.waitFor(() =>+ expect(p.frames.map((j) => JSON.parse(j))).toContainEqual(+ expect.objectContaining({ t: 'res', id: reqId, ok: true, result: expect.objectContaining({ sessionId }) })+ )+ )+ }+it('forwards a host pty:data BINARY frame to onPtyData (decoded), not to onFrame', async () => {+ platform.handle('pty:create', async () => ({ sessionId: 's1', fresh: false }))const p = pairHostAndClient()await p.openMutually()+ await createOnHost(p, 1, 's1')const id = p.host.clientId()!// The host streams pty output to this client; the peer sink turns it into a BINARY tunnel frame.@@ -290,6 +303,35 @@ describe('relay client — the frame pipe (tunnel ↔ renderer)', () => {// pty:data must not leak onto the JSON frame pipe.expect(p.frames.some((j) => j.includes('hello world'))).toBe(false)})++ it('DROPS host pty output for a session this connection never created (a local-shaped pty-1)', async () => {+ platform.handle('pty:create', async () => ({ sessionId: 'pty-7', fresh: false }))+ const p = pairHostAndClient()+ await p.openMutually()+ const id = p.host.clientId()!++ // Before any create: nothing is delivered, whatever id the host names.+ platform.sendTo(id, 'pty:data:pty-1', 'FAKE PROMPT $ ')+ await createOnHost(p, 3, 'pty-7')+ platform.sendTo(id, 'pty:data:pty-1', '\x1b]52;c;ZXZpbA==\x07')+ platform.sendTo(id, 'pty:data:pty-2', 'nope')+ platform.sendTo(id, 'pty:data:pty-7', 'real output')++ await vi.waitFor(() => expect(p.ptyData).toEqual([{ sessionId: 'pty-7', data: 'real output' }]))+ })++ it('a FAILED pty:create allows nothing', async () => {+ platform.handle('pty:create', async () => {+ throw new Error('no')+ })+ const p = pairHostAndClient()+ await p.openMutually()+ p.client.send(JSON.stringify({ t: 'req', id: 4, method: 'pty:create', args: [{}] }))+ await vi.waitFor(() => expect(p.frames.some((j) => JSON.parse(j).id === 4)).toBe(true))+ platform.sendTo(p.host.clientId()!, 'pty:data:pty-1', 'x')+ await new Promise((r) => setTimeout(r, 20))+ expect(p.ptyData).toEqual([])+ })})describe('relay client — teardown', () => {diff --git a/src/main/remote/relay-pty-namespace.guard.test.ts b/src/main/remote/relay-pty-namespace.guard.test.tsnew file mode 100644index 000000000..a3f475f61--- /dev/null+++ b/src/main/remote/relay-pty-namespace.guard.test.ts@@ -0,0 +1,33 @@+// Source-level pin: every place main hands RELAY pty output to the renderer must use the namespaced+// key (shared/relay-pty-channel.ts). A bare `IPC.ptyData(sessionId)` there typechecks fine and+// delivers a remote host's output into the LOCAL terminal with the same id — the vitest suites for+// hosted-join cover one site, this covers the desktop pairing-offer site in index.ts too.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++const read = (rel: string): string => readFileSync(join(__dirname, '..', '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('relay pty output is always namespaced', () => {+ for (const file of ['main/index.ts', 'main/remote/hosted-join.ts']) {+ it(`${file}: every onPtyData delivery uses relayPtyDataKey`, () => {+ const src = read(file)+ const sites = src.split('\n').filter((l) => /onPtyData:\s*\(/.test(l))+ expect(sites.length).toBeGreaterThan(0)+ for (const line of sites) {+ if (!/IPC\.ptyData\(/.test(line)) continue+ expect(line).toMatch(/IPC\.ptyData\(relayPtyDataKey\(connectionId, sessionId\)\)/)+ }+ })+ }+ for (const file of ['renderer/nodes/TerminalNode.tsx', 'renderer/components/kanban/ModalTerminal.tsx']) {+ it(`${file}: the OSC 52 handler goes through the source policy`, () => {+ const src = read(file)+ const at = src.indexOf('registerOscHandler(52')+ expect(at).toBeGreaterThan(-1)+ const body = src.slice(at, at + 800)+ expect(body).toContain('handleOsc52Write(text, session.source')+ expect(body).not.toMatch(/clipboard\.writeText\(text\)/)+ })+ }+})diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.tsindex 06ef50ecc..968a3281e 100644--- a/src/renderer/bridge/relay-api.test.ts+++ b/src/renderer/bridge/relay-api.test.ts@@ -1,3 +1,4 @@+import { relayPtyDataKey } from '../../shared/relay-pty-channel'import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { IPC } from '../../shared/ipc'import type { NodeTerminalApi } from '../../shared/types'@@ -123,7 +124,7 @@ describe('buildRelayApi', () => {expect(typeof api.dialog.selectFile).toBe('function')})- it('delegates pty.onData to the LOCAL per-session channel, not the RpcClient', () => {+ it('delegates pty.onData to a NAMESPACED local channel, not the RpcClient', () => {const { local, ptyOnData } = fakeLocalApi();(globalThis as Record<string, unknown>).window = { nodeTerminal: local }const t = new FakeTransport()@@ -131,7 +132,9 @@ describe('buildRelayApi', () => {const listener = (): void => {}const unsub = api.pty.onData('sess-1', listener)- expect(ptyOnData).toHaveBeenCalledWith('sess-1', listener)+ // On the connection's NAMESPACED key — never the bare host id, which is a local pty's channel.+ expect(ptyOnData).toHaveBeenCalledWith(relayPtyDataKey('conn-1', 'sess-1'), listener)+ expect(ptyOnData).not.toHaveBeenCalledWith('sess-1', listener)expect(unsub).toBe(LOCAL_ONDATA_UNSUB)// No frame was sent for a subscription — proof it did not route through the relay transport.expect(t.sent).toHaveLength(0)diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 0c0e169f9..47675c58c 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -20,10 +20,11 @@//// ── Two gotchas that make or break the tab ───────────────────────────────────────────────────────// 1. `pty.onData` is the ONE core-bound member that does NOT go through the RpcClient. Relay pty-// output is decoded in the main process and re-emitted on the LOCAL per-session `pty:data`-// channel (`src/main/index.ts` `onPtyData` → `IPC.ptyData(sessionId)` → preload), NOT over the+// output is decoded in the main process and re-emitted on a NAMESPACED local `pty:data` channel+// (`src/main/index.ts` `onPtyData` → `IPC.ptyData(relayPtyDataKey(connectionId, sessionId))` →+// preload — never the bare host id, which a local pty shares), NOT over the// RpcClient frame stream (`RelayFrameTransport.onMessage` only carries JSON frames). So it-// delegates to the LOCAL preload's `pty.onData` — the exact same channel a local pty uses. Wire+// delegates to the LOCAL preload's `pty.onData` — the same preload member a local pty uses, on the namespaced key. Wire// it to the RpcClient instead and the remote terminal is blank.// 2. `RelayFrameTransport.ready()` resolves on `onApproved`, which fires exactly ONCE. The transport// must be constructed (registering that listener) BEFORE the humans confirm the SAS — i.e. Task 6@@ -46,6 +47,7 @@ import {buildGitHubApi} from './ws-bridge'import { buildStubApi } from './stubs'+import { relayPtyDataKey } from '../../shared/relay-pty-channel'import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'/** What Task 6 consumes: the bridged api for `createSession`, an approval gate to await, and a@@ -122,7 +124,9 @@ export function buildRelayApi(// channel, so subscribe on the local preload, same shape as a local pty.pty: {...real.pty,- onData: (sessionId, listener) => local.pty.onData(sessionId, listener)+ // On the NAMESPACED key main delivers relay output on — never the bare host id, which is a+ // LOCAL terminal's channel too (shared/relay-pty-channel.ts).+ onData: (sessionId, listener) => local.pty.onData(relayPtyDataKey(connectionId, sessionId), listener)},// boardLog is CORE-BOUND: a relay guest reads and writes the HOST project's board comments/activitydiff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex a17102fa5..93b193afa 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -35,6 +35,7 @@ import {import { urlLinkMenuItems } from '../../terminal/link-menu'import { ContextMenu } from '../ContextMenu'import { parseOsc52 } from '../../terminal/osc52'+import { createOsc52Notice, dispatchOsc52Toast, handleOsc52Write } from '../../terminal/osc52-policy'import { activateUnicode11 } from '../../terminal/unicode-width'import { useCopyFeedback } from '../../terminal/useCopyFeedback'import {@@ -271,11 +272,17 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere// tmux's mouse is ON, so a drag-select in copy-mode emits OSC 52 to this client; this handler// writes the system clipboard. `parseOsc52` returns null for a `?` read query so a remote program// can never read the local clipboard. Returning true swallows the sequence (also the read query).+ // MIRROR TerminalNode: a RELAY tab's writes are refused (osc52-policy.ts).+ const osc52Notice = createOsc52Notice()term.parser.registerOscHandler(52, (data) => {const text = parseOsc52(data)if (text !== null) {- window.nodeTerminal.clipboard.writeText(text)- copy.notifyCopy(text)+ handleOsc52Write(text, session.source, {+ write: (t) => window.nodeTerminal.clipboard.writeText(t),+ notifyCopied: (t) => copy.notifyCopy(t),+ shouldNotify: osc52Notice,+ toast: dispatchOsc52Toast+ })}return true})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex eae24e2e9..def97d07d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -40,6 +40,7 @@ import { guardMiddleClickPaste } from '../terminal/middle-click'import { patchTerminalScale } from '../terminal/scale-fix'import { focusedNodeId, subscribeFocusedNode, focusSurfaceEl } from '../state/focusNode'import { parseOsc52 } from '../terminal/osc52'+import { createOsc52Notice, dispatchOsc52Toast, handleOsc52Write } from '../terminal/osc52-policy'import { activateUnicode11 } from '../terminal/unicode-width'import {createFileLinkProvider,@@ -3090,12 +3091,19 @@ export function TerminalNode({// The emulator's own Cmd+C / Ctrl+Shift+C chords (below) stay for a selection xterm owns.// WRITE-ONLY — `parseOsc52` returns null for a `?` read query so a remote program can never// read the local clipboard. Returning true swallows the sequence (also the read query).+ // A RELAY tab's stream is another person's core: its writes are refused (osc52-policy.ts —+ // paste-jacking). Local and SSH-project terminals (source 'local') are untouched.+ const osc52Notice = createOsc52Notice()term.parser.registerOscHandler(52, (data) => {const text = parseOsc52(data)if (text !== null) {- window.nodeTerminal.clipboard.writeText(text)- // Through the registry, never a captured setState: this handler outlives a park.- copySubs.get(termKey)?.(text)+ handleOsc52Write(text, session.source, {+ write: (t) => window.nodeTerminal.clipboard.writeText(t),+ // Through the registry, never a captured setState: this handler outlives a park.+ notifyCopied: (t) => copySubs.get(termKey)?.(t),+ shouldNotify: osc52Notice,+ toast: dispatchOsc52Toast+ })}return true})diff --git a/src/renderer/terminal/osc52-policy.test.ts b/src/renderer/terminal/osc52-policy.test.tsnew file mode 100644index 000000000..0670f84d6--- /dev/null+++ b/src/renderer/terminal/osc52-policy.test.ts@@ -0,0 +1,38 @@+import { describe, it, expect, vi } from 'vitest'+import { createOsc52Notice, handleOsc52Write, osc52BlockedMessage, osc52Decision, OSC52_NOTICE_INTERVAL_MS } from './osc52-policy'++function deps() {+ return { write: vi.fn(), notifyCopied: vi.fn(), shouldNotify: vi.fn(() => true), toast: vi.fn() }+}++describe('OSC 52 policy', () => {+ it('a LOCAL session (incl. SSH projects and the Server Edition) writes exactly as before', () => {+ const d = deps()+ expect(osc52Decision('local')).toBe('write')+ expect(handleOsc52Write('hi', 'local', d)).toBe(true)+ expect(d.write).toHaveBeenCalledWith('hi')+ expect(d.notifyCopied).toHaveBeenCalledWith('hi')+ expect(d.toast).not.toHaveBeenCalled()+ })+ it('a RELAY session never writes the clipboard, and says so', () => {+ const d = deps()+ expect(osc52Decision('relay')).toBe('block')+ expect(handleOsc52Write('rm -rf ~\n', 'relay', d)).toBe(false)+ expect(d.write).not.toHaveBeenCalled()+ expect(d.notifyCopied).not.toHaveBeenCalled()+ expect(d.toast).toHaveBeenCalledWith(osc52BlockedMessage())+ })+ it('the notice is throttled per terminal', () => {+ let t = 0+ const n = createOsc52Notice(() => t)+ expect(n()).toBe(true)+ t = OSC52_NOTICE_INTERVAL_MS - 1+ expect(n()).toBe(false)+ t = OSC52_NOTICE_INTERVAL_MS+ expect(n()).toBe(true)+ })+ it('names the platform escape', () => {+ expect(osc52BlockedMessage(true)).toContain('⌥')+ expect(osc52BlockedMessage(false)).toContain('Ctrl+Shift+C')+ })+})diff --git a/src/renderer/terminal/osc52-policy.ts b/src/renderer/terminal/osc52-policy.tsnew file mode 100644index 000000000..c53b421f0--- /dev/null+++ b/src/renderer/terminal/osc52-policy.ts@@ -0,0 +1,63 @@+// Who may write THIS machine's clipboard through OSC 52.+//+// OSC 52 is the terminal's clipboard-write sequence: whatever byte stream the pane emits can put+// text on the system clipboard, with no gesture from the person at the keyboard. For a LOCAL core+// and for an SSH project that stream comes from the user's own machines, and it is the primary copy+// path (tmux copy-mode emits OSC 52 on a drag-select), so it stays exactly as it was.+//+// A relay tab is different: the stream comes from ANOTHER person's core. A hostile or compromised+// host can write the clipboard silently — the classic paste-jacking setup, where a harmless-looking+// copy is replaced by a command that runs when the user pastes it into a shell. So for any+// non-local source the write is REFUSED, and the user is told once per burst, because a copy that+// silently does nothing reads as broken. Chosen over a confirm prompt because the prompt would+// fire on every tmux drag in a relay tab and train the user to click Allow without reading — the+// consent would be worth nothing. The escape is the emulator's own selection (hold Option / Shift+// while dragging, then Cmd+C / Ctrl+Shift+C), which is a gesture on this machine.++import { isMacPlatform } from '@shared/platform-utils'+import type { SessionSource } from '../session/session'++export type Osc52Decision = 'write' | 'block'++export function osc52Decision(source: SessionSource): Osc52Decision {+ return source === 'local' ? 'write' : 'block'+}++export function osc52BlockedMessage(mac: boolean = isMacPlatform()): string {+ const mod = mac ? '⌥' : 'Shift'+ const copy = mac ? '⌘C' : 'Ctrl+Shift+C'+ return `Blocked a clipboard write from the remote host. To copy from this terminal, hold ${mod} while selecting, then press ${copy}.`+}++/** At most one notice per terminal in this window, so a burst of writes is one toast. */+export const OSC52_NOTICE_INTERVAL_MS = 10_000++/** Build the per-terminal notice throttle. `now` is a test seam. */+export function createOsc52Notice(now: () => number = Date.now): () => boolean {+ let last = -Infinity+ return () => {+ const t = now()+ if (t - last < OSC52_NOTICE_INTERVAL_MS) return false+ last = t+ return true+ }+}++/** Apply the policy to one decoded OSC 52 write. Returns true when the clipboard was written. */+export function handleOsc52Write(+ text: string,+ source: SessionSource,+ deps: { write(text: string): void; notifyCopied(text: string): void; shouldNotify(): boolean; toast(message: string): void }+): boolean {+ if (osc52Decision(source) === 'write') {+ deps.write(text)+ deps.notifyCopied(text)+ return true+ }+ if (deps.shouldNotify()) deps.toast(osc52BlockedMessage())+ return false+}++export function dispatchOsc52Toast(message: string): void {+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))+}diff --git a/src/shared/relay-pty-channel.test.ts b/src/shared/relay-pty-channel.test.tsnew file mode 100644index 000000000..1d3b7a353--- /dev/null+++ b/src/shared/relay-pty-channel.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect } from 'vitest'+import { IPC } from './ipc'+import { createRelayPtyGate, relayPtyDataKey, RELAY_PTY_ALLOW_MAX } from './relay-pty-channel'++const req = (id: number, method = 'pty:create') => JSON.stringify({ t: 'req', id, method, args: [{}] })+const ok = (id: number, result: unknown) => JSON.stringify({ t: 'res', id, ok: true, result })++describe('relayPtyDataKey', () => {+ it('never equals a local-shaped id, whatever the host names', () => {+ for (const hostId of ['pty-1', 'pty-42', '', 'relay:x']) {+ const key = relayPtyDataKey('conn-1', hostId)+ expect(key).not.toBe(hostId)+ expect(key.startsWith('relay:conn-1:')).toBe(true)+ expect(IPC.ptyData(key)).not.toBe(IPC.ptyData('pty-1'))+ }+ })+ it('separates two connections naming the same host id', () => {+ expect(relayPtyDataKey('a', 'pty-1')).not.toBe(relayPtyDataKey('b', 'pty-1'))+ })+})++describe('createRelayPtyGate', () => {+ it('allows nothing until a pty:create this connection sent is answered', () => {+ const g = createRelayPtyGate()+ expect(g.allows('pty-1')).toBe(false)+ // An answer to a request we never sent is ignored (a host inventing a create reply).+ g.noteInbound(ok(9, { sessionId: 'pty-1' }))+ expect(g.allows('pty-1')).toBe(false)+ g.noteOutbound(req(9))+ g.noteInbound(ok(9, { sessionId: 'pty-3' }))+ expect(g.allows('pty-3')).toBe(true)+ expect(g.allows('pty-1')).toBe(false)+ })+ it('ignores answers to other methods, failures, and malformed ids', () => {+ const g = createRelayPtyGate()+ g.noteOutbound(req(1, 'fs:list'))+ g.noteInbound(ok(1, { sessionId: 'pty-1' }))+ g.noteOutbound(req(2))+ g.noteInbound(JSON.stringify({ t: 'res', id: 2, ok: false, error: { code: 'x', message: 'y' } }))+ g.noteOutbound(req(3))+ g.noteInbound(ok(3, { sessionId: 5 }))+ g.noteOutbound(req(4))+ g.noteInbound('not json')+ g.noteInbound(ok(4, null))+ expect(g.allows('pty-1')).toBe(false)+ expect(g.allows('5')).toBe(false)+ })+ it('an answered request id is spent: a second answer adds nothing', () => {+ const g = createRelayPtyGate()+ g.noteOutbound(req(1))+ g.noteInbound(ok(1, { sessionId: 'pty-1' }))+ g.noteInbound(ok(1, { sessionId: 'pty-2' }))+ expect(g.allows('pty-2')).toBe(false)+ })+ it('is bounded: the oldest id is forgotten past the cap', () => {+ const g = createRelayPtyGate()+ for (let i = 0; i <= RELAY_PTY_ALLOW_MAX; i++) {+ g.noteOutbound(req(i))+ g.noteInbound(ok(i, { sessionId: `s${i}` }))+ }+ expect(g.allows('s0')).toBe(false)+ expect(g.allows(`s${RELAY_PTY_ALLOW_MAX}`)).toBe(true)+ })+})diff --git a/src/shared/relay-pty-channel.ts b/src/shared/relay-pty-channel.tsnew file mode 100644index 000000000..495cbb97c--- /dev/null+++ b/src/shared/relay-pty-channel.ts@@ -0,0 +1,87 @@+// Where a relay tab's pty output is delivered inside THIS machine, and which host sessions it may+// be delivered for at all.+//+// A relay connection is a pipe to ANOTHER machine's core. Its pty output is decoded in main and+// handed to the renderer over Electron IPC — and the obvious channel, `pty:data:<sessionId>`, is the+// one every LOCAL terminal listens on. Session ids are per-core sequential (`pty-${++counter}`), so+// the host's `pty-3` and this machine's `pty-3` are the same string: the host's output landed in a+// local xterm, and a hostile host could name `pty-1..N` on purpose to paint fake prompts, write the+// clipboard through OSC 52, or provoke xterm query replies (DA/DSR) that the LOCAL xterm then types+// into the LOCAL shell.+//+// Two independent rules close that:+// 1. NAMESPACE. Relay output never uses a bare session id as its channel key. The key is+// `relay:<connectionId>:<hostSessionId>`, and no local id can take that shape (local ids are+// minted by `PtyManager` as `pty-<n>`), so a relay frame cannot reach a local subscriber by+// construction — whatever id the host writes. Only the main→renderer DATA channel carries it:+// every call the relay tab makes (write/resize/kill/…) rides that connection's own RpcClient+// with the host's own id, and every other per-session event (exit/size/closed/recycled/resync)+// already arrives as an `ev` frame inside the connection's own RpcClient, so neither direction+// needs a translation table.+// 2. ALLOWLIST. A host frame is delivered only for a session THIS connection opened: the id came+// back in the answer to a `pty:create` request this connection sent. Anything else is dropped+// in main, before IPC. (Rule 1 alone would already make a stray id harmless — nobody listens on+// it — so this is defence in depth, and it keeps a host from streaming into ids a relay tab has+// not asked for.)++/** Prefix no local pty session id can start with. */+export const RELAY_PTY_KEY_PREFIX = 'relay:'++/** The pty-data channel key for a relay connection's host session. Always namespaced; never a+ * bare host id. */+export function relayPtyDataKey(connectionId: string, hostSessionId: string): string {+ return `${RELAY_PTY_KEY_PREFIX}${connectionId}:${hostSessionId}`+}++/** Upper bound on remembered sessions per connection: a hostile host answering every create with a+ * fresh id cannot grow this without limit. Past it the OLDEST entry is forgotten. */+export const RELAY_PTY_ALLOW_MAX = 4096+/** Bound on `pty:create` requests awaiting an answer (a host that never answers). */+const PENDING_MAX = 1024++export interface RelayPtyGate {+ /** An outbound rpc frame (JSON) this connection is sending to the host. */+ noteOutbound(json: string): void+ /** An inbound rpc frame (JSON) from the host, seen before it is forwarded. */+ noteInbound(json: string): void+ /** May pty output for this HOST session id be delivered? */+ allows(hostSessionId: string): boolean+}++const PTY_CREATE = 'pty:create'++function parse(json: string): Record<string, unknown> | null {+ try {+ const v: unknown = JSON.parse(json)+ return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null+ } catch {+ return null+ }+}++/** A per-connection record of the host sessions this connection created or attached. */+export function createRelayPtyGate(): RelayPtyGate {+ const pending = new Set<number>()+ const allowed = new Set<string>()+ return {+ noteOutbound(json) {+ const m = parse(json)+ if (!m || m.t !== 'req' || m.method !== PTY_CREATE || typeof m.id !== 'number') return+ if (pending.size >= PENDING_MAX) pending.delete(pending.values().next().value as number)+ pending.add(m.id)+ },+ noteInbound(json) {+ const m = parse(json)+ if (!m || m.t !== 'res' || typeof m.id !== 'number' || !pending.has(m.id)) return+ pending.delete(m.id)+ if (m.ok !== true) return+ const result = m.result as { sessionId?: unknown } | null | undefined+ const sid = result && typeof result === 'object' ? result.sessionId : undefined+ if (typeof sid !== 'string' || sid.length === 0 || sid.length > 256) return+ if (allowed.has(sid)) return+ if (allowed.size >= RELAY_PTY_ALLOW_MAX) allowed.delete(allowed.values().next().value as string)+ allowed.add(sid)+ },+ allows: (sid) => allowed.has(sid)+ }+}