Skip to content

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.

fix(project-setup): host-only trust gate + port-scoped ssh trust + quit teardown

enes03ffecc3c239
diff --git a/src/core/project-setup-service.test.ts b/src/core/project-setup-service.test.ts
index c02fce03f..fd064b82b 100644
--- a/src/core/project-setup-service.test.ts
+++ b/src/core/project-setup-service.test.ts
@@ -623,3 +623,116 @@ describe('registerProjectSetupHandlers', () => {
expect(consents).toEqual([['r1', 'approve']])
})
})
+
+/**
+ * The consent prompt carries the SCRIPT BODIES of a shared settings file — the exact bytes a human
+ * is being asked to authorize. `platform().broadcast` on the desktop fans out to every relay peer
+ * (a paired phone, another desktop), so broadcasting the prompt would hand a guest the contents of
+ * a file they may have no other way to read, and show them a dialog only the host may answer. The
+ * shell therefore injects WHERE a prompt goes; the default stays broadcast, which is right for the
+ * Server Edition (every attached client there is an authenticated operator of that host).
+ */
+describe('ProjectSetupService — consent delivery seam', () => {
+ const seam = (): { sent: Array<{ channel: string; payload: unknown }>; send: (channel: string, payload: unknown) => void } => {
+ const sent: Array<{ channel: string; payload: unknown }> = []
+ return { sent, send: (channel, payload) => sent.push({ channel, payload }) }
+ }
+
+ it('routes the consent REQUEST through sendConsent, never through the peer-fanning broadcast', async () => {
+ const s = seam()
+ const { calls, runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci --registry=secret' } })),
+ runLocal: runner,
+ sendConsent: s.send
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(s.sent).toHaveLength(1))
+ expect(s.sent[0].channel).toBe(IPC.projectSetupConsentRequest)
+ const req = s.sent[0].payload as ProjectSetupConsentRequest
+ expect(req.scripts).toEqual({ setup: 'npm ci --registry=secret' })
+ // The script body never entered the broadcast fan-out at all.
+ expect(consentRequests()).toEqual([])
+ expect(JSON.stringify(plat.sent)).not.toContain('secret')
+
+ svc.submitConsent(req.requestId, 'approve')
+ expect(await pending).toMatchObject({ status: 'started' })
+ await vi.waitFor(() => expect(calls).toHaveLength(1))
+ // Run EVENTS keep broadcasting: they are the canvas's own run state, not the approval question.
+ await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))
+ })
+
+ it('routes the DISMISS through the same seam (cancel and expiry alike)', async () => {
+ const s = seam()
+ const { runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci' } })),
+ runLocal: runner,
+ sendConsent: s.send
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(s.sent).toHaveLength(1))
+ const { requestId } = s.sent[0].payload as ProjectSetupConsentRequest
+
+ expect(svc.cancel(setupRunKey(target(), 'setup'))).toBe(true)
+ expect(s.sent[1]).toEqual({ channel: IPC.projectSetupConsentDismiss, payload: { requestId } })
+ expect(dismissed()).toEqual([]) // and not to the peers
+ expect(await pending).toEqual({ status: 'skipped', reason: 'declined' })
+ })
+})
+
+/**
+ * A local run is a DETACHED process group (setsid), deliberately, so a cancel can SIGKILL the whole
+ * tree. The same property means an app quit leaves one running with nothing left to report to:
+ * `npm ci` keeps churning after the window is gone. Every shell's shutdown path calls disposeAll.
+ */
+describe('ProjectSetupService — disposeAll', () => {
+ it('aborts every active run, so each runner sees its own signal fire', async () => {
+ const aborted: string[] = []
+ const runner: ProjectSetupRunner = ({ cwd, signal }) =>
+ new Promise((resolve) => {
+ signal.addEventListener('abort', () => {
+ aborted.push(cwd)
+ resolve({ exitCode: 137 })
+ })
+ })
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'sleep 100' } }),
+ runLocal: runner
+ })
+ const a = await svc.run(target({ projectId: 'p1', rootPath: '/a' }), 'setup')
+ const b = await svc.run(target({ projectId: 'p2', rootPath: '/b' }), 'setup')
+ expect([a.status, b.status]).toEqual(['started', 'started'])
+
+ svc.disposeAll()
+ expect(aborted.sort()).toEqual(['/a', '/b'])
+ await vi.waitFor(() => expect(events('p1').at(-1)?.state).toBe('cancelled'))
+ await vi.waitFor(() => expect(events('p2').at(-1)?.state).toBe('cancelled'))
+
+ // Idempotent: a second pass (Electron runs before-quit twice) has nothing left to abort.
+ expect(() => svc.disposeAll()).not.toThrow()
+ expect(aborted).toHaveLength(2)
+ })
+
+ it('also closes a run still waiting at its consent dialog, and dismisses that dialog', async () => {
+ const s: Array<{ channel: string; payload: unknown }> = []
+ const { calls, runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci' } })),
+ runLocal: runner,
+ sendConsent: (channel, payload) => s.push({ channel, payload })
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(s).toHaveLength(1))
+ const { requestId } = s[0].payload as ProjectSetupConsentRequest
+
+ svc.disposeAll()
+ expect(s[1]).toEqual({ channel: IPC.projectSetupConsentDismiss, payload: { requestId } })
+ expect(await pending).toEqual({ status: 'skipped', reason: 'declined' })
+ expect(calls).toHaveLength(0)
+ })
+})
diff --git a/src/core/project-setup-service.ts b/src/core/project-setup-service.ts
index cca769e68..b041e2ed3 100644
--- a/src/core/project-setup-service.ts
+++ b/src/core/project-setup-service.ts
@@ -34,6 +34,8 @@ import { ProjectTrustStore, hashTrustContent, localTrustKey, sshTrustKey } from
* runs; an expired prompt is never a retroactive yes.
* - Prompts are serialized app-wide: one dialog at a time, so a workspace opening five projects
* cannot stack five modals over each other.
+ * - The prompt goes to the HOST's own UI (`sendConsent`), never to the broadcast fan-out: the
+ * question — and the script bytes it renders — belongs to the human at this machine.
*
* Spawning itself is injected (`runLocal`/`runSsh`) — this file knows nothing about child_process
* or ssh, which is also what makes the gate testable without a shell.
@@ -69,6 +71,19 @@ export interface ProjectSetupDeps {
runLocal?: ProjectSetupRunner
runSsh?: ProjectSetupRunner
now?: () => number
+ /**
+ * WHERE a consent prompt (and its dismiss) is delivered. Injected because the answer differs per
+ * shell and `platform().broadcast` — the only fan-out the core can see — is the WRONG answer on
+ * the desktop: it also reaches every relay PEER, which would (a) disclose the shared script
+ * bodies, the exact bytes being approved, to a guest who may have no other way to read that file,
+ * and (b) put the host's trust dialog on a screen that is not the host's. Electron passes its
+ * main-window-only send; the Server Edition leaves the default, where every attached client is an
+ * authenticated operator of that host and broadcast is exactly right.
+ *
+ * Only the CONSENT pair is routed this way. Run `events` keep broadcasting: they are the canvas's
+ * shared run state (a peer's canvas shows the same run), not the approval question.
+ */
+ sendConsent?: (channel: string, payload: unknown) => void
}
/** Single-flight identity: one live run per LOCATION per kind. Two canvas nodes pointing at the
@@ -215,11 +230,23 @@ export class ProjectSetupService {
// modal whose answer can no longer mean anything. Resolving the pending entry also drops it
// from `pending`, so a late approve for it is a no-op.
this.pending.get(requestId)?.(undefined)
- platform().broadcast(IPC.projectSetupConsentDismiss, { requestId })
+ this.sendConsent(IPC.projectSetupConsentDismiss, { requestId })
}
return true
}
+ /**
+ * Shell shutdown: abort every run still in flight. A local run is a DETACHED process group
+ * (setsid, so a cancel can SIGKILL the whole tree) — which is also why quitting without this
+ * leaves `npm ci` churning with nothing left to report to, and, on the ssh leg, an orphaned remote
+ * command. Goes through `cancel`, so a run parked at its consent dialog is closed and its dialog
+ * dismissed too. Idempotent: Electron's `before-quit` runs twice, and the second pass finds
+ * nothing left.
+ */
+ disposeAll(): void {
+ for (const runKey of [...this.active.keys()]) this.cancel(runKey)
+ }
+
/** Renderer answer for a pending consent prompt. An unknown/stale requestId (expired, double
* submit) and an unrecognized answer are silent no-ops — never an approval. */
submitConsent(requestId: string, answer: ProjectSetupConsentAnswer): void {
@@ -231,6 +258,12 @@ export class ProjectSetupService {
return this.deps.now ? this.deps.now() : Date.now()
}
+ /** The consent pair's delivery, per shell (see `ProjectSetupDeps.sendConsent`). */
+ private sendConsent(channel: string, payload: unknown): void {
+ if (this.deps.sendConsent) this.deps.sendConsent(channel, payload)
+ else platform().broadcast(channel, payload)
+ }
+
private askConsent(
entry: ActiveRun,
trustKey: string,
@@ -252,7 +285,7 @@ export class ProjectSetupService {
}
const timer = setTimeout(() => {
settle(undefined) // expired, NOT declined
- platform().broadcast(IPC.projectSetupConsentDismiss, { requestId })
+ this.sendConsent(IPC.projectSetupConsentDismiss, { requestId })
}, CONSENT_EXPIRY_MS)
timer.unref?.()
this.pending.set(requestId, (answer) => {
@@ -261,7 +294,7 @@ export class ProjectSetupService {
})
entry.consentRequestId = requestId
const payload: ProjectSetupConsentRequest = { ...req, requestId, previouslyApproved }
- platform().broadcast(IPC.projectSetupConsentRequest, payload)
+ this.sendConsent(IPC.projectSetupConsentRequest, payload)
})
})
// A rejected step must not poison the queue for every later prompt.
diff --git a/src/core/project-trust-store.test.ts b/src/core/project-trust-store.test.ts
index ede5a11e3..d427be02b 100644
--- a/src/core/project-trust-store.test.ts
+++ b/src/core/project-trust-store.test.ts
@@ -20,6 +20,24 @@ describe('trust keys', () => {
expect(ssh).toContain('u@h')
expect(ssh).not.toBe(localTrustKey('/srv/x'))
})
+
+ // `user@host` alone is not a machine. A jump host, a container, and a VM behind the same DNS name
+ // are routinely separated by PORT ONLY (sshAttachmentId already keys on host+user+port for exactly
+ // this reason), so an approval granted for the box on :2222 must not silently authorize the box on
+ // :22. The trust file is unreleased, so the key gains the port with no migration.
+ it('ssh keys are per PORT: the default :22 and an explicit :2222 are different locations', () => {
+ const base = { host: 'h', user: 'u' }
+ const implicit = sshTrustKey({ server: base, remoteCwd: '/srv/x' })
+ const explicit22 = sshTrustKey({ server: { ...base, port: 22 }, remoteCwd: '/srv/x' })
+ const alt = sshTrustKey({ server: { ...base, port: 2222 }, remoteCwd: '/srv/x' })
+ // An omitted port IS 22 (that is what ssh dials), so the two must be the SAME location.
+ expect(implicit).toBe(explicit22)
+ expect(alt).not.toBe(implicit)
+ expect(implicit).toContain('u@h:22')
+ expect(alt).toContain('u@h:2222')
+ // Still per-remoteCwd, and still not a local key.
+ expect(sshTrustKey({ server: { ...base, port: 2222 }, remoteCwd: '/srv/y' })).not.toBe(alt)
+ })
})
describe('ProjectTrustStore', () => {
diff --git a/src/core/project-trust-store.ts b/src/core/project-trust-store.ts
index cb7c88e43..187e239f4 100644
--- a/src/core/project-trust-store.ts
+++ b/src/core/project-trust-store.ts
@@ -17,8 +17,17 @@ export function localTrustKey(cwd: string): string {
return `local\0${path.resolve(cwd)}`
}
-export function sshTrustKey(ssh: { server: Pick<SshConnection, 'host' | 'user'>; remoteCwd: string }): string {
- return `ssh\0${sshHostKey(ssh.server)}\0${ssh.remoteCwd}`
+/**
+ * `user@host:port` + remote path. The PORT is part of the location, not decoration: one `user@host`
+ * is routinely several different machines — a container, a VM, a jump host behind the same DNS name
+ * — separated by port alone (`sshAttachmentId` keys on host+user+port for exactly this reason). An
+ * approval granted for the box on :2222 must never authorize the box on :22. An omitted port IS 22,
+ * because that is what ssh dials, so the two spellings are one key.
+ */
+export function sshTrustKey(
+ ssh: { server: Pick<SshConnection, 'host' | 'user' | 'port'>; remoteCwd: string }
+): string {
+ return `ssh\0${sshHostKey(ssh.server)}:${ssh.server.port ?? 22}\0${ssh.remoteCwd}`
}
export function hashTrustContent(content: string): string {
diff --git a/src/main/index.ts b/src/main/index.ts
index 039116676..a9566b4c0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -365,7 +365,14 @@ const projectSetupService = new ProjectSetupService({
// reports that as a failed run rather than dialing a fresh connection. Server Edition has no
// ssh-project manager at all, so it wires `runLocal` only and an ssh target there stays
// `{status:'skipped', reason:'unavailable'}`.
- runSsh: makeSshSetupRunner((endpoint) => sshProjectManager?.refForEndpoint(endpoint) ?? null)
+ runSsh: makeSshSetupRunner((endpoint) => sshProjectManager?.refForEndpoint(endpoint) ?? null),
+ // The trust prompt goes to THIS window only — never `platform().broadcast`, which also fans out
+ // to every relay peer (a paired phone, another desktop). Broadcasting it would hand a guest the
+ // shared script bodies (the exact bytes being approved) and put the host's own trust dialog on
+ // their screen. Same main-window-only push the ssh passphrase prompt uses; with the window closed
+ // (macOS) the prompt is simply not delivered and the run rides out its expiry as `unanswered`,
+ // which is the fail-closed direction.
+ sendConsent: (channel, payload) => sendToMain(channel, payload)
})
registerProjectSetupHandlers(corePlatform, projectSetupService, {
projectTargetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
@@ -3064,6 +3071,11 @@ app.on('before-quit', (e) => {
keepAwake?.dispose()
keepAwake = undefined
workspaceWatcher.dispose()
+ // A setup/archive run is a DETACHED process group (setsid, so cancel can SIGKILL the tree), which
+ // means quitting without this leaves `npm ci` churning with no app left to report to — and the
+ // hook/pty teardown below would never touch it. Idempotent, so the second before-quit pass (the
+ // deferred app.quit()) costs nothing.
+ projectSetupService.disposeAll()
if (quitFlushed) {
// Second pass (the deferred app.quit() below): the flush had its chance — drop the masters.
sshProjectManager?.disconnectAll()
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index a7d83f358..88d5d81ed 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -305,3 +305,60 @@ describe('electronPlatform.dispatch / cast (the peer inbound path)', () => {
expect(Object.keys(h.handlers).sort()).toEqual(['c1', 'c2', 'c3'])
})
})
+
+/**
+ * A relay guest is NOT the host's user. `project-setup:run` starts a script on the host, and
+ * `project-setup:consent-submit` is the ANSWER to the host's own trust prompt — a guest reaching
+ * both could trigger a run and then approve it themselves, with the host's human never touching
+ * anything. BOTH legs of the peer surface are gated: `dispatch` (request/response — how `run` and
+ * `cancel` arrive) and `cast` (fire-and-forget — how `consent-submit` arrives). Gating only the
+ * first would leave the self-approval half wide open.
+ */
+describe('electronPlatform host-only admission (project-setup)', () => {
+ const REFUSAL = {
+ code: 'E_FORBIDDEN',
+ message: 'host-control method is not available to relay peers'
+ }
+ const GATED = ['project-setup:run', 'project-setup:cancel', 'project-setup:consent-submit']
+
+ it('refuses a peer dispatch of run/cancel/consent-submit without reaching the handler', async () => {
+ const p = electronPlatform()
+ const reached: string[] = []
+ for (const ch of GATED) {
+ p.handle(ch, () => {
+ reached.push(ch)
+ return 'must-not-run'
+ })
+ }
+ let id = 0
+ for (const ch of GATED) {
+ id += 1
+ expect(await p.dispatch(PEER, { t: 'req', id, method: ch, args: [] })).toEqual({
+ t: 'res', id, ok: false, error: REFUSAL
+ })
+ }
+ expect(reached).toEqual([])
+ })
+
+ it('refuses a peer CAST of consent-submit — the self-approval path', () => {
+ const p = electronPlatform()
+ const answers: unknown[][] = []
+ p.on('project-setup:consent-submit', (...args: unknown[]) => answers.push(args))
+ p.cast(PEER, 'project-setup:consent-submit', ['req-1', 'approve'])
+ expect(answers).toEqual([])
+ })
+
+ it('still admits the harmless project-setup lifecycle channels', () => {
+ const p = electronPlatform()
+ const seen: string[] = []
+ p.on('project-setup:subscribe', () => seen.push('sub'))
+ p.cast(PEER, 'project-setup:subscribe', ['p1'])
+ expect(seen).toEqual(['sub'])
+ })
+
+ it('the LOCAL window is unaffected — its ipcMain registration still answers', async () => {
+ const p = electronPlatform()
+ p.handle('project-setup:run', (projectId: string) => `ran:${projectId}`)
+ expect(await h.handlers['project-setup:run']({ sender: { id: 1 } }, 'p1')).toBe('ran:p1')
+ })
+})
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index 116b18a80..c9b4de552 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -2,6 +2,7 @@ import { app, ipcMain, safeStorage, shell, webContents } from 'electron'
import type { CorePlatform } from '../core/platform'
import { mainWindowClientIds, sendToMain } from './main-window'
import { peerRegistry } from './peer-registry'
+import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from '../shared/host-control'
import { E_NO_HANDLER, type RpcErr, type RpcOk, type RpcRequest } from '../shared/rpc'
type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }
@@ -92,13 +93,13 @@ export function electronPlatform(): ElectronPlatform {
ipcMain.on(ch, (e, ...args) => fn(e.sender.id, ...args))
},
async dispatch(clientId, req) {
- if (req.method.startsWith('githubControl:')) {
+ // Host-control admission, from the ONE shared list (src/shared/host-control.ts) rather than a
+ // prefix test written out here — the second shell copying a stale copy of that test is the
+ // failure mode this closes.
+ if (isHostOnlyChannel(req.method)) {
return {
t: 'res', id: req.id, ok: false,
- error: {
- code: 'E_FORBIDDEN',
- message: 'host-control method is not available to relay peers'
- }
+ error: { code: 'E_FORBIDDEN', message: HOST_ONLY_REFUSAL }
}
}
const h = handlers.get(req.method)
@@ -119,6 +120,14 @@ export function electronPlatform(): ElectronPlatform {
}
},
cast(clientId, method, args) {
+ // The SAME admission as dispatch, because a cast is a second door into the same table. Gating
+ // dispatch alone would still admit `project-setup:consent-submit`, which the renderer sends as
+ // a cast (ws-bridge.ts) — i.e. a guest could not start a run but could still answer the host's
+ // trust prompt for it. A cast has no reply channel, so a refusal can only be dropped + logged.
+ if (isHostOnlyChannel(method)) {
+ console.warn(`[peer] refused host-control cast ${method} from peer ${clientId}`)
+ return
+ }
const set = listeners.get(method)
if (!set) return
for (const l of set) {
diff --git a/src/renderer/components/SetupConsentDialog.tsx b/src/renderer/components/SetupConsentDialog.tsx
index fd2b271f6..82561afb3 100644
--- a/src/renderer/components/SetupConsentDialog.tsx
+++ b/src/renderer/components/SetupConsentDialog.tsx
@@ -40,13 +40,15 @@ import { ConfirmDialog } from './ConfirmDialog'
* inside a script making a comment read as executable code, or vice versa) by pinning the DISPLAY
* order to the byte order, WITHOUT altering a single byte of what is approved and run.
*
- * KNOWN GAP (documented here, not fixable from this side — final-wave decision): a relay guest can
- * currently dispatch `project-setup:run` AND `project-setup:consent-submit` on the host
- * (`src/main/platform-electron.ts` — `dispatch` forbids only `githubControl:` methods), so a guest
- * could trigger a prompt and then answer it themselves without the host's user touching anything.
- * That is a main-side ADMISSION question — which methods a non-host peer may call — and no dialog
- * property can close it: this component cannot tell whose IPC message reached main. It is recorded
- * for the final wave's admission decision.
+ * WHO MAY ANSWER (closed in the final wave, main-side — nothing here could have closed it): a
+ * relay guest could otherwise dispatch `project-setup:run` and then cast
+ * `project-setup:consent-submit`, triggering a prompt and approving it itself with the host's user
+ * never touching anything. Both channels are now HOST-ONLY at the admission seam
+ * (`src/shared/host-control.ts`, enforced in `dispatch` AND `cast` in
+ * `src/main/platform-electron.ts`), and the prompt itself is delivered to the host's main window
+ * only (`ProjectSetupService`'s `sendConsent`) instead of the peer-fanning broadcast — so the
+ * script bytes rendered below are never disclosed to a guest either. This component still cannot
+ * tell whose message reached main; it does not have to.
*/
/** Longest a name/location may be on screen, in characters. */
diff --git a/src/server/index.ts b/src/server/index.ts
index a2dd2da11..ad3288e63 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -625,6 +625,9 @@ export async function startServer(
return {
port: 0, // nothing bound
async close() {
+ // Kill any in-flight setup/archive run: it is a detached process group, so nothing else in
+ // this teardown reaches it. Same call, same reason, in the serving branch's close() below.
+ projectSetupService.disposeAll()
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
pressure.stop()
@@ -677,6 +680,9 @@ export async function startServer(
return {
port,
async close() {
+ // Kill any in-flight setup/archive run first: it is a detached process group (setsid), so
+ // neither the WS teardown nor ptyManager.killAll() below would ever reach it.
+ projectSetupService.disposeAll()
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
sessionReaper.stop()
pressure.stop()
diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.ts
new file mode 100644
index 000000000..dfdedfd44
--- /dev/null
+++ b/src/shared/host-control.test.ts
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest'
+import { IPC } from './ipc'
+import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from './host-control'
+
+/**
+ * The ONE list both shells consult. It exists so the desktop's relay admission and any future
+ * shell cannot drift: a channel that only the host's own human may reach is named here, not in a
+ * per-shell `startsWith` that one of them forgets to copy.
+ */
+describe('isHostOnlyChannel', () => {
+ it('covers the whole GitHub host-control namespace by prefix', () => {
+ expect(isHostOnlyChannel(IPC.githubControlApprove)).toBe(true)
+ expect(isHostOnlyChannel(IPC.githubControlSaveToken)).toBe(true)
+ // A namespace, not a fixed list: a method added later is gated the day it is added.
+ expect(isHostOnlyChannel('githubControl:something-new')).toBe(true)
+ })
+
+ it('covers the three project-setup channels that can START or APPROVE a shared script', () => {
+ expect(isHostOnlyChannel(IPC.projectSetupRun)).toBe(true)
+ expect(isHostOnlyChannel(IPC.projectSetupConsentSubmit)).toBe(true)
+ expect(isHostOnlyChannel(IPC.projectSetupCancel)).toBe(true)
+ })
+
+ it('leaves the read-only/lifecycle channels alone — the gate is on ACTION, not on the namespace', () => {
+ // Subscribing and receiving events costs a guest nothing the canvas does not already show;
+ // running host code, and answering the host's own trust prompt, are the two acts being gated.
+ expect(isHostOnlyChannel(IPC.projectSetupSubscribe)).toBe(false)
+ expect(isHostOnlyChannel(IPC.projectSetupUnsubscribe)).toBe(false)
+ expect(isHostOnlyChannel(IPC.projectSetupEvent('p1'))).toBe(false)
+ expect(isHostOnlyChannel(IPC.ptyWrite)).toBe(false)
+ // Near-misses must not be swallowed by a sloppy prefix.
+ expect(isHostOnlyChannel('project-setup:run-something-else')).toBe(false)
+ expect(isHostOnlyChannel('notgithubControl:approve')).toBe(false)
+ })
+
+ it('carries the refusal wording the peer sees, so both shells answer identically', () => {
+ expect(HOST_ONLY_REFUSAL).toBe('host-control method is not available to relay peers')
+ })
+})
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
new file mode 100644
index 000000000..55931a263
--- /dev/null
+++ b/src/shared/host-control.ts
@@ -0,0 +1,42 @@
+import { IPC } from './ipc'
+
+/**
+ * HOST-ONLY channels: the RPC methods a relay GUEST may never reach, in ONE list both shells read.
+ *
+ * A relay peer (a paired phone, another desktop over 4c) is a first-class client of this machine's
+ * core — that is the point of the peer registry — but it is NOT the host's user. A small set of
+ * methods are the host's own control plane, and admitting one of them from a guest hands over
+ * something the guest could not otherwise have:
+ *
+ * - `githubControl:*` — the token/approval plane for the host's GitHub credentials.
+ * - `project-setup:run` — starts a script ON the host, in the host's shell, as the host's user.
+ * - `project-setup:consent-submit` — the ANSWER to the host's own trust prompt. Admitting `run`
+ * and this one together is the whole attack: a guest raises the prompt and then approves it
+ * itself, so a shared `.nodeterm/project.json` script executes with no human ever looking at a
+ * dialog. Either one alone is much weaker; the pair is a complete self-approval loop.
+ * - `project-setup:cancel` — the other side of the same run's control: a guest must not be able to
+ * kill the host's setup mid-write.
+ *
+ * DELIBERATELY NOT LISTED: `project-setup:subscribe`/`unsubscribe` and the `project-setup:event:*`
+ * push. They neither start nor authorize anything, and a peer that can see the canvas can already
+ * see that a setup is running. The gate is on ACTION, not on the namespace — which is also why
+ * this is an explicit list rather than a `project-setup:` prefix.
+ *
+ * This lives in `shared/` because it is a policy question, not a shell mechanism: two shells each
+ * carrying their own `startsWith` is exactly how one of them ends up a release behind the other.
+ */
+export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = ['githubControl:']
+
+export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
+ IPC.projectSetupRun,
+ IPC.projectSetupCancel,
+ IPC.projectSetupConsentSubmit
+])
+
+/** What a refused peer is told. One wording, so the two shells answer identically. */
+export const HOST_ONLY_REFUSAL = 'host-control method is not available to relay peers'
+
+export function isHostOnlyChannel(channel: string): boolean {
+ if (HOST_ONLY_CHANNELS.has(channel)) return true
+ return HOST_ONLY_CHANNEL_PREFIXES.some((prefix) => channel.startsWith(prefix))
+}