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): a relay tab never makes the guest dial SSH
review6012b9836ece
diff --git a/src/core/remote-ssh/control-master.destination.test.ts b/src/core/remote-ssh/control-master.destination.test.tsnew file mode 100644index 000000000..a16151fcf--- /dev/null+++ b/src/core/remote-ssh/control-master.destination.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { checkMasterArgs, childArgs, masterArgs, sshDestination } from './control-master'++/**+ * SECURITY: the `user@host` destination is one argv element, and ssh parses an element starting+ * with `-` as an OPTION — `-oProxyCommand=<cmd>@host` runs `<cmd>` on THIS machine. The endpoint+ * can come from a hand-edited project file or another machine, so the leaf refuses it.+ */+describe('sshDestination', () => {+ it('builds user@host for an ordinary endpoint', () => {+ expect(sshDestination({ user: 'corvin', host: 'devbox.example' })).toBe('[email protected]')+ expect(sshDestination({ user: 'deploy', host: '10.0.0.7' })).toBe('[email protected]')+ })++ it('refuses a user or host that ssh would read as an option', () => {+ expect(() => sshDestination({ user: '-oProxyCommand=touch /tmp/x', host: 'h' })).toThrow(/refusing ssh user/)+ expect(() => sshDestination({ user: 'u', host: '-oProxyCommand=x' })).toThrow(/refusing ssh host/)+ })++ it('refuses whitespace and control characters', () => {+ expect(() => sshDestination({ user: 'a b', host: 'h' })).toThrow()+ expect(() => sshDestination({ user: 'u', host: 'h\nx' })).toThrow()+ expect(() => sshDestination({ user: 'u', host: 'h\u0000' })).toThrow()+ expect(() => sshDestination({ user: 'u', host: '' })).toThrow()+ })++ it('every argv builder goes through it', () => {+ const bad = { user: '-oProxyCommand=x', host: 'h' }+ expect(() => masterArgs(bad, '/cp')).toThrow(/refusing/)+ expect(() => childArgs(bad, '/cp', 'true')).toThrow(/refusing/)+ expect(() => checkMasterArgs(bad, '/cp')).toThrow(/refusing/)+ })+})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 50eec55d6..d1ca58041 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -50,10 +50,27 @@ export function controlPathFor(projectId: string): string {return path.join(os.homedir(), '.nodeterm', 'ssh-cm', `${id}.sock`)}-function target(conn: SshConnection): string {+/**+ * One `user@host` destination argv element, refused when it could be anything else. A leading `-`+ * makes ssh parse the whole element as an OPTION (`-oProxyCommand=…@host` runs a local command), and+ * whitespace or a control character is never part of a real user or host name. Every argv this module+ * builds passes through here, so no caller — a hand-edited project file, a relay peer, a future+ * dialog — can turn an endpoint into ssh options.+ */+export function sshDestination(conn: Pick<SshConnection, 'user' | 'host'>): string {+ for (const [field, v] of [['user', conn.user], ['host', conn.host]] as const) {+ // eslint-disable-next-line no-control-regex+ if (typeof v !== 'string' || (field === 'host' && v === '') || v.startsWith('-') || /[\s\u0000-\u001f\u007f]/.test(v)) {+ throw new Error(`refusing ssh ${field} ${JSON.stringify(String(v)).slice(0, 80)}: not a valid ${field}`)+ }+ }return `${conn.user}@${conn.host}`}+function target(conn: SshConnection): string {+ return sshDestination(conn)+}+function portArgs(conn: SshConnection): string[] {return ['-p', String(conn.port ?? 22)]}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 7006c1619..3ac1a7776 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -75,8 +75,10 @@ import {useSharedGlyphActive} from './SharedGlyphLayer'import { SshReconnector } from '../lib/sshReconnect'+import { projectMayDialSsh, sanitizeRelayMutation } from '../session/relay-ssh'import {hostAttachmentsFor,+ planActiveProjectDials,connectHostAttachment,type SshConnectFn} from '../lib/sshAttachments'@@ -2829,8 +2831,11 @@ export function Canvas() {// SSH project: (re)open its ControlMaster and record the controlPath so this project's// terminal nodes can run over it. Idempotent in main (a live master is reused), so a tab// switch back to a connected project is a no-op. Remote tmux is unaffected by the master.- if (project.ssh) {- const ssh = project.ssh+ // A RELAY tab dials nothing (`planActiveProjectDials`): its project and nodes are another+ // machine's, and connecting them would log THIS machine into a server the host named.+ const dials = planActiveProjectDials(project)+ if (dials.own) {+ const ssh = dials.own// SSH remote projects are free (Core). Only phone/relay remote access is Pro-gated.window.nodeTerminal.sshProject.connect(project.id, ssh.server, ssh.remoteCwd)@@ -2857,7 +2862,7 @@ export function Canvas() {// locally.// NOTE: git routing is deliberately NOT armed for an attachment. The project's own cwd is what// the Source Control panel is about, and an attached node must not repoint it at another host.- for (const attachment of hostAttachmentsFor(project.id, project.nodes, project.ssh?.server)) {+ for (const attachment of dials.attachments) {void connectHostAttachment(attachment.scopeId,{@@ -3729,7 +3734,10 @@ export function Canvas() {// mount-time local one (the bug). Byte-identical on a local tab (`activeSession.api` IS// `window.nodeTerminal`). Re-keyed on the api OBJECT below, in lockstep with the publisher, so a// tab switch tears down + re-binds both together (and a local→local switch does neither).- return activeSession.api.canvas.onMutation((projectId, mutation) => {+ const relay = activeSession.source === 'relay'+ return activeSession.api.canvas.onMutation((projectId, incoming) => {+ // A relay peer's node never brings a dial-capable SSH connection onto this machine.+ const mutation = relay ? sanitizeRelayMutation(incoming) : incominghasPeersRef.current = true // proof of a peer, whatever the presence table saysif (!orderRef.current?.accept(mutation)) returnif (projectId !== useProjects.getState().activeProjectId) {@@ -3774,7 +3782,7 @@ export function Canvas() {setNodes(flow)markDirty()})- }, [activeSession.api, setNodes, markDirty, publishableLater])+ }, [activeSession.api, activeSession.source, setNodes, markDirty, publishableLater])// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).useEffect(() => {@@ -15195,7 +15203,8 @@ export function Canvas() {if (attached) return connectHostAttachment(scopeId, attached, sshConnect, sshDisconnect)const projectId = scopeIdconst project = useProjects.getState().getProject(projectId)- if (!project?.ssh) return false+ // Never a relay tab's endpoint — see session/relay-ssh.ts.+ if (!project?.ssh || !projectMayDialSsh(project)) return falseconst ssh = project.ssh// Same post-connect sequence as the active-project effect: arm remote git routing first// (only if this project is still the active tab), then record the connection info.diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex 5d5358707..e9c564d07 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -350,7 +350,9 @@ export function TabBar({: `${p.name} disconnected, click to reconnect`: p.ssh? `${p.ssh.server.user}@${p.ssh.server.host}:${p.ssh.remoteCwd}`- : p.cwd || undefined+ : p.relaySsh+ ? `${p.relaySsh.user}@${p.relaySsh.host}:${p.relaySsh.remoteCwd}`+ : p.cwd || undefined}><ProjectGlyph@@ -370,6 +372,12 @@ export function TabBar({SSH</span>)}+ {/* A relay tab of the host's SSH project: display strings only (relay-ssh.ts). */}+ {!p.ssh && p.relaySsh && (+ <span className="tab__ssh" title={`${p.relaySsh.user}@${p.relaySsh.host}`}>+ SSH+ </span>+ )}{editingId === p.id ? (<inputclassName="tab__edit"diff --git a/src/renderer/lib/sshAttachments.test.ts b/src/renderer/lib/sshAttachments.test.tsindex 5c4bef0c0..123bed0f9 100644--- a/src/renderer/lib/sshAttachments.test.ts+++ b/src/renderer/lib/sshAttachments.test.ts@@ -1,9 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import { sshAttachmentId, type SshConnection } from '@shared/ssh'import { useSshConn } from '../state/sshConn'+import { useProjects } from '../state/projects'+import type { Project } from '@shared/types'import {connectHostAttachment,hostAttachmentsFor,+ planActiveProjectDials,resetHostAttachmentDials,type AttachableNode} from './sshAttachments'@@ -191,3 +194,47 @@ describe('connectHostAttachment', () => {expect(connect).toHaveBeenCalledTimes(2)})})++// SECURITY: a relay tab's project belongs to ANOTHER machine. Even if one somehow carries `ssh`+// (the adopt boundary strips it — session/relay-ssh.ts), THIS machine must never dial it.+describe('relay tabs never dial guest-side SSH', () => {+ beforeEach(() => {+ resetHostAttachmentDials()+ useSshConn.setState({ byProject: {}, attachments: {} } as never)+ })++ it('planActiveProjectDials opens the own master and attachments of a normal project', () => {+ const plan = planActiveProjectDials({+ id: 'ssh-1',+ ssh: { server: DEVBOX, remoteCwd: '/srv' },+ nodes: [remote('n1', OTHER)]+ })+ expect(plan.own?.server).toBe(DEVBOX)+ expect(plan.attachments).toHaveLength(1)+ })++ it('planActiveProjectDials opens NOTHING for a relay project, whatever it carries', () => {+ const plan = planActiveProjectDials({+ id: 'relay-1',+ remote: true,+ ssh: { server: DEVBOX, remoteCwd: '/srv' },+ nodes: [remote('n1', OTHER)]+ })+ expect(plan).toEqual({ own: null, attachments: [] })+ })++ it('connectHostAttachment refuses an attachment owned by a relay tab (no dial, no registration)', async () => {+ const relay = { id: 'relay-1', name: 'R', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [], remote: true } as Project+ useProjects.setState({ projects: [relay] })+ const connect = vi.fn()+ const scope = sshAttachmentId('relay-1', OTHER)+ const ok = await connectHostAttachment(+ scope,+ { conn: OTHER, hostKey: 'corvin@other', ownerProjectId: 'relay-1' },+ connect+ )+ expect(ok).toBe(false)+ expect(connect).not.toHaveBeenCalled()+ expect(useSshConn.getState().getAttachment(scope)).toBeUndefined()+ })+})diff --git a/src/renderer/lib/sshAttachments.ts b/src/renderer/lib/sshAttachments.tsindex 2005dc375..d0ca7df24 100644--- a/src/renderer/lib/sshAttachments.ts+++ b/src/renderer/lib/sshAttachments.ts@@ -1,5 +1,7 @@import { sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'import { useSshConn, type SshAttachment, type SshConnInfo } from '../state/sshConn'+import { useProjects } from '../state/projects'+import { projectMayDialSsh } from '../session/relay-ssh'/** One host a project's canvas has REMOTE nodes on, other than the project's own endpoint. */export interface HostAttachment {@@ -104,6 +106,13 @@ export function connectHostAttachment(connect: SshConnectFn,disconnect?: (scopeId: string) => Promise<unknown>): Promise<boolean> {+ // A host attachment OWNED by a relay tab is another machine's node: never dialed from here, and+ // never registered either — a registration is what the reconnect coordinator would redial.+ if (+ attachment.ownerProjectId &&+ !projectMayDialSsh(useProjects.getState().getProject(attachment.ownerProjectId))+ )+ return Promise.resolve(false)useSshConn.getState().registerAttachment(scopeId, attachment)const inFlight = dialing.get(scopeId)if (inFlight) return inFlight@@ -133,3 +142,23 @@ export function connectHostAttachment(export function resetHostAttachmentDials(): void {dialing.clear()}++/**+ * Every ControlMaster the active-project effect opens for `project`: its own endpoint (when it is an+ * SSH project) and its host attachments. A RELAY tab opens NOTHING, whatever it carries — its+ * project and nodes belong to another machine, and dialing them would log THIS machine into a+ * server the host named, with this machine's keys (see session/relay-ssh.ts). The relay adopt+ * boundary already strips the connections; this is the second, independent half.+ */+export function planActiveProjectDials(project: {+ id: string+ remote?: boolean+ ssh?: { server: SshConnection; remoteCwd: string }+ nodes: readonly AttachableNode[]+}): { own: { server: SshConnection; remoteCwd: string } | null; attachments: HostAttachment[] } {+ if (!projectMayDialSsh(project)) return { own: null, attachments: [] }+ return {+ own: project.ssh ?? null,+ attachments: hostAttachmentsFor(project.id, project.nodes, project.ssh?.server)+ }+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex eae24e2e9..2d81e8e32 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -302,6 +302,7 @@ import { nodeIconDialog } from '../components/NodeIconPicker'import { applyIconChoice } from '../lib/nodeIconChoice'import type { NodeIcon } from '@shared/node-icon'import { connectHostAttachment } from '../lib/sshAttachments'+import { projectMayDialSsh } from '../session/relay-ssh'import { waitForSshRemote } from '../lib/sshRemoteWait'/** Which physical modifier the registry's abstract `Cmd` resolves to for the find-bar chord. */@@ -440,6 +441,10 @@ export async function resolveSshRemote(| undefined> {const activeProjectId = useProjects.getState().activeProjectId+ // A relay tab's node belongs to another machine: never dial or wait for a master for it here+ // (session/relay-ssh.ts). The caller treats undefined as "no master"; the relay spawn path does+ // not call this at all — this is the second half.+ if (!projectMayDialSsh(useProjects.getState().getProject(activeProjectId))) return undefinedconst projectId = sshConnectionScope(conn)// A HOST ATTACHMENT dials for itself, HERE, because nothing else will. Canvas's active-project// effect pre-warms the attachments it can SEE in the stored canvas, but a node created at@@ -3334,6 +3339,10 @@ export function TerminalNode({// `ssh` as a LOCAL pty program. Only the latter sets shell:'ssh' + buildSshArgs.const sshRemoteTmux = !!data.sshRemoteTmuxconst localSsh = !!ssh && !sshRemoteTmux+ // A RELAY tab's SSH-project node lives on the HOST's side: this machine never dials for it+ // (session/relay-ssh.ts). Its create goes to the host's core with `requireRemote`, which joins+ // the session when the host holds it live and refuses otherwise — never a local spawn.+ const dialsSsh = sshRemoteTmux && session.source !== 'relay'// Connection SCOPE of a remote terminal, captured at spawn time for the exit-255 drop report// below. Same choice `resolveSshRemote` makes: the owning project for an SSH project's own// node, the host attachment for a node attached to another endpoint — so the reconnect@@ -3367,14 +3376,14 @@ export function TerminalNode({// or an unreachable host, and a terminal that is silently blank for that long reads as// broken. Only when there is nothing to wait FOR is nothing printed (the common case: the// master is already up and this resolves in a microtask).- if (sshRemoteTmux && ssh && !currentControlPath(ssh)) {+ if (dialsSsh && ssh && !currentControlPath(ssh)) {// Drop the overlay for the duration of the attempt (this respawn IS the retry the user or// the coordinator asked for) so the line below is visible; it comes back if we fail.setCo(termKey, { offline: false })term.write(`\x1b[90m[connecting to ${ssh.user}@${ssh.host}…]\x1b[0m\r\n`)}const sshRemote =- sshRemoteTmux && ssh+ dialsSsh && ssh? await resolveSshRemote(ssh, data.cwd as string | undefined, { nodeId: id, pty: api.pty }): undefinedif (disposed) return@@ -3384,7 +3393,7 @@ export function TerminalNode({// scrollback snapshot, and (agent nodes) running the cold-restore `--resume` on the wrong// machine. `requireRemote` below refuses the same thing core-side; this is the near half,// which also saves the round-trip. Report the node so the reconnect coordinator retries.- if (sshRemoteTmux && !sshRemote) {+ if (dialsSsh && !sshRemote) {setCo(termKey, { offline: true })term.write(`\r\n\x1b[90m[not connected — this session lives on ${ssh ? `${ssh.user}@${ssh.host}` : 'the remote host'}; nothing was started locally]\x1b[0m\r\n`@@ -3488,7 +3497,7 @@ export function TerminalNode({: { offline: false, spawnError: refusal.message })if (!disposed) term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)- if (refusal.connectionLost && sshProjectId) reportSshDrop(sshProjectId, id)+ if (refusal.connectionLost && sshProjectId && dialsSsh) reportSshDrop(sshProjectId, id)return}// REFUSED: core's tombstone says another client deleted this node while we weren't@@ -3757,7 +3766,7 @@ export function TerminalNode({// ssh exiting 255 on an SSH-project terminal is a CONNECTION drop (sleep/wake,// network change, NAT idle) — the remote tmux session survives. Report it so the// reconnect coordinator can re-establish the master and respawn this node.- if (code === 255 && sshProjectId) sshDropHandler?.(sshProjectId, id)+ if (code === 255 && sshProjectId && dialsSsh) sshDropHandler?.(sshProjectId, id)}))cleanups.push(diff --git a/src/renderer/session/relay-ssh.test.ts b/src/renderer/session/relay-ssh.test.tsnew file mode 100644index 000000000..ebc0151ef--- /dev/null+++ b/src/renderer/session/relay-ssh.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest'+import type { CanvasNodeState, Project } from '@shared/types'+import { projectMayDialSsh, sanitizeRelayMutation, sanitizeRelayNode, sanitizeRelayProject } from './relay-ssh'++const EVIL = { host: 'evil.example', user: 'me', identityFile: '/home/me/.ssh/id_ed25519', extraArgs: '-A' }++const node = (over: Partial<CanvasNodeState>): CanvasNodeState =>+ ({ id: 'n1', kind: 'terminal', title: 'T', color: '#111', position: { x: 0, y: 0 }, ...over }) as CanvasNodeState++describe('relay-ssh', () => {+ it('strips the host project\'s ssh endpoint, keeping display strings only', () => {+ const p = sanitizeRelayProject({+ id: 'p',+ name: 'P',+ color: '#fff',+ viewport: { x: 0, y: 0, zoom: 1 },+ ssh: { server: EVIL, remoteCwd: '/srv' },+ nodes: [node({ ssh: EVIL, sshRemoteTmux: true })]+ } as Project)+ expect(p.ssh).toBeUndefined()+ expect(p.remote).toBe(true)+ expect(p.relaySsh).toEqual({ user: 'me', host: 'evil.example', remoteCwd: '/srv' })+ expect(p.nodes[0].ssh).toBeUndefined()+ expect(p.nodes[0].sshRemoteTmux).toBe(true) // still requireRemote on the host's core+ expect(JSON.stringify(p)).not.toContain('id_ed25519')+ })++ it('sanitizes display strings from the other machine', () => {+ const p = sanitizeRelayProject({+ id: 'p', name: 'P', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],+ ssh: { server: { host: 'h\u001b[31m', user: 'u' }, remoteCwd: '/x' }+ } as Project)+ expect(p.relaySsh?.host).toBe('h[31m')+ })++ it('a plain ssh-terminal node (runs ssh on the HOST core) is left alone', () => {+ const n = node({ ssh: EVIL })+ expect(sanitizeRelayNode(n)).toBe(n)+ })++ it('strips upserts arriving on a relay session', () => {+ const m = sanitizeRelayMutation({ op: 'upsert', node: node({ ssh: EVIL, sshRemoteTmux: true }), seq: 3 })+ expect(m.op === 'upsert' && m.node.ssh).toBeFalsy()+ expect(m.op === 'upsert' && m.seq).toBe(3)+ const rm = { op: 'remove' as const, id: 'n1' }+ expect(sanitizeRelayMutation(rm)).toBe(rm)+ })++ it('projectMayDialSsh refuses exactly relay projects', () => {+ expect(projectMayDialSsh({ remote: true })).toBe(false)+ expect(projectMayDialSsh({})).toBe(true)+ expect(projectMayDialSsh(undefined)).toBe(true)+ })+})diff --git a/src/renderer/session/relay-ssh.ts b/src/renderer/session/relay-ssh.tsnew file mode 100644index 000000000..cd84427b9--- /dev/null+++ b/src/renderer/session/relay-ssh.ts@@ -0,0 +1,82 @@+import type { CanvasMutation, CanvasNodeState, Project } from '@shared/types'++/**+ * A relay tab must never make THIS machine dial SSH.+ *+ * A relay tab shows another machine's project. When that project is an SSH project, its+ * `ssh.server` (host, user, port, identity file, extra args) is the HOST's connection, and every+ * guest-side consumer of it — the active-project connect, the host-attachment pre-warm, the+ * reconnect coordinator, a terminal's `resolveSshRemote` — dials through this machine's own+ * preload, i.e. with this machine's keys and agent, then runs the whole post-connect routine+ * (hook and shim installs, a reverse tunnel back into this machine's hook server) on whatever box+ * the host named. The host is not trusted with that: a malicious host names its own box and+ * harvests an authenticated session. Even an honest host's endpoint is wrong here — the guest has+ * no business logging into the host's SSH server with the guest's credentials.+ *+ * So the connection objects are removed at every relay ingest point (`sanitizeRelayProject`,+ * `sanitizeRelayMutation`) and each dial site ALSO refuses a relay project on its own+ * (`projectMayDialSsh`) — defence in depth: either half alone closes the hole.+ *+ * What survives:+ * - `sshRemoteTmux` on a node — a plain boolean. It keeps `requireRemote` on the create the tab+ * sends to the HOST's core, which then co-attaches when the host holds the session live and+ * refuses otherwise; it never creates a local session on the host under the node's identity.+ * - `relaySsh` on the project — display-only strings for the tab's `SSH user@host` chip. It is not+ * an `SshConnection` and nothing that dials reads it.+ * - A plain `ssh <host>` node (`ssh` without `sshRemoteTmux`) keeps its connection: its create runs+ * `ssh` as a pty program on the HOST's core (the relay api), never on this machine.+ */++/** Display-only strings for a relay tab of the host's SSH project. */+export interface RelaySshDisplay {+ user: string+ host: string+ remoteCwd: string+}++/** Printable, single-line, bounded — this is text from another machine headed for the tab bar. */+function displayText(v: unknown): string {+ if (typeof v !== 'string') return ''+ // eslint-disable-next-line no-control-regex+ return v.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 256)+}++/** Drop the dial-capable connection from an SSH-project node (see the module header). */+export function sanitizeRelayNode(node: CanvasNodeState): CanvasNodeState {+ if (!node.sshRemoteTmux || node.ssh === undefined) return node+ const { ssh: _dropped, ...rest } = node+ return rest+}++/** The host's project as a relay tab may hold it: no `ssh`, display strings only. */+export function sanitizeRelayProject(project: Project): Project {+ const { ssh, ...rest } = project+ const out: Project = { ...rest, remote: true, nodes: (project.nodes ?? []).map(sanitizeRelayNode) }+ if (ssh && typeof ssh === 'object') {+ const server = (ssh as { server?: { user?: unknown; host?: unknown } }).server+ out.relaySsh = {+ user: displayText(server?.user),+ host: displayText(server?.host),+ remoteCwd: displayText((ssh as { remoteCwd?: unknown }).remoteCwd)+ }+ } else {+ delete out.relaySsh+ }+ return out+}++/** A canvas-sync mutation arriving on a relay session, with the same stripping applied. */+export function sanitizeRelayMutation(mutation: CanvasMutation): CanvasMutation {+ if (mutation.op !== 'upsert') return mutation+ const node = sanitizeRelayNode(mutation.node)+ return node === mutation.node ? mutation : { ...mutation, node }+}++/**+ * THE gate every guest-side SSH dial asks: a relay tab's project never dials, whatever it carries.+ * `undefined` (unknown project) is not a relay project — the caller's own "nothing to dial" check+ * decides that case, exactly as before.+ */+export function projectMayDialSsh(project: Pick<Project, 'remote'> | undefined): boolean {+ return !project?.remote+}diff --git a/src/renderer/session/relay-ssh.wiring.test.ts b/src/renderer/session/relay-ssh.wiring.test.tsnew file mode 100644index 000000000..e4b911d57--- /dev/null+++ b/src/renderer/session/relay-ssh.wiring.test.ts@@ -0,0 +1,39 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'++/**+ * SECURITY (source-level): the guest-side SSH dial sites each refuse a relay tab on their own, in+ * addition to the adopt boundary stripping `ssh` (relay-ssh.ts). These sites close over the+ * Electron preload and live React state, so their wiring is pinned here; the decisions themselves+ * are behaviour-tested in sshAttachments.test.ts and relay-ssh.test.ts.+ */+const read = (rel: string): string =>+ readFileSync(join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('relay tabs never reach a guest-side ssh dial', () => {+ const canvas = read('canvas/Canvas.tsx')+ const node = read('nodes/TerminalNode.tsx')++ it('the active-project effect dials only what planActiveProjectDials returns', () => {+ expect(canvas).toContain('const dials = planActiveProjectDials(project)')+ expect(canvas).toContain('if (dials.own) {')+ expect(canvas).toContain('for (const attachment of dials.attachments) {')+ expect(canvas).not.toMatch(/if \(project\.ssh\) \{\n\s+const ssh = project\.ssh\n\s+\/\/ SSH remote projects are free/)+ })++ it('the reconnect coordinator refuses a relay project', () => {+ expect(canvas).toContain('if (!project?.ssh || !projectMayDialSsh(project)) return false')+ })++ it('relay canvas-sync mutations are stripped', () => {+ expect(canvas).toContain('const mutation = relay ? sanitizeRelayMutation(incoming) : incoming')+ })++ it('a relay terminal never resolves a guest-local ControlMaster', () => {+ expect(node).toContain("const dialsSsh = sshRemoteTmux && session.source !== 'relay'")+ expect(node).toMatch(/dialsSsh && ssh\n\s+\? await resolveSshRemote\(/)+ expect(node).not.toMatch(/sshRemoteTmux && ssh\n\s+\? await resolveSshRemote\(/)+ expect(node).toContain('if (!projectMayDialSsh(useProjects.getState().getProject(activeProjectId))) return undefined')+ })+})diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.tsindex c232398d5..c02c89229 100644--- a/src/renderer/session/relay-tab.test.ts+++ b/src/renderer/session/relay-tab.test.ts@@ -15,6 +15,7 @@ import {resetSessionsForTest,} from './session'import { LocalTransport } from '../terminal/local-transport'+import { planActiveProjectDials } from '../lib/sshAttachments'import type { NodeTerminalApi, Project, Workspace } from '@shared/types'import type { RelayApiHandle } from '../bridge/relay-api'import { emitLocalRelayClose } from '../bridge/relay-local-close'@@ -145,6 +146,34 @@ describe('openRelayTab (connect → tab → mount)', () => {expect(setActiveProject).toHaveBeenCalledWith('host-proj-adopted')})+ it('SECURITY: adopting a host SSH project brings no dial-capable ssh onto this machine', async () => {+ const server = { host: 'evil.example', user: 'me', identityFile: '/home/me/.ssh/id_ed25519' }+ const hostProject = {+ id: 'host-proj',+ name: 'P',+ color: '#fff',+ viewport: { x: 0, y: 0, zoom: 1 },+ ssh: { server, remoteCwd: '/srv' },+ nodes: [+ { id: 't1', kind: 'terminal', title: 'A', color: '#111', position: { x: 0, y: 0 }, ssh: server, sshRemoteTmux: true },+ ],+ } as unknown as Project+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: 'host-proj', projects: [hostProject] })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps, adoptProject } = makeDeps({ handle })++ await openRelayTab('conn-1', 'Host', deps)++ const adopted = adoptProject.mock.calls[0][0] as Project+ expect(adopted.ssh).toBeUndefined()+ expect(adopted.nodes[0].ssh).toBeUndefined()+ expect(adopted.relaySsh).toEqual({ user: 'me', host: 'evil.example', remoteCwd: '/srv' })+ // …and the Canvas active-project effect's plan for it dials nothing.+ expect(planActiveProjectDials(adopted)).toEqual({ own: null, attachments: [] })+ // Even with `remote` forgotten, nothing dial-capable is left to find.+ expect(planActiveProjectDials({ ...adopted, remote: false })).toEqual({ own: null, attachments: [] })+ })+it('falls back to an empty labelled tab when the host shared nothing (no throw)', async () => {const { api } = fakeBridgedApi({ version: 2, activeProjectId: '', projects: [] })const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.tsindex 11615a925..9d30d1850 100644--- a/src/renderer/session/relay-tab.ts+++ b/src/renderer/session/relay-tab.ts@@ -18,6 +18,7 @@ import type { HostedRole, HostedSessionApi, Project, RelayClientApi } from '@shaimport { buildRelayApi, type RelayApiHandle } from '../bridge/relay-api'import { E_DISCONNECTED } from '../../shared/rpc'import { onLocalRelayClose } from '../bridge/relay-local-close'+import { sanitizeRelayProject } from './relay-ssh'import { closedReasonMessage, RelayApprovalError } from '../lib/hostedTeam'import { attachHostedOwner } from '../lib/hostedOwner'import { useHostedTeams, type HostedTeamInfo } from '../state/hostedTeams'@@ -138,7 +139,7 @@ export async function openRelayTab(const hostProject = ws.projects[0]const projectId =hostProject && deps.adoptProject- ? deps.adoptProject({ ...hostProject, remote: true }).id+ ? deps.adoptProject(sanitizeRelayProject(hostProject)).id: deps.addProject(label).idbindProjectToSession(projectId, session.id)if (deps.activate !== false) {diff --git a/src/shared/types.ts b/src/shared/types.tsindex f8dfbdb9d..bd3784338 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1027,6 +1027,12 @@ export interface Project {* peer's disk, so it must never land in this client's workspace.json.*/remote?: boolean+ /**+ * Relay tabs only: the host's SSH endpoint as DISPLAY strings (the tab's `SSH user@host` chip).+ * A relay tab never carries `ssh` — it would make this machine dial the host's server with this+ * machine's credentials (see renderer/session/relay-ssh.ts). Runtime-only like `remote`.+ */+ relaySsh?: { user: string; host: string; remoteCwd: string }}/** The full workspace written to / read from disk. */