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(relay): make a project-scoped relay session an actual boundary

reviewb8804bbaa49e
diff --git a/CLAUDE.md b/CLAUDE.md
index 424c31324..28983539e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6741,6 +6741,27 @@ to the class, and no bare `.react-flow__viewport` rule carries `will-change`).
## Remote access (phone relay) — free, not Pro
+- **A Team Access invite that shares ONE project is a boundary, not a label**
+ (`core/relay/scoped-guest-policy.ts`, wired by `main/remote/relay-host.ts` as the core relay
+ host's hooks). The invite is consent to run commands IN that project, and nothing else: inbound is
+ an allowlist (`SCOPED`) where a node id must belong only to the shared project (or be one the
+ guest just created over `canvas:mut` that no project holds yet — the host saves on a debounce, so
+ a new terminal's first `pty:create` precedes its node on disk), paths realpath inside the project
+ root and outside userData (symlinks and dangling links refused), `pty:create` loses `sshRemote`
+ and defaults its cwd to the root, `workspace:save` is refused; outbound reuses the viewer policy's
+ per-project event/terminal-frame attribution. An unknown channel is refused, and the guard test
+ forces a decision for every relay-tab channel. `connectRelayHost` THROWS for a scoped session
+ given no scope deps rather than serve it unscoped. **What it does not claim**: the guest's own
+ terminal is a shell as the host's user and can `cd` anywhere or attach another tmux session; the
+ policy closes the app's RPC doors, not the OS. Secret-bearing RPCs are host-only for EVERY relay
+ peer (`shared/host-control.ts`, now also enforced in core `relay-host.ts` `serve`, so the Server
+ Edition's hosted peers meet it): `settings:*` (a peer that saved `modelGateway.baseUrl` and then
+ called `agent:discover-models` would have the keychain-held gateway key sent to its URL),
+ gateway credentials, `license:*`, `claude-accounts:*`/`codex-accounts:*`, `usage:*`, and the
+ pairing/relay trust plane. An UNSCOPED invite (Team Access seats) stays full access, and its copy
+ now says so. Known degrades of the scoped tab: the host-path picker starts at `/` and is refused
+ (navigate from the project instead), and an SSH project's terminals do not open over the relay.
+
- Phone relay remote access ("Reach this Mac from anywhere") is a **Core (free) feature** as of
2026-08-01 — the iOS app is itself paid, so a desktop Pro gate double-charged the same feature.
The former Pro gate AND the free-tier monthly quota (`core/relay-quota.ts`, `RelayQuotaBanner`,
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d35ffc41b..59d7248a0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -462,6 +462,15 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
test forces that: without one, the event simply never arrives. Deep version: CLAUDE.md § Hosted
team relay.
+- **...and in `src/core/relay/scoped-guest-policy.ts` too.** A Team Access invite that shares ONE
+ project is served through that allowlist: every relay-tab channel is in `SCOPED` (with a check
+ that its node / path / projectId belongs to the shared project) or in the reviewed
+ `SCOPED_REFUSED` set, and `scoped-guest-policy.guard.test.ts` fails on one that is neither. An
+ unlisted channel is refused to scoped guests; an event they must receive needs to be attributable
+ to the shared project (`filterScopedEvent`). Anything that touches the host's settings,
+ credentials, license or pairing belongs in `src/shared/host-control.ts` instead — refused to every
+ relay peer.
+
- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where
it is built and matched raw where it is used is a no-op on the machine you wrote it on and a
silent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` while
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index 85018c054..a1fda125e 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -87,7 +87,7 @@ function sharedRoots(ctx: AccessContext): string[] {
/** `p` is `root` or below it. Relative-path based, so a sibling like `/srv/app2` is not inside
* `/srv/app`, a root of `/` contains everything, and a path on another Windows drive is outside. */
-function within(root: string, p: string): boolean {
+export function within(root: string, p: string): boolean {
const rel = path.relative(root, p)
return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))
}
diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.ts
index 1c90af880..559beeb9f 100644
--- a/src/core/relay/relay-host.ts
+++ b/src/core/relay/relay-host.ts
@@ -53,6 +53,7 @@ import {
import { IPC } from '../../shared/ipc'
import { scopeWorkspaceToProject } from '../../shared/relay-workspace-scope'
import { outOfProjectScope } from './relay-project-scope'
+import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from '../../shared/host-control'
import type { Workspace } from '../../shared/types'
/**
@@ -437,6 +438,17 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
* Live frames and held ones (see `held`) both come through here, so they meet the same checks. */
const serve = (m: RpcRequest | RpcCast): void => {
if (clientId === null) return
+ // HOST-ONLY channels (shared/host-control.ts) are refused to EVERY relay peer, before any hook
+ // or dispatch — here, in core, so the Server Edition's hosted peers meet the same list the
+ // desktop's platform dispatch already enforced (a hosted Editor passes every role check).
+ if ((m.t === 'req' || m.t === 'cast') && isHostOnlyChannel(m.method)) {
+ if (m.t === 'req') {
+ socket.sendTunnelText(
+ JSON.stringify({ t: 'res', id: m.id, ok: false, error: { code: 'E_FORBIDDEN', message: HOST_ONLY_REFUSAL } })
+ )
+ }
+ return
+ }
if (m.t === 'req') {
// A hook may answer the request itself — it then never reaches a scope check or the core.
// Every hook call below is guarded: a throw is ANSWERED (E_HANDLER), never let into the
diff --git a/src/core/relay/scoped-guest-policy.guard.test.ts b/src/core/relay/scoped-guest-policy.guard.test.ts
new file mode 100644
index 000000000..4736568d6
--- /dev/null
+++ b/src/core/relay/scoped-guest-policy.guard.test.ts
@@ -0,0 +1,44 @@
+// Forces a decision whenever the relay tab gains a channel: every IPC.* a relay tab can send must be
+// allowlisted for a scoped guest (SCOPED, with its own argument check) or reviewed-and-refused
+// (SCOPED_REFUSED). Also: nothing host-only is ever allowlisted.
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { IPC } from '../../shared/ipc'
+import { isHostOnlyChannel } from '../../shared/host-control'
+import { SCOPED, SCOPED_REFUSED } from './scoped-guest-policy'
+
+const ROOT = path.resolve(__dirname, '../../..')
+const read = (p: string) => fs.readFileSync(path.join(ROOT, p), 'utf8').replace(/\r\n/g, '\n')
+const BUILDERS = ['buildRealApi', 'buildFilesApi', 'buildGitHubApi', 'buildAgentApi', 'buildCanvasApi', 'buildPresenceApi', 'buildClaudeApi', 'buildHostedApi']
+
+function body(src: string, fn: string): string {
+ const start = src.indexOf(`export function ${fn}(`)
+ if (start < 0) throw new Error(`builder ${fn} not found — update BUILDERS`)
+ const next = src.indexOf('\nexport function ', start + 1)
+ return src.slice(start, next < 0 ? undefined : next)
+}
+
+describe('scoped guest policy guard', () => {
+ const ipcValues = new Set((Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string'))
+ it('every decided method is a real IPC channel', () => {
+ for (const m of [...Object.keys(SCOPED), ...SCOPED_REFUSED]) expect(ipcValues.has(m), m).toBe(true)
+ })
+ it('no channel is decided twice', () => {
+ for (const m of SCOPED_REFUSED) expect(Object.hasOwn(SCOPED, m), `${m} is allowed AND refused`).toBe(false)
+ })
+ it('nothing host-only is allowlisted', () => {
+ for (const m of Object.keys(SCOPED)) expect(isHostOnlyChannel(m), m).toBe(false)
+ })
+ it('every relay-API channel has been decided', () => {
+ const ws = read('src/renderer/bridge/ws-bridge.ts')
+ const relay = read('src/renderer/bridge/relay-api.ts')
+ const src = BUILDERS.map((b) => body(ws, b)).join('\n') + relay
+ const names = new Set([...src.matchAll(/IPC\.([A-Za-z0-9_]+)/g)].map((x) => x[1]))
+ const undecided = [...names]
+ .map((n) => (IPC as Record<string, unknown>)[n])
+ .filter((v): v is string => typeof v === 'string')
+ .filter((v) => !Object.hasOwn(SCOPED, v) && !SCOPED_REFUSED.has(v))
+ expect(undecided, `classify these in scoped-guest-policy.ts: ${undecided.join(', ')}`).toEqual([])
+ })
+})
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.ts
new file mode 100644
index 000000000..63d376e61
--- /dev/null
+++ b/src/core/relay/scoped-guest-policy.test.ts
@@ -0,0 +1,260 @@
+// The project-scoped relay session as a boundary (scoped-guest-policy.ts), plus the host-only
+// channels every relay peer is refused (shared/host-control.ts, enforced in relay-host.ts `serve`).
+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { IPC } from '../../shared/ipc'
+import { encodePtyData } from '../../shared/rpc'
+import {
+ decideScopedAccess,
+ filterScopedEvent,
+ scopeForTest,
+ scopedGuestHooks,
+ type ScopedGuestDeps
+} from './scoped-guest-policy'
+import { connectRelayHost, type PeerAttach } from './relay-host'
+import { connectRelayClient } from './relay-client'
+import { transportPair } from './transport-pair'
+import { genKeyPair, publicKeyToB64 } from './e2ee'
+import type { RpcRequest } from '../../shared/rpc'
+
+let tmp: string
+let root: string // the shared project's folder
+let other: string // another project's folder
+let dataDir: string // this app's own data dir, planted INSIDE the shared root
+beforeAll(() => {
+ tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'scoped-guest-')))
+ root = path.join(tmp, 'alpha')
+ other = path.join(tmp, 'beta')
+ dataDir = path.join(root, 'appdata')
+ fs.mkdirSync(path.join(root, 'src'), { recursive: true })
+ fs.mkdirSync(other, { recursive: true })
+ fs.mkdirSync(dataDir, { recursive: true })
+ fs.writeFileSync(path.join(root, 'src', 'a.ts'), 'a')
+ fs.writeFileSync(path.join(other, 'secret.txt'), 's')
+ fs.writeFileSync(path.join(dataDir, 'license.json'), '{}')
+ // A symlink planted INSIDE the project that points OUT of it, and a dangling one.
+ fs.symlinkSync(path.join(other, 'secret.txt'), path.join(root, 'escape.txt'))
+ fs.symlinkSync(path.join(other, 'not-yet.txt'), path.join(root, 'dangling.txt'))
+ fs.symlinkSync(other, path.join(root, 'escape-dir'))
+})
+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }))
+
+const NODES: Record<string, string[]> = {
+ a1: ['alpha'],
+ b1: ['beta'],
+ both: ['alpha', 'beta'] // an id copied into another project
+}
+const SESSIONS: Record<string, string> = { sA: 'a1', sB: 'b1' }
+const deps = (): ScopedGuestDeps => ({
+ projectsOfNode: (id) => NODES[id] ?? [],
+ nodeOfSession: (sid) => SESSIONS[sid],
+ projectCwd: (p) => (p === 'alpha' ? root : p === 'beta' ? other : undefined),
+ hostDataDir: dataDir
+})
+const decide = (method: string, ...args: unknown[]) => decideScopedAccess('alpha', deps(), method, args)
+const allowed = (method: string, ...args: unknown[]) => decide(method, ...args).allow
+
+describe('scoped guest — refused outright', () => {
+ it('refuses an unknown or new channel (fail closed)', () => {
+ expect(allowed('some:new-channel')).toBe(false)
+ expect(allowed('constructor')).toBe(false)
+ })
+ it('refuses the host settings, license and whole-workspace writes', () => {
+ expect(allowed(IPC.settingsSave, {})).toBe(false)
+ expect(allowed(IPC.settingsLoad)).toBe(false)
+ expect(allowed(IPC.agentDiscoverModels, {})).toBe(false)
+ expect(allowed(IPC.licenseDeactivate)).toBe(false)
+ expect(allowed(IPC.workspaceSave, {})).toBe(false)
+ })
+})
+
+describe('scoped guest — terminals', () => {
+ it('opens a terminal for an in-project node, cwd defaulted to the project root', () => {
+ const d = decide(IPC.ptyCreate, { persistKey: 'a1', cols: 80, rows: 24, shell: '/bin/zsh' })
+ expect(d.allow).toBe(true)
+ expect(d.allow && d.args?.[0]).toMatchObject({ persistKey: 'a1', cwd: root, shell: '/bin/zsh' })
+ })
+ it('refuses to attach to another project\'s node, or a node shared with another project', () => {
+ expect(allowed(IPC.ptyCreate, { persistKey: 'b1', cols: 80, rows: 24 })).toBe(false)
+ expect(allowed(IPC.ptyCreate, { persistKey: 'both', cols: 80, rows: 24 })).toBe(false)
+ expect(allowed(IPC.ptyCreate, { persistKey: 'nobody', cols: 80, rows: 24 })).toBe(false)
+ expect(allowed(IPC.ptyCreate, { cols: 80, rows: 24 })).toBe(false)
+ })
+ it('refuses a cwd outside the project (incl. through a symlink) and a foreign owner project', () => {
+ expect(allowed(IPC.ptyCreate, { persistKey: 'a1', cwd: other, cols: 1, rows: 1 })).toBe(false)
+ expect(allowed(IPC.ptyCreate, { persistKey: 'a1', cwd: path.join(root, 'escape-dir'), cols: 1, rows: 1 })).toBe(false)
+ expect(allowed(IPC.ptyCreate, { persistKey: 'a1', cwd: path.join(root, 'src'), cols: 1, rows: 1 })).toBe(true)
+ expect(allowed(IPC.ptyCreate, { persistKey: 'a1', ownerProjectId: 'beta', cols: 1, rows: 1 })).toBe(false)
+ })
+ it('drops an ssh route the guest names', () => {
+ const d = decide(IPC.ptyCreate, {
+ persistKey: 'a1', cols: 1, rows: 1,
+ sshRemote: { controlPath: '/x', conn: { extraArgs: ['-oProxyCommand=touch /tmp/pwned'] }, remoteCwd: '/' }
+ })
+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).sshRemote).toBeUndefined()
+ })
+ it('judges session-id and persistKey verbs by the node', () => {
+ expect(allowed(IPC.ptyWrite, 'sA', 'ls\r')).toBe(true)
+ expect(allowed(IPC.ptyWrite, 'sB', 'ls\r')).toBe(false)
+ expect(allowed(IPC.ptyWrite, 'unknown', 'ls\r')).toBe(false)
+ expect(allowed(IPC.ptyCapture, 'a1')).toBe(true)
+ expect(allowed(IPC.ptyCapture, 'b1')).toBe(false)
+ expect(allowed(IPC.ptyDestroy, 'b1')).toBe(false)
+ expect(allowed(IPC.ptySendText, 'b1', 'x')).toBe(false)
+ expect(allowed(IPC.contextEnsure, 's', root, undefined, 'b1', 'claude')).toBe(false)
+ expect(allowed(IPC.contextEnsure, 's', root, undefined, 'a1', 'claude')).toBe(true)
+ })
+})
+
+describe('scoped guest — files and git', () => {
+ it('reads inside the root, refuses outside and through a planted symlink', () => {
+ expect(allowed(IPC.fsRead, path.join(root, 'src', 'a.ts'))).toBe(true)
+ expect(allowed(IPC.fsList, root)).toBe(true)
+ expect(allowed(IPC.fsRead, path.join(other, 'secret.txt'))).toBe(false)
+ expect(allowed(IPC.fsRead, path.join(root, '..', 'beta', 'secret.txt'))).toBe(false)
+ expect(allowed(IPC.fsRead, path.join(root, 'escape.txt'))).toBe(false)
+ expect(allowed(IPC.fsList, path.join(root, 'escape-dir'))).toBe(false)
+ expect(allowed(IPC.fsRead, '~/.ssh/id_rsa')).toBe(false)
+ expect(allowed(IPC.fsRead, 'relative.txt')).toBe(false)
+ })
+ it('never reaches the app data dir, even inside the shared root', () => {
+ expect(allowed(IPC.fsRead, path.join(dataDir, 'license.json'))).toBe(false)
+ })
+ it('writes a new file inside the root, refuses through a dangling symlink or an escaping dir', () => {
+ expect(allowed(IPC.fsWrite, path.join(root, 'src', 'new', 'b.ts'), 'x')).toBe(true)
+ expect(allowed(IPC.fsWrite, path.join(root, 'dangling.txt'), 'x')).toBe(false)
+ expect(allowed(IPC.fsWrite, path.join(root, 'escape-dir', 'planted.txt'), 'x')).toBe(false)
+ expect(allowed(IPC.fsMkdir, path.join(other, 'x'))).toBe(false)
+ })
+ it('jails git working directories and its option-shaped arguments', () => {
+ expect(allowed(IPC.gitStatus, root)).toBe(true)
+ expect(allowed(IPC.gitStatus, other)).toBe(false)
+ expect(allowed(IPC.gitShowFile, root, '--output=/tmp/x', 'a.ts')).toBe(false)
+ expect(allowed(IPC.gitShowFile, root, 'HEAD', 'a.ts')).toBe(true)
+ expect(allowed(IPC.gitDiff, root, path.join(other, 'secret.txt'), false, true)).toBe(false)
+ expect(allowed(IPC.gitDiff, root, 'src/a.ts', false, false)).toBe(true)
+ expect(allowed(IPC.gitSetActiveRemote, 'beta')).toBe(false)
+ })
+ it('allows a worktree inside the root or in the default `<root>.worktrees` sibling only', () => {
+ expect(allowed(IPC.gitWorktreeAdd, root, path.join(tmp, 'alpha.worktrees', 'feat'), 'feat', 'main', true)).toBe(true)
+ expect(allowed(IPC.gitWorktreeAdd, root, path.join(tmp, 'beta', 'feat'), 'feat', 'main', true)).toBe(false)
+ })
+})
+
+describe('scoped guest — canvas, board and GitHub', () => {
+ it('refuses board and issue calls naming another project', () => {
+ expect(allowed(IPC.boardLogSubscribe, 'alpha')).toBe(true)
+ expect(allowed(IPC.boardLogSubscribe, 'beta')).toBe(false)
+ expect(allowed(IPC.githubIssuesQuery, { projectId: 'beta' })).toBe(false)
+ expect(allowed(IPC.githubIssuesQuery, { projectId: 'alpha' })).toBe(true)
+ })
+ it('refuses a canvas mutation into another project, or adopting another project\'s node id', () => {
+ const node = (id: string) => ({ op: 'upsert', node: { id, kind: 'terminal', position: { x: 0, y: 0 } } })
+ expect(allowed(IPC.canvasMut, 'beta', node('fresh'))).toBe(false)
+ expect(allowed(IPC.canvasMut, 'alpha', node('b1'))).toBe(false)
+ expect(allowed(IPC.canvasMut, 'alpha', { op: 'remove', id: 'b1' })).toBe(false)
+ expect(allowed(IPC.canvasMut, 'alpha', node('a1'))).toBe(true)
+ })
+ it('a node the guest just created is in scope for its first terminal (before the host saves)', () => {
+ const hooks = scopedGuestHooks('alpha', deps())
+ const ask = (method: string, ...args: unknown[]) => hooks.access!(null as never, 'req', method, args)
+ expect(ask(IPC.ptyCreate, { persistKey: 'fresh', cols: 1, rows: 1 }).allow).toBe(false)
+ const upsert = { op: 'upsert', node: { id: 'fresh', kind: 'terminal', position: { x: 0, y: 0 } } }
+ expect(ask(IPC.canvasMut, 'alpha', upsert).allow).toBe(true)
+ expect(ask(IPC.ptyCreate, { persistKey: 'fresh', cols: 1, rows: 1 }).allow).toBe(true)
+ })
+})
+
+describe('scoped guest — what it receives', () => {
+ const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })
+ it('drops other projects\' events and the host log; keeps its own', () => {
+ const s = scopeForTest('alpha', deps())
+ const owners = new Map<string, string>()
+ expect(filterScopedEvent(ev(IPC.canvasMut, 'beta', { op: 'remove', id: 'b1' }), s, owners)).toBe(false)
+ expect(filterScopedEvent(ev(IPC.canvasMut, 'alpha', { op: 'remove', id: 'a1' }), s, owners)).toBe(true)
+ expect(filterScopedEvent(ev(IPC.agentStatus, { nodeId: 'b1' }), s, owners)).toBe(false)
+ expect(filterScopedEvent(ev(IPC.agentStatus, { nodeId: 'a1' }), s, owners)).toBe(true)
+ expect(filterScopedEvent(ev(IPC.logBatch, []), s, owners)).toBe(false)
+ expect(filterScopedEvent(ev(IPC.githubIssuesChanged('alpha'), [1]), s, owners)).toBe(true)
+ expect(filterScopedEvent(ev(IPC.githubIssuesChanged('beta'), [1]), s, owners)).toBe(false)
+ expect(filterScopedEvent(ev(IPC.workspaceExternalChange, { id: 'beta' }), s, owners)).toBe(false)
+ })
+ it('delivers terminal bytes only for the shared project\'s sessions', () => {
+ const hooks = scopedGuestHooks('alpha', deps())
+ const got: string[] = []
+ const sink = hooks.wrapSink!(null as never, {
+ sendText: () => {},
+ sendBinary: (b) => got.push(Buffer.from(b).toString('hex'))
+ })
+ sink.sendBinary(encodePtyData('sB', 'secret'))
+ sink.sendBinary(encodePtyData('sA', 'ok'))
+ expect(got.length).toBe(1)
+ })
+})
+
+// ── End to end, through the relay host's own serve loop ────────────────────────────────────────
+
+function openHost(hooks?: Parameters<typeof connectRelayHost>[0]['hooks']) {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const dispatched: RpcRequest[] = []
+ const casts: string[] = []
+ const attach: PeerAttach = {
+ attach: () => 1,
+ detach: () => {},
+ dispatch: async (_id, req) => { dispatched.push(req); return { t: 'res', id: req.id, ok: true, result: 'ok' } },
+ cast: (_id, method) => { casts.push(method) }
+ }
+ const opened: string[] = []
+ const frames: string[] = []
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach, transport: hostT, autoApprove: () => true,
+ sharedProjectId: hooks ? 'alpha' : undefined, hooks,
+ onPeerPending: () => {}, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ const client = connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => opened.push('peer'),
+ onFrame: (j) => frames.push(j), onPtyData: () => {}, onClose: () => {}
+ })
+ return { client, dispatched, casts, opened, frames }
+}
+
+describe('relay host — scoped session end to end', () => {
+ it('refuses out-of-scope requests without dispatching them, and serves in-scope ones', async () => {
+ const t = openHost(scopedGuestHooks('alpha', deps()))
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'req', id: 1, method: IPC.fsRead, args: [path.join(other, 'secret.txt')] }))
+ t.client.send(JSON.stringify({ t: 'req', id: 2, method: IPC.ptyCreate, args: [{ persistKey: 'b1', cols: 1, rows: 1 }] }))
+ t.client.send(JSON.stringify({ t: 'cast', method: IPC.ptyWrite, args: ['sB', 'rm -rf ~\r'] }))
+ t.client.send(JSON.stringify({ t: 'req', id: 3, method: IPC.fsRead, args: [path.join(root, 'src', 'a.ts')] }))
+ await vi.waitFor(() => expect(t.dispatched.map((r) => r.id)).toEqual([3]))
+ await vi.waitFor(() => expect(t.frames.filter((f) => f.includes('E_ROLE')).length).toBe(2))
+ expect(t.casts).toEqual([])
+ })
+})
+
+describe('relay host — host-only channels refused to every peer', () => {
+ it('refuses settings, license and credential channels even with no policy hooks', async () => {
+ const t = openHost()
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ const methods = [
+ IPC.settingsSave, IPC.settingsLoad, IPC.agentDiscoverModels, IPC.agentGatewayCredentialSave,
+ IPC.licenseActivate, IPC.licenseDeactivate, IPC.claudeAccountsAdd, IPC.usageRemote, IPC.relayHostInvite
+ ]
+ methods.forEach((method, i) => t.client.send(JSON.stringify({ t: 'req', id: 100 + i, method, args: [] })))
+ t.client.send(JSON.stringify({ t: 'cast', method: IPC.settingsSave, args: [{}] }))
+ t.client.send(JSON.stringify({ t: 'req', id: 999, method: IPC.workspaceLoad, args: [] }))
+ await vi.waitFor(() => expect(t.frames.filter((f) => f.includes('E_FORBIDDEN')).length).toBe(methods.length))
+ await vi.waitFor(() => expect(t.dispatched.map((r) => r.method)).toEqual([IPC.workspaceLoad]))
+ expect(t.casts).toEqual([])
+ })
+ it('still lets a hosted team\'s own verbs through to their interceptor', async () => {
+ const t = openHost()
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'req', id: 5, method: IPC.relayHostedSelf, args: [] }))
+ await vi.waitFor(() => expect(t.dispatched.map((r) => r.method)).toEqual([IPC.relayHostedSelf]))
+ })
+})
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
new file mode 100644
index 000000000..b1da0a083
--- /dev/null
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -0,0 +1,582 @@
+// A Team Access relay session bound to ONE project (`sharedProjectId`) is a SECURITY BOUNDARY, enforced
+// here, at the one choke point every relay-peer message crosses (relay-host.ts hooks).
+//
+// What the invite consents to, and what it does not (the policy these rules implement):
+// - It IS consent to run commands in the shared project: a scoped guest opens terminals and agents
+// there (`pty:create` with its own shell/command), edits its files, runs git in it, moves its
+// board cards and comments. None of that is gated beyond "is it in the shared project".
+// - It is NOT consent to other projects on this machine (their canvases, their live tmux sessions,
+// their transcripts, their files, their board and GitHub data), nor to the host's secrets and
+// control plane (settings, license, accounts, gateway credentials, pairing). Those are refused.
+//
+// How: DENY BY DEFAULT in both directions, like the hosted-team viewer policy (access-policy.ts),
+// but for a guest that is an EDITOR inside its project. Inbound, a method is reachable only if it is
+// in `SCOPED` below, and each entry carries its own argument check (a node id must belong to the
+// shared project, a path must realpath inside the project root, a projectId must be the shared one).
+// A channel added tomorrow is refused to scoped guests until someone decides otherwise; the guard
+// test (scoped-guest-policy.guard.test.ts) forces that decision for every channel the relay tab can
+// send. Outbound, the peer receives only the events the viewer policy already attributes to a
+// shared project (VIEW_EVENTS) plus the two an editor's tab also listens on.
+//
+// WHAT THIS DOES NOT CLAIM. A scoped guest has a shell in the project, as the host's user. From that
+// shell it can `cd` anywhere the user can, read any file the user can read, and even attach to
+// another project's tmux session on the shared socket. The fs/git jails and the node checks below
+// close the APP's doors (every RPC the relay tab speaks), which is what turns "scoped" from a UI
+// label into something an attacker cannot bypass by sending a crafted RPC — but they are not an OS
+// sandbox. What the shell cannot reach without a prompt are keychain-held secrets, and the host's
+// secret-bearing RPCs (settings:save + agent:discover-models, accounts, license) are host-only for
+// every peer (shared/host-control.ts). The invite copy says exactly this.
+import fs from 'node:fs'
+import path from 'node:path'
+import { IPC } from '../../shared/ipc'
+import type { UiSink } from '../ui-sink-registry'
+import type { AccessDecision, RelayHostHooks } from './relay-host'
+import {
+ filterOutboundBinary,
+ filterOutboundEvent,
+ narrowResponseForRole,
+ within,
+ type AccessContext,
+ type SubagentOwners
+} from './access-policy'
+
+export interface ScopedGuestDeps {
+ /** EVERY project that holds this node id, from the persisted canvases ([] = none). */
+ projectsOfNode(nodeId: string): readonly string[]
+ /** The node (canvas node id) a live terminal session runs; undefined = unknown session. */
+ nodeOfSession(sessionId: string): string | undefined
+ /** The shared project's LOCAL folder, or undefined (a cwd-less or SSH project). */
+ projectCwd(projectId: string): string | undefined
+ /** This app's own data directory (keys, license, every project's scrollback): never reachable
+ * through a scoped guest's fs/git calls, even when the shared root contains it. */
+ hostDataDir: string
+ /** `fs.realpath`; null = does not resolve. Injected for tests. */
+ realpath?(p: string): string | null
+ /** Does the path exist AS AN ENTRY (lstat — a dangling symlink counts)? Injected for tests. */
+ lexists?(p: string): boolean
+}
+
+type Check = (args: unknown[], s: Scope) => AccessDecision
+const OK: AccessDecision = { allow: true }
+const no = (message: string): AccessDecision => ({ allow: false, message })
+
+const OUTSIDE = 'That is outside the project shared with you.'
+const NODE_OUTSIDE = 'That terminal is not in the project shared with you.'
+const PATH_OUTSIDE = 'Only files inside the shared project folder are reachable.'
+const NO_ROOT = 'This shared project has no folder on the host.'
+const HOST_DATA = "The host app's own data folder is not reachable."
+const NOT_SCOPED = 'That is not available in a shared-project session.'
+
+const defaultRealpath = (p: string): string | null => {
+ try {
+ return fs.realpathSync(p)
+ } catch {
+ return null
+ }
+}
+const defaultLexists = (p: string): boolean => {
+ try {
+ fs.lstatSync(p)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** Everything a check needs about ONE session, built once per session. */
+interface Scope {
+ projectId: string
+ deps: Required<Pick<ScopedGuestDeps, 'realpath' | 'lexists'>> & ScopedGuestDeps
+ /** Node ids this guest introduced into the shared project over `canvas:mut` that no persisted
+ * canvas holds yet (the host renderer saves on a debounce, so a brand-new terminal's first
+ * `pty:create` routinely arrives before the node is on disk). Only ids NO project holds are
+ * recorded, so this can never adopt another project's node. */
+ newNodes: Set<string>
+}
+
+/** Every project holding `id`, with this session's own fresh nodes counted as the shared project's. */
+function projectsOf(id: string, s: Scope): readonly string[] {
+ const held = s.deps.projectsOfNode(id)
+ if (held.length > 0) return held
+ return s.newNodes.has(id) ? [s.projectId] : held
+}
+
+/** A node is in scope only when EVERY project holding its id is the shared one: node ids travel in
+ * git-shared project files, so an id copied into another project must not ride this session. */
+export function nodeInScope(id: unknown, s: Scope): boolean {
+ if (typeof id !== 'string' || !id) return false
+ const held = projectsOf(id, s)
+ return held.length > 0 && held.every((p) => p === s.projectId)
+}
+
+/** The shared project's root as a REAL path (a project opened through a symlink has a cwd that never
+ * equals its files' realpaths). null = no local folder, or a relative one (never a root). */
+function rootOf(s: Scope): string | null {
+ const cwd = s.deps.projectCwd(s.projectId)
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return null
+ return s.deps.realpath(cwd) ?? path.resolve(cwd)
+}
+
+function inHostData(real: string, s: Scope): boolean {
+ const d = s.deps.hostDataDir
+ if (typeof d !== 'string' || !d) return false
+ const resolved = path.resolve(d)
+ return within(s.deps.realpath(resolved) ?? resolved, real)
+}
+
+/**
+ * The REAL path `p` names, for a path that may not exist yet (a write, a mkdir, a new worktree): the
+ * realpath of the path itself, else of its nearest existing ancestor plus the missing tail. A path
+ * that EXISTS as an entry but does not resolve (a dangling symlink) is refused: a write through it
+ * lands wherever it points, and "wherever" is outside anything a lexical check can see.
+ */
+function realTarget(p: string, s: Scope): string | null {
+ const abs = path.resolve(p)
+ const direct = s.deps.realpath(abs)
+ if (direct) return direct
+ if (s.deps.lexists(abs)) return null
+ let dir = abs
+ const tail: string[] = []
+ for (;;) {
+ const parent = path.dirname(dir)
+ tail.unshift(path.basename(dir))
+ if (parent === dir) return null
+ dir = parent
+ const real = s.deps.realpath(dir)
+ if (real) return path.join(real, ...tail)
+ if (s.deps.lexists(dir)) return null
+ }
+}
+
+/** `p` is an absolute path whose REAL target sits inside the shared root and outside the host data
+ * dir. `mustExist`: reads need the path to resolve; writes may name a path that does not exist yet. */
+function jail(p: unknown, s: Scope, mustExist: boolean): { real: string } | { refuse: string } {
+ if (typeof p !== 'string' || !path.isAbsolute(p)) return { refuse: PATH_OUTSIDE }
+ const root = rootOf(s)
+ if (!root) return { refuse: NO_ROOT }
+ const real = mustExist ? s.deps.realpath(path.resolve(p)) : realTarget(p, s)
+ if (!real || !within(root, real)) return { refuse: PATH_OUTSIDE }
+ if (inHostData(real, s)) return { refuse: HOST_DATA }
+ return { real }
+}
+
+const decide = (j: { real: string } | { refuse: string }): AccessDecision => ('real' in j ? OK : no(j.refuse))
+
+const pass: Check = () => OK
+const projectArg0: Check = (a, s) => (a[0] === s.projectId ? OK : no(OUTSIDE))
+const projectField0: Check = (a, s) =>
+ a[0] !== null && typeof a[0] === 'object' && (a[0] as { projectId?: unknown }).projectId === s.projectId
+ ? OK
+ : no(OUTSIDE)
+const nodeArg0: Check = (a, s) => (nodeInScope(a[0], s) ? OK : no(NODE_OUTSIDE))
+const nodeField0: Check = (a, s) =>
+ a[0] !== null && typeof a[0] === 'object' && nodeInScope((a[0] as { nodeId?: unknown }).nodeId, s)
+ ? OK
+ : no(NODE_OUTSIDE)
+/** A terminal SESSION id (write/resize/flow): judged by the node the pty manager says it runs. */
+const sessionArg0: Check = (a, s) => {
+ const node = typeof a[0] === 'string' ? s.deps.nodeOfSession(a[0]) : undefined
+ return nodeInScope(node, s) ? OK : no(NODE_OUTSIDE)
+}
+const readArg0: Check = (a, s) => decide(jail(a[0], s, true))
+const writeArg0: Check = (a, s) => decide(jail(a[0], s, false))
+
+/** A git call whose FIRST argument is the working directory (every git verb but the ones below). */
+const gitCwd =
+ (rest: Check = pass): Check =>
+ (a, s) => {
+ const j = jail(a[0], s, true)
+ return 'real' in j ? rest(a, s) : no(j.refuse)
+ }
+
+/** `git diff` (cwd, file, staged, untracked): an untracked diff runs `git diff --no-index` against
+ * ANY file on the host, so that file is jailed by realpath too; a tracked pathspec is cwd-relative
+ * and git refuses one outside the repository. Pathspec magic (`:(top)…`) re-roots at the repo. */
+const gitDiff: Check = (a, s) => {
+ const cwd = jail(a[0], s, true)
+ if (!('real' in cwd)) return no(cwd.refuse)
+ const file = a[1]
+ if (typeof file !== 'string' || file.startsWith(':')) return no(PATH_OUTSIDE)
+ const target = path.resolve(cwd.real, file)
+ if (a[3]) return decide(jail(target, s, true))
+ const root = rootOf(s)
+ if (!root || !within(root, target)) return no(PATH_OUTSIDE)
+ return inHostData(target, s) ? no(HOST_DATA) : OK
+}
+
+/** `git show <ref>:<file>`: a ref starting with `-` is parsed as an OPTION (`--output=<file>` writes
+ * a file anywhere on the host). */
+const gitShowFile: Check = (a) => {
+ const ref = a[1]
+ if (ref !== undefined && ref !== null && (typeof ref !== 'string' || ref.startsWith('-'))) {
+ return no('That is not a revision name.')
+ }
+ return typeof a[2] === 'string' ? OK : no(PATH_OUTSIDE)
+}
+
+/** A worktree path: inside the shared root, or in the `<root>.worktrees` sibling the default
+ * worktree template (`../${repoName}.worktrees/${branch}`) creates. Anywhere else is refused. */
+const worktreePathIn = (p: unknown, s: Scope): AccessDecision => {
+ if (typeof p !== 'string' || !path.isAbsolute(p)) return no(PATH_OUTSIDE)
+ const root = rootOf(s)
+ if (!root) return no(NO_ROOT)
+ const real = realTarget(p, s)
+ if (!real) return no(PATH_OUTSIDE)
+ const sibling = path.join(path.dirname(root), `${path.basename(root)}.worktrees`)
+ if (!within(root, real) && !within(sibling, real)) return no(PATH_OUTSIDE)
+ return inHostData(real, s) ? no(HOST_DATA) : OK
+}
+const worktreeAddOrRemove: Check = (a, s) => {
+ const repo = jail(a[0], s, true)
+ if (!('real' in repo)) return no(repo.refuse)
+ return worktreePathIn(a[1], s)
+}
+
+/**
+ * `pty:create`: the guest may start a terminal (any shell or command — that is the invite) for a node
+ * of the shared project, in a working directory inside the project root. Rewritten, not just judged:
+ * - `sshRemote` is dropped. Its `conn.extraArgs` reach `ssh` on the host during the existence probe,
+ * and a guest never names an ssh route; a node that requires one (`requireRemote`) is then
+ * refused by the core instead of spawning locally.
+ * - a missing `cwd` becomes the project root (the core's default would be the host user's `$HOME`).
+ * - `ownerProjectId` may only name the shared project (it is recorded as the pane's owner, which
+ * agent messaging trusts).
+ */
+const ptyCreate: Check = (a, s) => {
+ const o = a[0]
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return no(NODE_OUTSIDE)
+ const opts = { ...(o as Record<string, unknown>) }
+ if (!nodeInScope(opts.persistKey, s)) return no(NODE_OUTSIDE)
+ if (opts.ownerProjectId !== undefined && opts.ownerProjectId !== s.projectId) return no(OUTSIDE)
+ delete opts.sshRemote
+ const root = rootOf(s)
+ if (opts.cwd === undefined || opts.cwd === null || opts.cwd === '') {
+ if (root) opts.cwd = root
+ else delete opts.cwd
+ } else {
+ const j = jail(opts.cwd, s, true)
+ if (!('real' in j)) return no(j.refuse)
+ }
+ return { allow: true, args: [opts, ...a.slice(1)] }
+}
+
+/**
+ * `canvas:mut` (projectId, mutation): only into the shared project, and only for a node that is in
+ * scope or that NO project holds yet (a node the guest is creating — recorded, so its `pty:create`
+ * is accepted before the host's debounced save lands). An upsert of another project's node id is
+ * refused: applied, it would put that id in the shared project and hand this session its terminal.
+ */
+const canvasMut: Check = (a, s) => {
+ if (a[0] !== s.projectId) return no(OUTSIDE)
+ const m = a[1]
+ if (!m || typeof m !== 'object') return no(OUTSIDE)
+ const mut = m as { op?: unknown; id?: unknown; node?: { id?: unknown } }
+ const id = mut.op === 'remove' ? mut.id : mut.node?.id
+ if (typeof id !== 'string' || !id) return no(OUTSIDE)
+ if (nodeInScope(id, s)) return OK
+ if (mut.op === 'upsert' && s.deps.projectsOfNode(id).length === 0) {
+ s.newNodes.add(id)
+ return OK
+ }
+ return no(NODE_OUTSIDE)
+}
+
+/**
+ * The channels a SCOPED guest may send, each with its argument check. Built from the channels the
+ * relay tab actually sends (the ws-bridge builders relay-api.ts spreads, and relay-api.ts itself —
+ * the guard test re-derives that list). Anything not here is refused.
+ */
+export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({
+ // Workspace: the load is narrowed to the shared project by relay-host.ts (scopeResponse). `save`
+ // is NOT here: a relay tab never saves the host workspace, and a whole-workspace save from a peer
+ // would replace every other project's index entry.
+ [IPC.workspaceLoad]: pass,
+ [IPC.workspaceProbeFolder]: readArg0,
+ [IPC.workspaceProjectFileState]: readArg0,
+ // Where the worktree dialog derives a default path from. A path, not a secret.
+ [IPC.appUserDataDir]: pass,
+
+ // Terminals. Every persistKey / session id must belong to the shared project.
+ [IPC.ptyCreate]: ptyCreate,
+ [IPC.ptyWrite]: sessionArg0,
+ [IPC.ptyResize]: sessionArg0,
+ [IPC.ptyFlow]: sessionArg0,
+ // Detaches the sender's OWN view only (the core checks it subscribes); the session keeps running.
+ [IPC.ptyKill]: pass,
+ [IPC.ptyDestroy]: nodeArg0,
+ [IPC.ptyRecycle]: nodeArg0,
+ [IPC.ptyCapture]: nodeArg0,
+ [IPC.ptySessionAge]: nodeArg0,
+ [IPC.ptyReadScrollback]: nodeArg0,
+ [IPC.ptySendText]: nodeArg0,
+ [IPC.ptyTmuxStatus]: pass,
+ [IPC.ptyPaneCommand]: nodeArg0,
+ [IPC.ptyPaneCwd]: nodeArg0,
+ [IPC.ptyPaneOwner]: nodeArg0,
+ [IPC.ptyTerminateForeground]: nodeArg0,
+ [IPC.ptyReadSessionName]: nodeArg0,
+
+ // Files: realpath-jailed to the project root (reads must resolve; writes may create).
+ [IPC.fsList]: readArg0,
+ [IPC.fsRead]: readArg0,
+ [IPC.fsReadBinary]: readArg0,
+ [IPC.fsExists]: writeArg0,
+ [IPC.fsWrite]: writeArg0,
+ [IPC.fsMkdir]: writeArg0,
+ [IPC.filesQuickOpen]: readArg0,
+ [IPC.filesDownloadTicket]: readArg0,
+ // Writes into this app's own uploads dir under an app-chosen name (a pasted screenshot's bytes).
+ [IPC.filesSaveUpload]: pass,
+ [IPC.filesSaveCanvasImage]: projectArg0,
+
+ // Git: the working directory realpath-jailed to the project root, plus per-verb argument checks.
+ [IPC.gitStatus]: gitCwd(),
+ [IPC.gitInit]: gitCwd(),
+ [IPC.gitClone]: gitCwd(),
+ [IPC.gitCloneAbort]: pass,
+ [IPC.gitCloneDefaultParent]: pass,
+ [IPC.gitCommit]: gitCwd(),
+ [IPC.gitPush]: gitCwd(),
+ [IPC.gitPull]: gitCwd(),
+ [IPC.gitSync]: gitCwd(),
+ [IPC.gitPublish]: gitCwd(),
+ [IPC.gitStage]: gitCwd(),
+ [IPC.gitUnstage]: gitCwd(),
+ [IPC.gitStageAll]: gitCwd(),
+ [IPC.gitUnstageAll]: gitCwd(),
+ [IPC.gitDiff]: gitDiff,
+ [IPC.gitDiscard]: gitCwd(),
+ [IPC.gitSwitchBranch]: gitCwd(),
+ [IPC.gitCreateBranch]: gitCwd(),
+ [IPC.gitShowFile]: gitCwd(gitShowFile),
+ [IPC.commitGenerate]: gitCwd(),
+ [IPC.gitHistory]: gitCwd(),
+ [IPC.gitCommitFiles]: gitCwd(),
+ [IPC.gitRemoteCommitUrl]: gitCwd(),
+ [IPC.gitMerge]: gitCwd(),
+ [IPC.gitRebase]: gitCwd(),
+ [IPC.gitDeleteBranch]: gitCwd(),
+ [IPC.gitRenameBranch]: gitCwd(),
+ [IPC.gitFetch]: gitCwd(),
+ [IPC.gitForcePush]: gitCwd(),
+ [IPC.gitStashPush]: gitCwd(),
+ [IPC.gitStashPop]: gitCwd(),
+ [IPC.gitRevert]: gitCwd(),
+ [IPC.gitBranchAt]: gitCwd(),
+ [IPC.gitCheckoutCommit]: gitCwd(),
+ [IPC.gitRepoRoot]: gitCwd(),
+ [IPC.gitWorktreeList]: gitCwd(),
+ [IPC.gitWorktreeAdd]: worktreeAddOrRemove,
+ [IPC.gitWorktreeMerge]: gitCwd(),
+ [IPC.gitWorktreeRemove]: worktreeAddOrRemove,
+ [IPC.gitSetActiveRemote]: projectArg0,
+
+ // Agent context: the transcript read behind the meter is keyed by node (args: sessionId, cwd,
+ // accountId, nodeId, agentId), so only the shared project's nodes.
+ [IPC.contextEnsure]: (a, s) => (nodeInScope(a[3], s) ? OK : no(NODE_OUTSIDE)),
+
+ // Board log + GitHub issues: the shared project only (relay-host.ts's class jail runs as well).
+ // read/append pass HERE on purpose: relay-host.ts's own board-log jail (which always runs on a
+ // scoped session) answers an out-of-scope project with the degraded "unknown project" shape a
+ // relay tab already handles, without dispatching. Refusing them here would change that answer.
+ [IPC.boardLogAppend]: pass,
+ [IPC.boardLogRead]: pass,
+ [IPC.boardLogSubscribe]: projectArg0,
+ [IPC.boardLogUnsubscribe]: projectArg0,
+ [IPC.githubIssuesSubscribe]: projectField0,
+ [IPC.githubIssuesQuery]: projectField0,
+ [IPC.githubIssuesMove]: projectField0,
+ [IPC.githubIssuesClaimPullAutoMove]: projectField0,
+ [IPC.githubIssuesNotePullWaits]: projectField0,
+ [IPC.githubIssuesUnsubscribe]: projectArg0,
+ [IPC.githubIssuesRefresh]: projectArg0,
+ [IPC.githubIssuesCreateLabels]: projectArg0,
+ [IPC.githubIssuesClearCache]: projectArg0,
+ [IPC.githubIssuesPullStatus]: projectArg0,
+ [IPC.githubIssuesChasePulls]: projectArg0,
+ [IPC.githubIssuesPullChecks]: projectArg0,
+ [IPC.githubProjectAvatar]: projectArg0,
+
+ // Agent status actions, per node. The subagent snapshot's RESPONSE is narrowed below.
+ [IPC.agentSubagentSnapshot]: pass,
+ [IPC.agentHibernated]: nodeField0,
+ [IPC.agentAnswerPermission]: nodeField0,
+ [IPC.agentAckDone]: nodeArg0,
+ [IPC.claudeCliCaps]: pass,
+
+ // Canvas + presence.
+ [IPC.canvasMut]: canvasMut,
+ [IPC.presenceHello]: pass,
+ [IPC.presenceCursor]: pass,
+ [IPC.presenceFocus]: pass,
+ [IPC.presenceChat]: pass,
+ [IPC.presenceDino]: pass,
+ [IPC.presenceProject]: pass
+})
+
+/**
+ * Relay-API channels reviewed and deliberately REFUSED to a scoped guest (the guard test requires
+ * every channel the relay tab's builders mention to be in SCOPED or here). Listing one changes
+ * nothing at runtime — the default is refusal — it records that someone DECIDED. Most of these are
+ * never sent by a relay tab at all (relay-api.ts keeps them LOCAL), which is exactly why a peer that
+ * sends one is not a relay tab doing its job.
+ */
+export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([
+ // A whole-workspace write from a peer would replace the host's other projects.
+ IPC.workspaceSave,
+ // Project settings / setup / trust: relay-api.ts keeps these LOCAL; the setup ones are host-only.
+ IPC.projectSettingsRead,
+ IPC.projectSettingsWriteShared,
+ IPC.projectSettingsUpdateLocal,
+ IPC.projectSettingsLaunchInfo,
+ IPC.projectSetupRun,
+ IPC.projectSetupCancel,
+ IPC.projectSetupConsentSubmit,
+ IPC.projectSetupRequestTrust,
+ IPC.projectSetupSubscribe,
+ IPC.projectSetupUnsubscribe,
+ IPC.worktreeMaterializeShared,
+ // Host settings and credentials (also host-only for every peer, shared/host-control.ts).
+ IPC.settingsLoad,
+ IPC.settingsSave,
+ IPC.agentDiscoverModels,
+ IPC.agentGatewayCredentialStatus,
+ IPC.agentGatewayCredentialSave,
+ IPC.agentGatewayCredentialClear,
+ // The host's debug log spans every project; relay-api.ts keeps `logs` LOCAL.
+ IPC.logSnapshot,
+ IPC.logClear,
+ IPC.logSubscribe,
+ IPC.logUnsubscribe,
+ // GitHub credential plane (host-only prefix) — relay-api.ts uses the LOCAL githubControl.
+ IPC.githubControlStatus,
+ IPC.githubControlApprove,
+ IPC.githubControlRevoke,
+ IPC.githubControlSelectProvider,
+ IPC.githubControlSaveToken,
+ IPC.githubControlClearToken,
+ // A relay tab's seed is a local no-op (relay-api.ts); it writes the mirror's session identities.
+ IPC.agentSeedIdentity,
+ // Server→client events (a client cannot invoke them; what a scoped guest RECEIVES is decided by
+ // `filterScopedEvent`).
+ IPC.workspaceMigrated,
+ IPC.workspaceCorruptRecovered,
+ IPC.workspaceExternalChange,
+ IPC.workspaceServerChange,
+ IPC.projectTrustChanged,
+ IPC.projectSetupConsentRequest,
+ IPC.projectSetupConsentDismiss,
+ IPC.gitCloneProgress,
+ IPC.contextUpdate,
+ IPC.logBatch,
+ IPC.agentStatus,
+ IPC.agentUnreadClear,
+ IPC.agentSubagentActivity,
+ IPC.presenceSync,
+ IPC.presencePeer,
+ // Hosted-team verbs: answered by the Server Edition's hosted service only, never on Team Access.
+ IPC.relayHostedSelf,
+ IPC.relayHostedPending,
+ IPC.relayHostedInviteCode,
+ IPC.relayHostedApprove,
+ IPC.relayHostedDeny,
+ IPC.relayHostedPeerPending,
+ IPC.relayHostedPendingClosed
+])
+
+function makeScope(projectId: string, deps: ScopedGuestDeps): Scope {
+ return {
+ projectId,
+ deps: { ...deps, realpath: deps.realpath ?? defaultRealpath, lexists: deps.lexists ?? defaultLexists },
+ newNodes: new Set()
+ }
+}
+
+function decideWith(method: string, args: unknown[], s: Scope): AccessDecision {
+ if (typeof method !== 'string' || !Object.hasOwn(SCOPED, method)) return no(NOT_SCOPED)
+ return SCOPED[method](Array.isArray(args) ? args : [], s)
+}
+
+/** Test seam: one decision against a fresh scope. Production goes through `scopedGuestHooks`. */
+export function decideScopedAccess(
+ projectId: string,
+ deps: ScopedGuestDeps,
+ method: string,
+ args: unknown[]
+): AccessDecision {
+ return decideWith(method, args, makeScope(projectId, deps))
+}
+
+/** The access-policy context for this scope, read as a viewer of the ONE shared project: its event
+ * and terminal-frame attribution is exactly "does this belong to the shared project". */
+function viewCtx(s: Scope): AccessContext {
+ const root = s.deps.projectCwd(s.projectId)
+ return {
+ role: 'viewer',
+ sharedProjects: new Set([s.projectId]),
+ projectsOfNode: (id) => projectsOf(id, s),
+ nodeOfSession: (sid) => s.deps.nodeOfSession(sid),
+ projectCwds: () => (typeof root === 'string' && root ? [root] : []),
+ hostDataDir: s.deps.hostDataDir,
+ realpath: s.deps.realpath,
+ isFile: () => false
+ }
+}
+
+/** Two events an editor's relay tab listens on that the viewer allowlist does not carry. */
+function scopedExtraEvent(json: string, s: Scope): boolean | null {
+ let m: unknown
+ try {
+ m = JSON.parse(json)
+ } catch {
+ return null
+ }
+ const channel = m !== null && typeof m === 'object' ? (m as { channel?: unknown }).channel : undefined
+ if (typeof channel !== 'string') return null
+ if (channel === IPC.gitCloneProgress) return true
+ const gh = IPC.githubIssuesChanged('')
+ if (channel.startsWith(gh)) return channel.slice(gh.length) === s.projectId
+ return null
+}
+
+/** true = deliver this event to the scoped guest. Exported for the test. */
+export function filterScopedEvent(json: string, s: Scope, owners: SubagentOwners): boolean {
+ const extra = scopedExtraEvent(json, s)
+ if (extra !== null) return extra
+ return filterOutboundEvent(json, viewCtx(s), owners)
+}
+
+/**
+ * The hooks that make a Team Access session bound to `projectId` a boundary. Every peer message is
+ * judged by `SCOPED` (inbound), `filterScopedEvent` / terminal-frame attribution (outbound), and the
+ * subagent snapshot is narrowed to the shared project's nodes.
+ */
+export function scopedGuestHooks(projectId: string, deps: ScopedGuestDeps): RelayHostHooks {
+ const s = makeScope(projectId, deps)
+ return {
+ access: (_session, _kind, method, args) => decideWith(method, args, s),
+ wrapSink: (_session, sink: UiSink): UiSink => {
+ const owners: SubagentOwners = new Map()
+ const safe = (judge: () => boolean): boolean => {
+ try {
+ return judge()
+ } catch {
+ return false
+ }
+ }
+ return {
+ sendText: (json) => {
+ if (safe(() => filterScopedEvent(json, s, owners))) sink.sendText(json)
+ },
+ sendBinary: (buf) => {
+ if (safe(() => filterOutboundBinary(buf, viewCtx(s)))) sink.sendBinary(buf)
+ },
+ bufferedAmount: () => sink.bufferedAmount?.() ?? 0
+ }
+ },
+ narrowResponse: (_session, method, result) => narrowResponseForRole(method, result, viewCtx(s))
+ }
+}
+
+/** TEST ONLY: a scope to drive `filterScopedEvent` / `nodeInScope` directly. */
+export const scopeForTest = makeScope
diff --git a/src/main/index.ts b/src/main/index.ts
index 1f3a4d20b..c9428005e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -4268,7 +4268,17 @@ app.whenReady().then(async () => {
// CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the
// phone still uses the legacy flow). Inert until `relay:host:start` — a solo user pays nothing.
// Revocation reaches its sessions via `killRelayHostsByPeerKey` (peerRevoker, above).
- initRelayHost(win, corePlatform, {})
+ initRelayHost(win, corePlatform, {
+ // A project-scoped seat is judged message by message against THIS core's own records: which
+ // projects hold a node (persisted canvases), which node a live session runs, and the project's
+ // local folder. Never anything the peer sends. See core/relay/scoped-guest-policy.ts.
+ scope: {
+ projectsOfNode: (nodeId) => workspaceStore.projectIdsForNode(nodeId),
+ nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),
+ projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),
+ hostDataDir: app.getPath('userData')
+ }
+ })
// Standing (phone) relay host: keep a host connection registered so a paired phone can reach
// this Mac from anywhere. Honors settings.phoneAccessEnabled internally.
const standingHost = initStandingHost(win, ptyManager, () => settingsStore.get(), listProjectsOutput, hostBridge)
diff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.ts
index f686f00a3..1fa8d1531 100644
--- a/src/main/remote/relay-host-service.test.ts
+++ b/src/main/remote/relay-host-service.test.ts
@@ -139,7 +139,14 @@ function wireHost(): {
isPremium: () => true,
relayAllowed: () => true,
getEntitlement: () => 'ent-abc',
- licensedSeats: () => 3
+ licensedSeats: () => 3,
+ // A scoped seat needs its policy deps; every node here belongs to whichever project is shared.
+ scope: {
+ projectsOfNode: () => [],
+ nodeOfSession: () => undefined,
+ projectCwd: () => undefined,
+ hostDataDir: '/nonexistent-app-data'
+ }
})
let peerGate: TrustGate | null = null
diff --git a/src/main/remote/relay-host-service.ts b/src/main/remote/relay-host-service.ts
index 71b0144fb..e023f4787 100644
--- a/src/main/remote/relay-host-service.ts
+++ b/src/main/remote/relay-host-service.ts
@@ -36,6 +36,7 @@ import { loadOrCreatePeerKeyPair } from './peer-identity'
import { isPremium as licenseIsPremium, getStoredEntitlement, licensedSeats as licenseSeats } from '../../core/license'
import { RELAY_URL, relayAllowed as hostRelayAllowed, mintPairingToken } from './host-service'
import { canAcceptSeat } from './seat-cap'
+import type { ScopedGuestDeps } from '../../core/relay/scoped-guest-policy'
/** Thrown (as an Error message) when a new invite would exceed the licensed seat cap. The renderer
* maps it to "All seats in use — add a seat." Host-side/UX enforcement only (see below). */
@@ -59,6 +60,9 @@ export interface RelayHostDeps {
licensedSeats?: () => number
/** TEST ONLY: override the wire-up (defaults to `connectRelayHost`). */
connect?: typeof connectRelayHost
+ /** What a project-scoped seat's policy reads from this core (scoped-guest-policy.ts). A scoped
+ * invite without it is refused (connectRelayHost throws before any socket opens). */
+ scope?: ScopedGuestDeps
}
/** Metadata options for a new seat. `email` is a DISPLAY label only (never trust/identity — the SAS
@@ -154,7 +158,9 @@ export function initRelayHost(
platform,
transport: deps.transport,
// The single project this hosting session shares with the peer. Absent → unscoped, as before.
+ // Present → every peer message is judged by the scoped-guest policy over `deps.scope`.
sharedProjectId: projectId,
+ scope: deps.scope,
// The SAS is known — ask the human to compare it. NOTHING is served yet. Reuse the reserved
// id (do NOT mint a fresh one) so onOpen/onClose/revoke all name the same seat.
onPeerPending: (s) => {
diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.ts
index 799fce835..86f2e48f7 100644
--- a/src/main/remote/relay-host.test.ts
+++ b/src/main/remote/relay-host.test.ts
@@ -69,6 +69,10 @@ import { presenceHub } from '../../core/presence/hub'
import { initCanvasSync } from '../../core/canvas-sync'
import { initPlatform, resetPlatformForTests } from '../../core/platform'
import { IPC } from '../../shared/ipc'
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type { ScopedGuestDeps } from '../../core/relay/scoped-guest-policy'
import { decodePtyData, E_UNAUTHORIZED } from '../../shared/rpc'
const decoder = new TextDecoder()
@@ -83,6 +87,16 @@ let platform: ElectronPlatform
* A host session bridged to a REAL peer relay socket over an in-process transport pair. `buffered`
* is the host transport's ws.bufferedAmount — the number the sink must surface.
*/
+/** The shared project's folder in the scoped tests (a real directory: the policy realpaths it). */
+const SHARED_ROOT = mkdtempSync(join(tmpdir(), 'relay-host-scope-'))
+/** A scope where every node belongs to the shared project `proj-1`, rooted at SHARED_ROOT. */
+const testScope = (): ScopedGuestDeps => ({
+ projectsOfNode: () => ['proj-1'],
+ nodeOfSession: () => undefined,
+ projectCwd: (p) => (p === 'proj-1' ? SHARED_ROOT : undefined),
+ hostDataDir: join(SHARED_ROOT, '..', 'no-such-app-data')
+})
+
function openHostAgainstFakeRelay(opts?: {
bufferedAmount?: () => number
sharedProjectId?: string
@@ -147,6 +161,7 @@ function openHostAgainstFakeRelay(opts?: {
platform,
transport: hostT,
sharedProjectId: opts?.sharedProjectId,
+ scope: opts?.sharedProjectId ? testScope() : undefined,
onPeerPending: (s) => pending.push(s),
onOpen: (s) => opens.push(s),
onClose: () => {
@@ -383,7 +398,7 @@ describe('relay host — workspace:load is scoped to the shared project', () =>
const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
await s.openMutually()
- s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 8, method: IPC.gitStatus, args: ['/w'] }))
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 8, method: IPC.gitStatus, args: [SHARED_ROOT] }))
await vi.waitFor(() =>
expect(JSON.parse(s.textFrames.at(-1)!)).toMatchObject({
t: 'res',
@@ -436,8 +451,10 @@ describe('relay host — GitHub issue RPCs are scoped to the shared project', ()
})).toHaveLength(methods.length))
const responses = s.textFrames.map((frame) => JSON.parse(frame))
.filter((message) => message.t === 'res' && message.id >= 100)
+ // Refused by the scoped-guest policy (E_ROLE) before the class jail (E_FORBIDDEN) is reached;
+ // either way nothing is dispatched.
expect(responses.every((response) =>
- response.ok === false && response.error.code === 'E_FORBIDDEN')).toBe(true)
+ response.ok === false && ['E_FORBIDDEN', 'E_ROLE'].includes(response.error.code))).toBe(true)
expect(reached).toEqual([])
})
@@ -478,7 +495,7 @@ describe('relay host — project-scoped channel CLASSES fail closed', () => {
args: [{ projectId: 'proj-2', nodeId: 'n', add: ['klbl-x'] }]
}))
const res = await collect(s, 301)
- expect(res).toMatchObject({ ok: false, error: { code: 'E_FORBIDDEN' } })
+ expect(res).toMatchObject({ ok: false })
expect(reached).toEqual([])
})
@@ -488,17 +505,17 @@ describe('relay host — project-scoped channel CLASSES fail closed', () => {
const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
await s.openMutually()
s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 302, method: 'githubIssues:future-verb', args: ['proj-1'] }))
- expect(await collect(s, 302)).toMatchObject({ ok: false, error: { code: 'E_FORBIDDEN' } })
+ expect(await collect(s, 302)).toMatchObject({ ok: false })
expect(reached).toEqual([])
})
it('lets the shared project through to dispatch', async () => {
const reached: unknown[] = []
- platform.handle('projects.editCardLabels', async (...args: unknown[]) => { reached.push(args); return 'ok' })
+ platform.handle(IPC.githubIssuesRefresh, async (...args: unknown[]) => { reached.push(args); return 'ok' })
const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
await s.openMutually()
s.peerSendsTunnelText(JSON.stringify({
- t: 'req', id: 303, method: 'projects.editCardLabels', args: [{ projectId: 'proj-1', nodeId: 'n', add: ['l'] }]
+ t: 'req', id: 303, method: IPC.githubIssuesRefresh, args: ['proj-1', false]
}))
expect(await collect(s, 303)).toMatchObject({ ok: true })
expect(reached).toHaveLength(1)
@@ -632,3 +649,42 @@ describe('relay host — teardown mirrors src/server/ws.ts', () => {
killRelayHostsByPeerKey('some-other-key')
})
})
+
+describe('relay host — a project-scoped session is a boundary (scoped-guest-policy)', () => {
+ it('refuses to open a scoped session with no scope policy', () => {
+ expect(() =>
+ connectRelayHost({
+ url: 'wss://relay.example', token: 'tok', ourKeys: genKeyPair(), platform,
+ transport: { bufferedAmount: 0, send: () => {}, close: () => {}, onMessage: () => {}, onClose: () => {} },
+ sharedProjectId: 'proj-1',
+ onPeerPending: () => {}, onOpen: () => {}, onClose: () => {}
+ })
+ ).toThrow(/scope policy/)
+ })
+
+ it('refuses files outside the shared folder, settings:save and an unknown channel before dispatch', async () => {
+ const reached: string[] = []
+ for (const m of [IPC.fsRead, IPC.settingsSave, 'brand:new-channel']) {
+ platform.handle(m, async () => { reached.push(m); return 'x' })
+ }
+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
+ await s.openMutually()
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 401, method: IPC.fsRead, args: ['/etc/hosts'] }))
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 402, method: IPC.settingsSave, args: [{}] }))
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 403, method: 'brand:new-channel', args: [] }))
+ await vi.waitFor(() =>
+ expect(s.textFrames.map((f) => JSON.parse(f)).filter((m) => m.id >= 401 && m.ok === false)).toHaveLength(3)
+ )
+ expect(reached).toEqual([])
+ })
+
+ it('an unscoped session still reaches files (full access, as its invite copy says)', async () => {
+ platform.handle(IPC.fsRead, async () => 'contents')
+ const s = openHostAgainstFakeRelay()
+ await s.openMutually()
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 404, method: IPC.fsRead, args: ['/etc/hosts'] }))
+ await vi.waitFor(() =>
+ expect(s.textFrames.map((f) => JSON.parse(f)).find((m) => m.id === 404)).toMatchObject({ ok: true, result: 'contents' })
+ )
+ })
+})
diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.ts
index f07b69bb6..cc8ea9561 100644
--- a/src/main/remote/relay-host.ts
+++ b/src/main/remote/relay-host.ts
@@ -19,8 +19,10 @@
// with E_UNAUTHORIZED and never touches a handler. A pairing grants shell access; the SAS is the
// only thing between a relay MITM and that shell.
//
-// SCOPE: this is the DESKTOP-peer vocabulary (the invited peer is fully trusted, as the invite copy
-// states). The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with
+// SCOPE: this is the DESKTOP-peer vocabulary. An UNSCOPED invite (Team Access) is fully trusted, as
+// its copy states ("full access to this Mac as you"). A SCOPED invite (`sharedProjectId`) is judged
+// message by message by `scopedGuestHooks` (src/core/relay/scoped-guest-policy.ts): the shared
+// project's terminals, files, git and board, and nothing of the host's other projects or secrets. The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with
// its deny-by-default fs jail — and is deliberately NOT routed through this dispatch path.
//
// THE MECHANISM LIVES IN CORE (src/core/relay/relay-host.ts, docs/hosted-team-relay.md): the
@@ -41,6 +43,7 @@ import type { ElectronPlatform } from '../platform-electron'
import { registerPeerSink, unregisterPeerSink } from '../peer-registry'
import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'
import { updateApprovedDevices } from './approved-devices'
+import { scopedGuestHooks, type ScopedGuestDeps } from '../../core/relay/scoped-guest-policy'
export { killRelayHostsByPeerKey }
@@ -48,8 +51,12 @@ export { killRelayHostsByPeerKey }
* a peer with a reason (a revoke closes it), so the desktop surface stays exactly what it was. */
export type RelayHostSession = Omit<CoreRelayHostSession, 'deny'>
-export interface ConnectRelayHostOptions extends Omit<CoreOptions, 'attach' | 'pins'> {
+export interface ConnectRelayHostOptions extends Omit<CoreOptions, 'attach' | 'pins' | 'hooks'> {
platform: ElectronPlatform
+ /** What the scoped-guest policy reads from this core (project membership, live sessions, the
+ * project folder). REQUIRED whenever `sharedProjectId` is set: a scoped session without it is
+ * refused at connect rather than served as if it were unscoped. */
+ scope?: ScopedGuestDeps
}
/** How a mutually-approved peer joins THIS desktop's core. `unregisterPeerSink` IS the ONE teardown
@@ -79,6 +86,18 @@ function desktopPins(): PinStore {
}
export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {
- const { platform, ...rest } = opts
- return connectCoreRelayHost({ ...rest, attach: desktopAttach(platform), pins: desktopPins() })
+ const { platform, scope, ...rest } = opts
+ // A session bound to one project is served through the scoped policy, or not at all. Failing
+ // here (before any socket opens) is the point: the alternative is a "scoped" invite that serves
+ // everything, which is the bug this policy exists to close.
+ if (rest.sharedProjectId && !scope) {
+ throw new Error('A project-scoped relay session needs its scope policy.')
+ }
+ const hooks = rest.sharedProjectId && scope ? scopedGuestHooks(rest.sharedProjectId, scope) : undefined
+ return connectCoreRelayHost({
+ ...rest,
+ attach: desktopAttach(platform),
+ pins: desktopPins(),
+ ...(hooks ? { hooks } : {})
+ })
}
diff --git a/src/main/remote/relay-scope-wiring.test.ts b/src/main/remote/relay-scope-wiring.test.ts
new file mode 100644
index 000000000..9dc1c6428
--- /dev/null
+++ b/src/main/remote/relay-scope-wiring.test.ts
@@ -0,0 +1,18 @@
+// The desktop shell must hand the relay host its scoped-guest policy deps. Without them a
+// project-scoped invite throws at connect (fail closed) — correct, but it would mean Team Access
+// sharing one project stopped working. Pinned at source level because index.ts is not importable.
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+
+describe('initRelayHost wiring', () => {
+ it('passes the scope deps from this core\'s own records', () => {
+ const src = fs.readFileSync(path.resolve(__dirname, '../index.ts'), 'utf8').replace(/\r\n/g, '\n')
+ const at = src.indexOf('initRelayHost(win, corePlatform, {')
+ expect(at).toBeGreaterThan(0)
+ const call = src.slice(at, src.indexOf('\n })', at))
+ for (const needle of ['scope:', 'workspaceStore.projectIdsForNode', 'ptyManager.nodeOfSession', 'workspaceStore.localCwdForProject', "app.getPath('userData')"]) {
+ expect(call, needle).toContain(needle)
+ }
+ })
+})
diff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsx
index ec5c26d74..72db52a1b 100644
--- a/src/renderer/components/RemoteAccessDialog.tsx
+++ b/src/renderer/components/RemoteAccessDialog.tsx
@@ -4,7 +4,7 @@ import { createPortal } from 'react-dom'
import { useDialogStack } from './dialog-stack'
import { useEntitlement } from '../state/entitlement'
import { useProjects } from '../state/projects'
-import { hostShareOptions } from '../lib/relayHostShare'
+import { hostShareOptions, relayShareGrantCopy } from '../lib/relayHostShare'
import { thisMachine } from '../lib/machineName'
import { Button } from '@renderer/ui/Button'
import { CopyButton } from '@renderer/ui/CopyButton'
@@ -105,9 +105,13 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
hostOffer ? (
<div className="remote-dialog__block">
<p className="remote-dialog__hint">
- Sharing <strong>{sharedName || 'this project'}</strong> — the joiner will see this
- project and can run commands on {thisMachine()}. Share this pairing code (single
- use):
+ {sharedName ? (
+ <>
+ Sharing <strong>{sharedName}</strong>.{' '}
+ </>
+ ) : null}
+ {relayShareGrantCopy(sharedName || null, thisMachine())} Share this pairing code
+ (single use):
</p>
<Input
className="w-full"
@@ -137,12 +141,15 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
))}
</Select>
</label>
- ) : (
- <p className="remote-dialog__hint">
- Sharing <strong>{sharedName || 'this project'}</strong> — the joiner sees this
- project and can run commands on {thisMachine()}.
- </p>
- )}
+ ) : null}
+ <p className="remote-dialog__hint">
+ {sharedName && shareOptions.length <= 1 ? (
+ <>
+ Sharing <strong>{sharedName}</strong>.{' '}
+ </>
+ ) : null}
+ {relayShareGrantCopy(sharedName || null, thisMachine())}
+ </p>
<Button disabled={hostBusy} onClick={() => void startHosting()}>
{hostBusy ? 'Starting…' : 'Allow remote access'}
</Button>
diff --git a/src/renderer/components/settings/sections/RemoteSection.tsx b/src/renderer/components/settings/sections/RemoteSection.tsx
index d1ccc8a8e..7fcbff1cc 100644
--- a/src/renderer/components/settings/sections/RemoteSection.tsx
+++ b/src/renderer/components/settings/sections/RemoteSection.tsx
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useEntitlement } from '../../../state/entitlement'
import { useProjects } from '../../../state/projects'
-import { hostShareOptions } from '../../../lib/relayHostShare'
+import { hostShareOptions, relayShareGrantCopy } from '../../../lib/relayHostShare'
import { thisMachine } from '../../../lib/machineName'
import { SettingsSection } from '../SettingsSection'
import { SearchableRow } from '../SearchableRow'
@@ -93,9 +93,13 @@ export function RemoteSection({
hostOffer ? (
<div className="space-y-2">
<p className="text-sm text-muted">
- Sharing <strong className="text-text">{sharedName || 'this project'}</strong> —
- the joiner will see this project and can run commands on {thisMachine()}. Share
- this pairing code with the other device (single use):
+ {sharedName ? (
+ <>
+ Sharing <strong className="text-text">{sharedName}</strong>.{' '}
+ </>
+ ) : null}
+ {relayShareGrantCopy(sharedName || null, thisMachine())} Share this pairing code
+ with the other device (single use):
</p>
<FieldRow
label="Pairing code"
@@ -132,12 +136,15 @@ export function RemoteSection({
</Select>
}
/>
- ) : (
- <p className="text-sm text-muted">
- Sharing <strong className="text-text">{sharedName || 'this project'}</strong> —
- the joiner sees this project and can run commands on {thisMachine()}.
- </p>
- )}
+ ) : null}
+ <p className="text-sm text-muted">
+ {sharedName && shareOptions.length <= 1 ? (
+ <>
+ Sharing <strong className="text-text">{sharedName}</strong>.{' '}
+ </>
+ ) : null}
+ {relayShareGrantCopy(sharedName || null, thisMachine())}
+ </p>
<Button disabled={hostBusy} onClick={() => void startHosting()}>
{hostBusy ? 'Starting…' : 'Allow remote access'}
</Button>
diff --git a/src/renderer/components/settings/sections/TeamAccessSection.tsx b/src/renderer/components/settings/sections/TeamAccessSection.tsx
index ec784c5ca..518466646 100644
--- a/src/renderer/components/settings/sections/TeamAccessSection.tsx
+++ b/src/renderer/components/settings/sections/TeamAccessSection.tsx
@@ -117,8 +117,9 @@ export function TeamAccessSection({
<div className="space-y-3">
<h4 className="text-[13px] font-medium text-text">Invite a teammate</h4>
<p className="text-sm text-muted">
- A teammate on a seat can run commands on {thisMachine()} — the same as giving
- them SSH access. Only invite people you trust.
+ A teammate on a seat gets full access to {thisMachine()} as you — every project,
+ and commands in any folder — the same as giving them SSH access. Only invite people
+ you trust.
</p>
<FieldRow
label="Teammate email"
@@ -191,8 +192,8 @@ export function TeamAccessSection({
end-to-end encrypted relay.
</p>
<p className="text-sm text-muted">
- A seat grants shell access: a teammate on a seat can run commands on{' '}
- {thisMachine()} — the same as giving them SSH access. Every connection is still
+ A seat grants full access: a teammate on a seat can run commands on{' '}
+ {thisMachine()} as you, in every project — the same as giving them SSH access. Every connection is still
verified with a one-time pairing code you compare together.
</p>
<Button variant="primary" onClick={() => void ent.upgrade()}>
diff --git a/src/renderer/lib/relayHostShare.test.ts b/src/renderer/lib/relayHostShare.test.ts
index 3458df4ae..aab3299ad 100644
--- a/src/renderer/lib/relayHostShare.test.ts
+++ b/src/renderer/lib/relayHostShare.test.ts
@@ -40,3 +40,20 @@ describe('hostShareOptions', () => {
expect(opts).toEqual([{ id: 'a', name: 'A' }])
})
})
+
+describe('relayShareGrantCopy', () => {
+ it('names the project and the shell honestly for a scoped invite', async () => {
+ const { relayShareGrantCopy } = await import('./relayHostShare')
+ const s = relayShareGrantCopy('Alpha', 'this Mac')
+ expect(s).toContain('Alpha')
+ expect(s).toContain('other projects')
+ expect(s).toContain('still a shell on this Mac')
+ expect(s).not.toContain('full access')
+ })
+
+ it('says full access for an unscoped invite', async () => {
+ const { relayShareGrantCopy } = await import('./relayHostShare')
+ expect(relayShareGrantCopy(null, 'this PC')).toContain('full access to this PC as you')
+ expect(relayShareGrantCopy('', 'this PC')).toContain('full access')
+ })
+})
diff --git a/src/renderer/lib/relayHostShare.ts b/src/renderer/lib/relayHostShare.ts
index 53e46bf80..eca958296 100644
--- a/src/renderer/lib/relayHostShare.ts
+++ b/src/renderer/lib/relayHostShare.ts
@@ -18,3 +18,24 @@ export function hostShareOptions(projects: Project[], activeProjectId: string):
if (activeIdx <= 0) return open
return [open[activeIdx], ...open.slice(0, activeIdx), ...open.slice(activeIdx + 1)]
}
+
+/**
+ * What a relay invite actually grants, in words — ONE sentence for both host surfaces (Settings →
+ * Remote access and the Remote access dialog), so the two cannot drift apart.
+ *
+ * A SCOPED invite (a project is selected) is enforced host-side by core/relay/scoped-guest-policy.ts:
+ * the joiner reaches that project's terminals, files, git and board, and none of the host's other
+ * projects, settings or saved credentials. It is still consent to run commands: a terminal the joiner
+ * opens is a shell on this machine as the host's user, and the sentence says so rather than implying
+ * an OS sandbox. An UNSCOPED invite (nothing to scope to) is full access, and says that plainly.
+ */
+export function relayShareGrantCopy(sharedName: string | null, machine: string): string {
+ if (!sharedName) {
+ return `No project is selected, so the joiner gets full access to ${machine} as you — every project, and commands in any folder.`
+ }
+ return (
+ `The joiner can open terminals and agents in ${sharedName}, and read and edit its files — ` +
+ `running commands on ${machine} as you. The app keeps them out of your other projects, ` +
+ `your settings and your saved credentials, but a terminal they open is still a shell on ${machine}.`
+ )
+}
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 9c65d8fde..925a34601 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -40,7 +40,26 @@ import { IPC } from './ipc'
* 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_CHANNEL_PREFIXES: readonly string[] = [
+ 'githubControl:',
+ // The host's credential and identity planes. None of these crosses the relay for a legitimate
+ // tab (relay-api.ts keeps license/accounts/usage LOCAL), and each is something the invite never
+ // granted: the license key and its seats, the managed Claude/Codex logins (a login node writes
+ // credentials into the account dir, removal deletes one), and account usage read with the
+ // host's stored tokens.
+ 'license:',
+ 'claude-accounts:',
+ 'codex-accounts:',
+ 'usage:',
+ // The trust plane itself: who is paired, who may connect, and the invites that mint seats. A
+ // peer that could reach these could pin its own key or revoke the host's other devices. Note the
+ // trailing colons: `relay:host:` does not match the hosted-team verbs (`relay:hosted:*`), which
+ // the Server Edition's hosted service intercepts and judges itself.
+ 'pairing:',
+ 'remote:',
+ 'relay:host:',
+ 'relay:client:'
+]
export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
IPC.projectSetupRun,
@@ -54,13 +73,29 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
// cannot quietly open it.
IPC.agentBoardCommentDeliver,
IPC.stationNoticeDropped,
- IPC.stationNoticeList
+ IPC.stationNoticeList,
+ // The host's settings. `settings:save` is the dangerous half: `modelGateway.baseUrl` is the TRUST
+ // ANCHOR `agent:discover-models` uses to decide whether it may resolve the stored
+ // `${secret:model-gateway-api-key}` (core/agent-env-ipc.ts), so a peer that could save settings
+ // and then ask for discovery would have the keychain-held key sent to a URL of its choosing.
+ // `settings:load` goes too: settings.json carries custom agents' launch env (API keys), and a
+ // relay tab keeps its settings LOCAL (relay-api.ts), so no legitimate peer reads the host's.
+ IPC.settingsLoad,
+ IPC.settingsSave,
+ // Model-gateway discovery and the write-only gateway credential. Discovery resolves host-side
+ // secrets against the saved gateway; the credential verbs write/clear the keychain-held key.
+ IPC.agentDiscoverModels,
+ IPC.agentGatewayCredentialStatus,
+ IPC.agentGatewayCredentialSave,
+ IPC.agentGatewayCredentialClear
])
/** 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 {
+ // The method name arrives off the wire; a non-string is never a channel (and must not throw).
+ if (typeof channel !== 'string') return false
if (HOST_ONLY_CHANNELS.has(channel)) return true
return HOST_ONLY_CHANNEL_PREFIXES.some((prefix) => channel.startsWith(prefix))
}