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(ssh): seed only an issued join code; code the shutting-down bootstrap
review614e98e59278
diff --git a/CLAUDE.md b/CLAUDE.mdindex 210a80249..997629a3e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8477,8 +8477,9 @@ invariants:existing client bookmark auto-confirm, so it is NOT a seventh confirm site. That is sound only forits input: the join code `team bootstrap` returned over the project's own ssh channel (host keyauthenticated by `known_hosts`; `decodeJoinCode` checks hostId = hash(key) and `wss:`/loopback- `ws:`). Feed it nothing else; the code does NOT yet enforce "only the last bootstrap's code". A- failed seed degrades to the SAS prompt, never to a skip; any pasted code compares the SAS.+ `ws:`). Main enforces that: it remembers the code each project's last SUCCESSFUL bootstrap+ returned (in memory) and refuses to seed any other, however valid. A failed seed degrades to the+ SAS prompt, never to a skip; any pasted code compares the SAS.- **Hosted tabs are one per shared project, and the tab id IS the host project id.** relay-apitranslates no ids, so a tab under any other id asks the host about a project it does not know: aclosed relay copy under that id is replaced, anything else holding it (an open tab, a localdiff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex 2f9d0ffc6..5a7d69f21 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -362,10 +362,11 @@ and host key already exists, sets `approvedAt` on it and keeps its device tokenThat is safe only because of what `seedBookmark` is given: the join code `team bootstrap` justreturned over the project's own SSH channel, whose host key `known_hosts` already authenticated. Thecode names the relay key it was minted for (`decodeJoinCode` checks that the host id is the hash of-that key), which is the assurance comparing six digits by eye gives. Its input must be such a code-and nothing else; the desktop does not yet check that the code it is handed is the one the last-bootstrap returned. The host approves its own half because your key is an owner in `team.json`. If-the seed fails, the join asks for the SAS like a pasted code. Every other join, a pasted code or a+that key), which is the assurance comparing six digits by eye gives. Main enforces that input: it+seeds only a code a successful `team bootstrap` returned during this app run (kept per project, in+memory), and refuses any other code, however valid, so that join compares the SAS. The host approves+its own half because your key is an owner in `team.json`. If the seed fails, the join asks for the+SAS like a pasted code. Every other join, a pasted code or ateammate's, still compares the SAS.### Refusals@@ -384,7 +385,7 @@ teammate's, still compares the SAS.| The host's home directory could not be read | "Could not read your home directory on the host, so Share with team cannot check that this project's folder is safe to share. Try again." || git or curl is missing, and the installer has to run | "Installing nodeterm-server needs git and curl on the host (missing: …)." || The folder path contains `'` or `\` | "The folder path contains a quote or backslash, which cannot be passed safely to every login shell." |-| Hosting cannot start | "Could not share: Hosting could not start on the host: …" with the relay's reason; the SSH project is reopened. |+| Hosting cannot start | "Could not share: " and the server's own sentence, e.g. "Hosting could not start: …" with the relay's reason, or "The nodeterm server is shutting down. Hosting was not started."; the SSH project is reopened. |**Root.** A root login is refused because the installer makes a system install for root, and theserver core would then hand every Editor a root shell. A host that already runs a system installdiff --git a/src/core/relay/team-bootstrap.test.ts b/src/core/relay/team-bootstrap.test.tsindex 97e9025c1..96c0350d7 100644--- a/src/core/relay/team-bootstrap.test.ts+++ b/src/core/relay/team-bootstrap.test.ts@@ -101,9 +101,10 @@ describe('runBootstrap', () => {expect(calls.some((c) => c.startsWith('share'))).toBe(false)})- it('a server shutting down after init does not start hosting', async () => {+ it('a server shutting down after init does not start hosting, and says so with a code', async () => {+ // Coded, so the desktop never reads it as a bootstrap that may have finished.const { d, calls } = deps({ closing: true })- await expect(runBootstrap(d, REQ)).rejects.toThrow(/shutting down/)+ await expect(runBootstrap(d, REQ)).rejects.toMatchObject({ code: 'E_HOSTING_OFF', message: expect.stringMatching(/shutting down/) })expect(calls).toEqual(['init'])})})diff --git a/src/core/relay/team-bootstrap.ts b/src/core/relay/team-bootstrap.tsindex a237bfd80..205449fd5 100644--- a/src/core/relay/team-bootstrap.ts+++ b/src/core/relay/team-bootstrap.ts@@ -30,7 +30,7 @@ export async function runBootstrap(const { created: team } = await svc.init()// The admin closes BEFORE the server stops hosting: a `start()` issued after that stop would bring// a scheduler up on a server that is going away (the same rule `team init` follows).- if (deps.closing()) throw new Error('The nodeterm server is shutting down. Hosting was not started.')+ if (deps.closing()) throw codedError('E_HOSTING_OFF', 'The nodeterm server is shutting down. Hosting was not started.')const start = await svc.start()if (start !== 'started') throw codedError('E_HOSTING_OFF', `Hosting did not start (${start}). See \`team status\`.`)const wait = await svc.waitForHosting(deps.hostingWaitMs ?? BOOTSTRAP_HOSTING_WAIT_MS)diff --git a/src/core/remote-ssh/share-team-remote.test.ts b/src/core/remote-ssh/share-team-remote.test.tsindex aa38c72db..3111f9d05 100644--- a/src/core/remote-ssh/share-team-remote.test.ts+++ b/src/core/remote-ssh/share-team-remote.test.ts@@ -16,7 +16,6 @@ const write = (p: string, body: string, mode = 0o644): void => {fs.mkdirSync(path.dirname(p), { recursive: true })fs.writeFileSync(p, body, { mode })}-const REAL_TIMEOUT = ['/usr/bin/timeout', '/bin/timeout'].find((p) => fs.existsSync(p)) ?? ''const findTool = (name: string): string => ['/usr/bin', '/bin'].map((d) => path.join(d, name)).find((p) => fs.existsSync(p)) ?? ''// A server bundle that knows `team bootstrap` carries its usage row as text; the probe detects the// verb from that text and never by running the bundle.@@ -35,6 +34,9 @@ beforeAll(() => {write(path.join(bin, 'uname'), '#!/bin/sh\necho Linux\n', 0o755)write(path.join(bin, 'id'), '#!/bin/sh\ncase "$1" in -u) echo 1000;; -un) echo alice;; esac\n', 0o755)write(path.join(bin, 'git'), '#!/bin/sh\nexit 0\n', 0o755)+ // A fake `timeout` that just runs the command: a stock macOS has no `timeout` binary, and the+ // probe skips `team status` without one. The bounding behaviour has its own test below.+ write(path.join(bin, 'timeout'), '#!/bin/sh\nshift\nexec "$@"\n', 0o755)// A fake tmux: sessions are files in $STATE; a "*.stuck" one survives kill-session. Like real// tmux, a target WITHOUT the leading `=` that matches no session exactly falls back to a prefix// match, and a miss prints tmux's own message (measured on tmux 3.4) with exit 1. Any socket but@@ -193,10 +195,27 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /biconst hung = path.join(dir, 'bin-hung', 'node')write(hung, ['#!/bin/sh', 'if read -r line; then echo "stdin:$line" >> ' + JSON.stringify(hangLog) + '; fi', `echo "$*" >> ${JSON.stringify(hangLog)}`, 'exec sleep 30'].join('\n'), 0o755)const hungHome = homeWithUnit('hung-home', hung, NEW_MAIN)- // A stand-in `timeout` records the duration it was given and then waits 1 s instead of it.+ // A stand-in `timeout` records the duration it was given, then kills the command after 1 s+ // instead and answers 124 as the real one does. Plain sh, so the test needs no `timeout` binary.const timeoutLog = path.join(dir, 'timeout-calls.log')const fastTimeout = path.join(dir, 'bin-fast-timeout')- write(path.join(fastTimeout, 'timeout'), ['#!/bin/sh', `echo "$1" >> ${JSON.stringify(timeoutLog)}`, 'shift', `exec ${REAL_TIMEOUT} 1 "$@"`].join('\n'), 0o755)+ write(+ path.join(fastTimeout, 'timeout'),+ [+ '#!/bin/sh',+ `echo "$1" >> ${JSON.stringify(timeoutLog)}`,+ 'shift',+ '"$@" &',+ 'pid=$!',+ '( sleep 1; kill -TERM "$pid" 2>/dev/null ) >/dev/null 2>&1 &',+ 'watcher=$!',+ 'wait "$pid"; rc=$?',+ 'kill "$watcher" 2>/dev/null',+ '[ "$rc" -gt 128 ] && exit 124',+ 'exit "$rc"'+ ].join('\n'),+ 0o755+ )const started = Date.now()const out = await sh(shareProbeCommand('~', noSystemUnit()), 'leaked\n', { HOME: hungHome, PATH: `${fastTimeout}:${bin}:/usr/bin:/bin` })expect(Date.now() - started).toBeLessThan(4000)diff --git a/src/main/remote-ssh/share-team.test.ts b/src/main/remote-ssh/share-team.test.tsindex 9de2ee076..70254cc47 100644--- a/src/main/remote-ssh/share-team.test.ts+++ b/src/main/remote-ssh/share-team.test.ts@@ -1,4 +1,6 @@import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import path from 'node:path'import { createShareTeamHandlers, SHARE_TIMEOUTS, type ShareTeamDeps } from './share-team'import { SHARE_REFUSAL } from '../../shared/share-team'import { encodeJoinCode } from '../../core/relay/join-code'@@ -67,6 +69,15 @@ const GOOD = (): Record<string, unknown> => ({})const lastArg = (c: { args: string[] }): string => c.args[c.args.length - 1]+describe('share-team wiring in main', () => {+ it('passes each verb timeout through to sshRun (a dropped argument falls back to the runner 15 s)', () => {+ // The runner end is pinned in ssh-project.test.ts; this is the glue between the two.+ const src = readFileSync(path.resolve(__dirname, '../index.ts'), 'utf8').replace(/\r\n/g, '\n')+ const block = src.slice(src.indexOf('createShareTeamHandlers({'), src.indexOf('runInstall:', src.indexOf('createShareTeamHandlers({')))+ expect(block).toMatch(/run: \(args, stdin, timeoutMs\) =>\s+sshProjectManager \? sshProjectManager\.sshRun\(args, stdin, \{ timeoutMs \}\)/)+ })+})+describe('share-team handlers', () => {it('probe: refuses a disconnected project with E_NOT_CONNECTED', async () => {const { h } = deps({ connected: false })@@ -251,11 +262,18 @@ describe('share-team handlers', () => {release({ exitCode: 0 })expect(await again).toEqual({ ok: true, exitCode: 0 })})+ /** Handlers whose last bootstrap returned CODE: the only code `seedBookmark` may seed. */+ const bootstrapped = async (o: Parameters<typeof deps>[0] = {}) => {+ const d = deps({ ...o, replies: [PROBE_OUT, cli(GOOD())] })+ await d.h.probe('p', [])+ expect(await d.h.bootstrap('p')).toMatchObject({ ok: true })+ return d+ }it('seedBookmark: a new team gets an approved ssh bookmark; an existing unapproved one is approved; a bad code is refused', async () => {- const a = deps()+ const a = await bootstrapped()expect(await a.h.seedBookmark(CODE)).toMatchObject({ ok: true, label: 'box' })expect(a.saved).toEqual([{ hostId: hostIdFromPublicKeyB64(hostKey), code: CODE, label: 'box', deviceToken: null, approvedAt: '2026-10-01T10:00:00.000Z', source: 'ssh' }])- const b = deps({ bookmarks: [{ hostId: hostIdFromPublicKeyB64(hostKey), code: CODE, label: 'box', deviceToken: 'tok', approvedAt: null, source: 'code' }] })+ const b = await bootstrapped({ bookmarks: [{ hostId: hostIdFromPublicKeyB64(hostKey), code: CODE, label: 'box', deviceToken: 'tok', approvedAt: null, source: 'code' }] })await b.h.seedBookmark(CODE)expect(b.saved[0]).toMatchObject({ deviceToken: 'tok', approvedAt: '2026-10-01T10:00:00.000Z', source: 'code' })expect(await a.h.seedBookmark('nodeterm://join/garbage')).toMatchObject({ ok: false })@@ -263,13 +281,31 @@ describe('share-team handlers', () => {it('seedBookmark: an approved bookmark for the same key is left alone; one for another key is replaced', async () => {const hostId = hostIdFromPublicKeyB64(hostKey)const kept: RelayBookmark = { hostId, code: CODE, label: 'box', deviceToken: 'tok', approvedAt: '2026-01-01T00:00:00.000Z', source: 'code' }- const a = deps({ bookmarks: [kept] })+ const a = await bootstrapped({ bookmarks: [kept] })await a.h.seedBookmark(CODE)expect(a.saved).toEqual([kept])// Same hostId, different stored key: the stored code no longer decodes to this key.const stale: RelayBookmark = { ...kept, code: 'nodeterm://join?code=stale' }- const b = deps({ bookmarks: [stale] })+ const b = await bootstrapped({ bookmarks: [stale] })await b.h.seedBookmark(CODE)expect(b.saved).toEqual([{ hostId, code: CODE, label: 'box', deviceToken: null, approvedAt: '2026-10-01T10:00:00.000Z', source: 'ssh' }])})+ it('seedBookmark skips the SAS only for a code a successful bootstrap handed out', async () => {+ // A valid code nobody bootstrapped: no SAS skip, and nothing written.+ const fresh = deps()+ expect(await fresh.h.seedBookmark(CODE)).toMatchObject({ ok: false })+ expect(fresh.saved).toEqual([])+ // A failed bootstrap hands out nothing either, even when the reply carried a code.+ const refused = deps({ replies: [PROBE_OUT, cli({ ok: false, code: 'E_HOSTING_OFF', error: 'no' }, 1)] })+ await refused.h.probe('p', [])+ await refused.h.bootstrap('p')+ expect(await refused.h.seedBookmark(CODE)).toMatchObject({ ok: false })+ expect(refused.saved).toEqual([])+ // A code for another team, valid and well-formed, after a bootstrap that returned CODE.+ const otherKey = publicKeyToB64(genKeyPair().publicKey)+ const other = encodeJoinCode({ v: 1, relayEndpoint: 'wss://relay.example', hostId: hostIdFromPublicKeyB64(otherKey), hostPublicKeyB64: otherKey, hostDeviceId: 'dev2', label: 'evil' })+ const done = await bootstrapped()+ expect(await done.h.seedBookmark(other)).toMatchObject({ ok: false })+ expect(done.saved).toEqual([])+ })})diff --git a/src/main/remote-ssh/share-team.ts b/src/main/remote-ssh/share-team.tsindex 735cb4e3b..4c309f957 100644--- a/src/main/remote-ssh/share-team.ts+++ b/src/main/remote-ssh/share-team.ts@@ -8,7 +8,8 @@// The server is not trusted with what it says about itself. A join code is accepted only through// `decodeJoinCode`, which checks that the hostId is the hash of the key the code carries and that the// relay endpoint is `wss:` (or loopback `ws:`); a bootstrap whose code names a different host than-// its own reply is refused.+// its own reply is refused. `seedBookmark`, which skips the SAS, seeds only a code a successful+// bootstrap returned here.//// The probe is cached per project. `bootstrap` and `resume` run the server binary, main.cjs and data// dir from that cached, validated probe, never from paths the renderer sends, and bootstrap adopts@@ -106,6 +107,7 @@ const PROJECT_READ_FAILED = 'Could not read the project file on the host.'const BAD_JOIN_CODE = 'The server sent an invalid join code.'const BAD_BOOTSTRAP = 'The server answered bootstrap with a result this build cannot read.'const BAD_RESUME = 'The server answered resume with a result this build cannot read.'+const NOT_ISSUED = 'Only the invite code Share with team just received can be added without the verification code.'/** The most of a server-sent sentence shown to the user. */const SHOWN_MAX = 500@@ -187,6 +189,9 @@ function resumeResults(body: unknown): ResumeResultEntry[] | null {export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers {const probes = new Map<string, ShareProbe>()const installs = new Map<string, AbortController>()+ /** The join code each project's last SUCCESSFUL bootstrap returned: the only codes `seedBookmark`+ * may seed, because only those arrived over the project's own authenticated ssh channel. */+ const issuedCodes = new Map<string, string>()/** The cached probe and its plan. A plan that refuses answers with its own reason, under the* not-probed code: nothing ran, and the renderer must not read it as a server failure. */@@ -309,6 +314,7 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlersif (!result) return fail(BAD_BOOTSTRAP)const code = decodeJoinCode(result.joinCode)if (!code || code.hostId !== result.hostId) return fail(BAD_JOIN_CODE)+ issuedCodes.set(projectId, result.joinCode)return { ok: true, result }} catch (e) {return caught(e)@@ -365,13 +371,15 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlersasync seedBookmark(joinCode) {try {+ // The ONE join that skips the SAS, so it takes only a code a successful bootstrap handed+ // out here: that code arrived over the project's own ssh channel, whose host key+ // known_hosts authenticated, and it names the relay key it was minted for — the same+ // assurance a human comparing six digits gives. Any other code, valid or not, still+ // compares the SAS.+ if (![...issuedCodes.values()].includes(joinCode)) return fail(NOT_ISSUED)const code = decodeJoinCode(joinCode)if (!code) return fail('That is not a valid team invite code.')const at = new Date(deps.now()).toISOString()- // The ONE join that skips the SAS: this code arrived over the project's own ssh channel,- // whose host key known_hosts authenticated, and it names the relay key it was minted for —- // the same assurance a human comparing six digits gives. Any pasted code still compares the- // SAS.const existing = (await deps.bookmarks.list()).find((b) => b.hostId === code.hostId)if (existing && decodeJoinCode(existing.code)?.hostPublicKeyB64 === code.hostPublicKeyB64) {// Same team, same key: keep its device token; approve it if it never was.diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex d8985b62c..0bf65358c 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -8,6 +8,7 @@ import { AskpassServer } from './ssh-askpass'import { AppSshAgent } from './ssh-agent'import { RemoteHooks } from './remote-hooks'import { controlPathFor } from '../../core/remote-ssh/control-master'+import { SHARE_TIMEOUTS } from './share-team'import { remoteCodexSocket } from '../../core/codex-accounts-core'import type { SshConnection } from '@shared/ssh'@@ -90,6 +91,14 @@ describe('SshProjectManager', () => {expect(mgr.refForProject('p1')?.conn.identityAgentSock).toBeUndefined()})+ it('sshRun hands its timeout to the runner (Share with team: bootstrap needs 60 s, not the 15 s default)', async () => {+ const { mgr, run } = makeMgr()+ await mgr.sshRun(['-S', '/cp', 'h', 'true'], 'stdin', { timeoutMs: SHARE_TIMEOUTS.bootstrap })+ expect(run).toHaveBeenLastCalledWith(['-S', '/cp', 'h', 'true'], 'stdin', 60_000)+ await mgr.sshRun(['h', 'true'])+ expect(run).toHaveBeenLastCalledWith(['h', 'true'], undefined, undefined) // the runner's own default+ })+it('listDir parses remote dir entries', async () => {const { mgr } = makeMgr()await mgr.connect('p1', conn)diff --git a/src/renderer/lib/shareSshTeam.test.ts b/src/renderer/lib/shareSshTeam.test.tsindex 928a27329..a0828e5bf 100644--- a/src/renderer/lib/shareSshTeam.test.ts+++ b/src/renderer/lib/shareSshTeam.test.ts@@ -133,9 +133,10 @@ describe('runShare', () => {expect(log).not.toContain('bootstrap')})it('a bootstrap failure reopens the SSH project and kills nothing', async () => {- const { deps, log } = setup({ bootstrap: { ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' } })+ // The server's own sentence already says hosting could not start; it is shown as it came.+ const { deps, log } = setup({ bootstrap: { ok: false, code: 'E_HOSTING_OFF', error: 'Hosting could not start: refused (403)' } })const out = await runShare(deps, INPUT)- expect(out).toEqual({ kind: 'failed', step: 'bootstrapping', reopened: true, error: 'Hosting could not start on the host: refused (403)' })+ expect(out).toEqual({ kind: 'failed', step: 'bootstrapping', reopened: true, error: 'Hosting could not start: refused (403)' })expect(log).toContain('restore')expect(log.some((l) => l.startsWith('kill:'))).toBe(false)})diff --git a/src/renderer/lib/shareSshTeam.ts b/src/renderer/lib/shareSshTeam.tsindex 0bfb9d787..50f31fa60 100644--- a/src/renderer/lib/shareSshTeam.ts+++ b/src/renderer/lib/shareSshTeam.ts@@ -279,13 +279,9 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Sharconst booted = await call(() => api.bootstrap(projectId))if (!booted.ok) {// Any bootstrap failure reopens the project, even one without a server code that may have- // left the server set up: the desktop must never stay closed on an unconfirmed handover.- const error =- booted.code === 'E_HOSTING_OFF'- ? `Hosting could not start on the host: ${booted.error}`- : booted.code- ? booted.error- : booted.error + BOOTSTRAP_MAY_HAVE_FINISHED+ // left the server set up: the desktop must never stay closed on an unconfirmed handover. A coded+ // failure is the server's (or main's) own sentence and is shown as it came.+ const error = booted.code ? booted.error : booted.error + BOOTSTRAP_MAY_HAVE_FINISHEDreturn failAndUndo('bootstrapping', error, true)}const result = booted.result