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
feat(relay): role access policy for hosted relay peers
review443c1f834e4e
diff --git a/src/core/relay/access-policy.guard.test.ts b/src/core/relay/access-policy.guard.test.tsnew file mode 100644index 000000000..92f25659b--- /dev/null+++ b/src/core/relay/access-policy.guard.test.ts@@ -0,0 +1,49 @@+// Forces a decision whenever the relay API gains a channel: every IPC.* a relay tab can send must+// be VIEW, COMMENT or reviewed-EDITOR_ONLY. Also pins that the allowlists name real channels.+import { describe, it, expect } from 'vitest'+import fs from 'node:fs'+import path from 'node:path'+import { IPC } from '../../shared/ipc'+import { VIEW, COMMENT, EDITOR_ONLY, VIEW_EVENTS } from './access-policy'++const ROOT = path.resolve(__dirname, '../../..')+const read = (p: string) => fs.readFileSync(path.join(ROOT, p), 'utf8').replace(/\r\n/g, '\n')+const BUILDERS = ['buildRealApi', 'buildFilesApi', 'buildGitHubApi', 'buildAgentApi', 'buildCanvasApi', 'buildPresenceApi', 'buildClaudeApi']++function body(src: string, fn: string): string {+ const start = src.indexOf(`export function ${fn}(`)+ if (start < 0) throw new Error(`builder ${fn} not found — update BUILDERS`)+ const next = src.indexOf('\nexport function ', start + 1)+ return src.slice(start, next < 0 ? undefined : next)+}++describe('access-policy guard', () => {+ const ipcValues = new Set((Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string'))+ it('every allowlisted method is a real IPC channel', () => {+ for (const m of [...Object.keys(VIEW), ...Object.keys(COMMENT), ...EDITOR_ONLY]) expect(ipcValues.has(m), m).toBe(true)+ })+ it('every VIEW / COMMENT method carries a declared argument check', () => {+ for (const [m, check] of [...Object.entries(VIEW), ...Object.entries(COMMENT)]) expect(typeof check, m).toBe('function')+ })+ it('no channel is decided twice', () => {+ const view = new Set(Object.keys(VIEW))+ for (const m of Object.keys(COMMENT)) expect(view.has(m), `${m} is in VIEW and COMMENT`).toBe(false)+ for (const m of EDITOR_ONLY) {+ expect(Object.hasOwn(VIEW, m) || Object.hasOwn(COMMENT, m), `${m} is allowlisted AND editor-only`).toBe(false)+ }+ })+ it('every event a non-editor may receive is a real IPC channel', () => {+ for (const ch of Object.keys(VIEW_EVENTS)) expect(ipcValues.has(ch), ch).toBe(true)+ })+ it('every relay-API channel has been decided', () => {+ const ws = read('src/renderer/bridge/ws-bridge.ts')+ const relay = read('src/renderer/bridge/relay-api.ts')+ const src = BUILDERS.map((b) => body(ws, b)).join('\n') + relay+ const names = new Set([...src.matchAll(/IPC\.([A-Za-z0-9_]+)/g)].map((x) => x[1]))+ const undecided = [...names]+ .map((n) => (IPC as Record<string, unknown>)[n])+ .filter((v): v is string => typeof v === 'string')+ .filter((v) => !Object.hasOwn(VIEW, v) && !Object.hasOwn(COMMENT, v) && !EDITOR_ONLY.has(v))+ expect(undecided, `classify these in access-policy.ts: ${undecided.join(', ')}`).toEqual([])+ })+})diff --git a/src/core/relay/access-policy.test.ts b/src/core/relay/access-policy.test.tsnew file mode 100644index 000000000..9c7312b56--- /dev/null+++ b/src/core/relay/access-policy.test.ts@@ -0,0 +1,430 @@+import { describe, it, expect, afterEach, vi } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import {+ decideAccess,+ filterOutboundEvent,+ narrowResponseForRole,+ wrapSinkForRole,+ type AccessContext+} from './access-policy'+import { IPC } from '../../shared/ipc'+import type { UiSink } from '../ui-sink-registry'++const ctx = (role: AccessContext['role']): AccessContext => ({+ role,+ sharedProjects: new Set(['P']),+ projectOfNode: (id) => (id === 'n1' ? 'P' : id === 'n2' ? 'Q' : undefined),+ projectCwds: () => ['/srv/app'],+ realpath: (p) => (p.startsWith('/srv/app/link') ? '/etc/passwd' : p)+})++describe('access policy', () => {+ it('editors and owners pass everything untouched', () => {+ expect(decideAccess('req', IPC.fsWrite, ['/x', 'y'], ctx('editor'))).toEqual({ allow: true })+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'n2' }], ctx('owner'))).toEqual({ allow: true })+ })+ it('a viewer may not write, destroy, send text or mutate the canvas', () => {+ for (const m of [IPC.fsWrite, IPC.ptyDestroy, IPC.ptySendText, IPC.gitCommit, IPC.settingsLoad]) {+ expect(decideAccess('req', m, [], ctx('viewer')).allow).toBe(false)+ }+ expect(decideAccess('cast', IPC.ptyWrite, ['s', 'ls\r'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('cast', IPC.canvasMut, ['P', {}], ctx('viewer')).allow).toBe(false)+ })+ it('viewer pty:create joins only, never votes size, and only in shared projects', () => {+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'n1', cols: 80, rows: 24 }], ctx('viewer')))+ .toEqual({ allow: true, args: [{ persistKey: 'n1', cols: 80, rows: 24, joinOnly: true, sizeVote: false }] })+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'n2' }], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'unknown' }], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.ptyCreate, [{}], ctx('viewer')).allow).toBe(false)+ })+ it('viewer resize is rewritten to "not looking"', () => {+ expect(decideAccess('cast', IPC.ptyResize, ['s', 40, 10, 'v'], ctx('viewer')))+ .toEqual({ allow: true, args: ['s', null, null, 'v'] })+ })+ it('fs reads are jailed to shared project cwds, symlinks included', () => {+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], ctx('viewer')).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, ['/root/.ssh/id_rsa'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/link'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/../../etc/passwd'], ctx('viewer')).allow).toBe(false)+ })+ 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', {}], ctx('commenter')).allow).toBe(true)+ expect(decideAccess('req', IPC.boardLogAppend, ['Q', {}], ctx('commenter')).allow).toBe(false)+ })+ it('outbound: non-shared canvas and agent events are dropped for non-editors only', () => {+ const mutQ = JSON.stringify({ t: 'ev', channel: IPC.canvasMut, args: ['Q', {}] })+ const statusN2 = JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'n2' }] })+ const statusN1 = JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'n1' }] })+ expect(filterOutboundEvent(mutQ, ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(statusN2, ctx('commenter'))).toBe(false)+ expect(filterOutboundEvent(statusN1, ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(mutQ, ctx('editor'))).toBe(true)+ })+})++describe('access policy: the fs jail', () => {+ const made: string[] = []+ afterEach(() => {+ for (const d of made.splice(0)) fs.rmSync(d, { recursive: true, force: true })+ })++ it('a project reached through a symlinked cwd is readable (the cwd is realpathed too)', () => {+ // /work/app is a symlink to /data/app: the file realpaths under /data/app, the cwd must as well.+ const c: AccessContext = {+ ...ctx('viewer'),+ projectCwds: () => ['/work/app'],+ realpath: (p) => (p.startsWith('/work/app') ? '/data/app' + p.slice('/work/app'.length) : p)+ }+ expect(decideAccess('req', IPC.fsRead, ['/work/app/README.md'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsList, ['/work/app'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, ['/data/app/README.md'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, ['/data/other/x'], c).allow).toBe(false)+ })++ it.skipIf(process.platform === 'win32')(+ 'a real symlinked project dir on disk (symlink creation needs privileges on Windows)',+ () => {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'access-')))+ made.push(root)+ fs.mkdirSync(path.join(root, 'real', 'app'), { recursive: true })+ fs.writeFileSync(path.join(root, 'real', 'app', 'README.md'), 'hi')+ fs.writeFileSync(path.join(root, 'secret.txt'), 'nope')+ fs.symlinkSync(path.join(root, 'real', 'app'), path.join(root, 'link'))+ // An escape planted INSIDE the project: a symlink to a file outside it.+ fs.symlinkSync(path.join(root, 'secret.txt'), path.join(root, 'real', 'app', 'escape'))+ const c: AccessContext = {+ role: 'viewer',+ sharedProjects: new Set(['P']),+ projectOfNode: () => undefined,+ projectCwds: () => [path.join(root, 'link')],+ realpath: (p) => {+ try {+ return fs.realpathSync(p)+ } catch {+ return null+ }+ }+ }+ expect(decideAccess('req', IPC.fsRead, [path.join(root, 'link', 'README.md')], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, [path.join(root, 'real', 'app', 'README.md')], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsList, [path.join(root, 'link')], c).allow).toBe(true)+ expect(decideAccess('req', IPC.fsRead, [path.join(root, 'link', 'escape')], c).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, [path.join(root, 'secret.txt')], c).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, [path.join(root, 'link', 'missing')], c).allow).toBe(false)+ }+ )++ it('refuses relative and ~ paths, sibling-prefix dirs, and non-strings', () => {+ const v = ctx('viewer')+ expect(decideAccess('req', IPC.fsRead, ['README.md'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['~/.ssh/id_rsa'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/srv/app2/secret'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, ['/srv/ap'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, [42], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsRead, [], v).allow).toBe(false)+ expect(decideAccess('req', IPC.fsList, ['/srv/app'], v).allow).toBe(true)+ expect(decideAccess('req', IPC.fsExists, ['/srv/app/x'], v).allow).toBe(true)+ 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', () => {+ const c: AccessContext = { ...ctx('viewer'), projectCwds: () => ['/'] }+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c).allow).toBe(true)+ })++ it('a cwd that is not absolute is never a root', () => {+ const c: AccessContext = { ...ctx('viewer'), projectCwds: () => ['', 'srv'] }+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c).allow).toBe(false)+ })++ it('no shared project cwd means nothing is readable', () => {+ const c: AccessContext = { ...ctx('viewer'), projectCwds: () => [] }+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], c).allow).toBe(false)+ })+})++describe('access policy: argument checks that "read" alone would not make safe', () => {+ it('viewer pty:create keeps ONLY the join fields — no ssh route, shell, account or env', () => {+ const d = decideAccess(+ 'req',+ IPC.ptyCreate,+ [{+ persistKey: 'n1', cols: 80, rows: 24, viewerId: 'modal',+ shell: '/bin/sh', shellArgs: ['-c', 'touch /tmp/x'], cwd: '/', agentId: 'claude', accountId: 'a1',+ ownerProjectId: 'P', clearEnv: true, requireRemote: false, agentModel: 'm',+ sshRemote: { controlPath: '/tmp/cp', remoteCwd: '/', conn: { host: 'h', user: 'u', extraArgs: '-oProxyCommand=touch /tmp/pwn', execTrusted: true } },+ joinOnly: false, sizeVote: true+ }],+ ctx('viewer')+ )+ expect(d).toEqual({+ allow: true,+ args: [{ persistKey: 'n1', cols: 80, rows: 24, viewerId: 'modal', joinOnly: true, sizeVote: false }]+ })+ })++ it('viewer pty:create refuses a non-object or array options argument', () => {+ expect(decideAccess('req', IPC.ptyCreate, [], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.ptyCreate, [null], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.ptyCreate, ['n1'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', IPC.ptyCreate, [['n1']], ctx('viewer')).allow).toBe(false)+ })++ it('viewer pty:create drops a non-numeric size and a non-string viewerId', () => {+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'n1', cols: '80', rows: null, viewerId: 7 }], ctx('viewer')))+ .toEqual({ allow: true, args: [{ persistKey: 'n1', joinOnly: true, sizeVote: false }] })+ })++ it('a viewer may resume its own flow but never pause the shared pty', () => {+ expect(decideAccess('cast', IPC.ptyFlow, ['s', true], ctx('viewer'))).toEqual({ allow: true })+ expect(decideAccess('cast', IPC.ptyFlow, ['s', true, 'modal'], ctx('viewer'))).toEqual({ allow: true })+ expect(decideAccess('cast', IPC.ptyFlow, ['s', false], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('cast', IPC.ptyFlow, ['s', 0], ctx('commenter')).allow).toBe(false)+ expect(decideAccess('cast', IPC.ptyFlow, ['s', false], ctx('editor')).allow).toBe(true)+ expect(decideAccess('cast', IPC.ptyKill, ['s'], ctx('viewer')).allow).toBe(true)+ })++ it('viewer resize without a viewerId stays three arguments', () => {+ expect(decideAccess('cast', IPC.ptyResize, ['s', 40, 10], ctx('viewer')))+ .toEqual({ allow: true, args: ['s', null, null] })+ })++ it('terminal reads are limited to nodes of shared projects', () => {+ for (const m of [IPC.ptyCapture, IPC.ptyReadScrollback, IPC.ptyPaneCommand]) {+ expect(decideAccess('req', m, ['n1'], ctx('viewer')).allow).toBe(true)+ expect(decideAccess('req', m, ['n2'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', m, ['nope'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', m, [], ctx('viewer')).allow).toBe(false)+ }+ expect(decideAccess('req', IPC.ptyTmuxStatus, [], ctx('viewer')).allow).toBe(true)+ })++ it('git reads are jailed by their cwd', () => {+ for (const m of [IPC.gitStatus, IPC.gitRepoRoot, IPC.gitHistory]) {+ expect(decideAccess('req', m, ['/srv/app'], ctx('viewer')).allow).toBe(true)+ expect(decideAccess('req', m, ['/root'], ctx('viewer')).allow).toBe(false)+ }+ })++ it('git:diff jails the FILE too — an untracked diff is `git diff --no-index`, which reads any path', () => {+ const v = ctx('viewer')+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', 'src/a.ts', false, false], v).allow).toBe(true)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', 'new.ts', false, true], v).allow).toBe(true)+ // The measured escape: `git diff --no-index -- /dev/null /root/.ssh/id_rsa` prints the key.+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', '/root/.ssh/id_rsa', false, true], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', '../../root/.ssh/id_rsa', false, true], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', 'link', false, true], v).allow).toBe(false)+ // `untracked` is read truthily by the handler, so a truthy non-boolean is the untracked branch.+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', '/root/.ssh/id_rsa', false, 1], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', '../outside', false, false], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', ':(top)x', false, false], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/srv/app', 42, false, false], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitDiff, ['/root', 'x', false, false], v).allow).toBe(false)+ })++ it('git:show-file refuses a ref that git would parse as an option (`--output=` WRITES a file)', () => {+ const v = ctx('viewer')+ expect(decideAccess('req', IPC.gitShowFile, ['/srv/app', 'HEAD', 'src/a.ts'], v).allow).toBe(true)+ expect(decideAccess('req', IPC.gitShowFile, ['/srv/app', '', 'src/a.ts'], v).allow).toBe(true)+ expect(decideAccess('req', IPC.gitShowFile, ['/srv/app', '--output=/tmp/pwned', 'a'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitShowFile, ['/srv/app', '-p', 'a'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitShowFile, ['/srv/app', { toString: () => '--output=x' }, 'a'], v).allow).toBe(false)+ expect(decideAccess('req', IPC.gitShowFile, ['/root', 'HEAD', 'a'], v).allow).toBe(false)+ })++ it('board-log reads and subscriptions name a shared project', () => {+ for (const m of [IPC.boardLogRead, IPC.boardLogSubscribe, IPC.boardLogUnsubscribe]) {+ expect(decideAccess('req', m, ['P'], ctx('viewer')).allow).toBe(true)+ expect(decideAccess('req', m, ['Q'], ctx('viewer')).allow).toBe(false)+ expect(decideAccess('req', m, [], ctx('viewer')).allow).toBe(false)+ }+ })++ it('a commenter has every viewer right; an unknown role is treated as the lowest', () => {+ expect(decideAccess('req', IPC.fsRead, ['/srv/app/README.md'], ctx('commenter')).allow).toBe(true)+ expect(decideAccess('req', IPC.fsWrite, ['/srv/app/README.md', 'x'], ctx('commenter')).allow).toBe(false)+ const odd = ctx('admin' as AccessContext['role'])+ expect(decideAccess('cast', IPC.presenceChat, ['hi'], odd).allow).toBe(false)+ expect(decideAccess('req', IPC.fsWrite, ['/srv/app/x', 'y'], odd)).toEqual({+ allow: false,+ message: "Viewers can't do that here. Ask an owner for Editor access."+ })+ expect(decideAccess('req', IPC.fsWrite, ['/srv/app/x', 'y'], ctx('toString' as AccessContext['role']))).toEqual({+ allow: false,+ message: "Viewers can't do that here. Ask an owner for Editor access."+ })+ expect(filterOutboundEvent(JSON.stringify({ t: 'ev', channel: IPC.logBatch, args: [[]] }), odd)).toBe(false)+ })++ it('a method named like an Object.prototype member is not a table entry', () => {+ for (const m of ['constructor', 'toString', '__proto__', 'hasOwnProperty', 'valueOf']) {+ const d = decideAccess('req', m, [], ctx('commenter'))+ expect(d.allow, m).toBe(false)+ expect(typeof (d as { message?: unknown }).message, m).toBe('string')+ }+ expect(decideAccess('req', 42 as unknown as string, [], ctx('viewer')).allow).toBe(false)+ })++ it('a refusal names the role and never echoes the method', () => {+ expect(decideAccess('req', IPC.gitCommit, ['/srv/app', 'm'], ctx('commenter'))).toEqual({+ allow: false,+ message: "Commenters can't do that here. Ask an owner for Editor access."+ })+ })+})++describe('outbound filter: deny by default for non-editors', () => {+ const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })++ it('host-private broadcasts never reach a viewer, and do reach an editor', () => {+ for (const ch of [IPC.logBatch, IPC.usageUpdate, IPC.licenseChanged, IPC.gitCloneProgress, IPC.workspaceCorruptRecovered]) {+ expect(filterOutboundEvent(ev(ch, { x: 1 }), ctx('viewer')), ch).toBe(false)+ expect(filterOutboundEvent(ev(ch, { x: 1 }), ctx('editor')), ch).toBe(true)+ }+ })++ it('a whole project pushed by the core is delivered only when it is shared', () => {+ for (const ch of [IPC.workspaceExternalChange, IPC.workspaceServerChange]) {+ expect(filterOutboundEvent(ev(ch, { id: 'P', nodes: [] }), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(ch, { id: 'Q', nodes: [] }), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(ch, null), ctx('viewer'))).toBe(false)+ }+ expect(filterOutboundEvent(ev(IPC.projectTrustChanged, { projectId: 'P' }), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(IPC.projectTrustChanged, { projectId: 'Q' }), ctx('viewer'))).toBe(false)+ })++ it('per-project channels are filtered by the project in their name', () => {+ expect(filterOutboundEvent(ev(IPC.boardLogChanged('P'), 'P'), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(IPC.boardLogChanged('Q'), 'Q'), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(IPC.projectSetupEvent('P'), {}), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(IPC.projectSetupEvent('Q'), {}), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(ev(IPC.githubIssuesChanged('P'), [1]), ctx('viewer'))).toBe(false)+ })++ it('per-session terminal events and presence 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)+ })++ it('an unread clear names a node', () => {+ expect(filterOutboundEvent(ev(IPC.agentUnreadClear, 'n1'), ctx('viewer'))).toBe(true)+ expect(filterOutboundEvent(ev(IPC.agentUnreadClear, 'n2'), ctx('viewer'))).toBe(false)+ })++ it('an unattributable message is dropped for a non-editor, never guessed', () => {+ expect(filterOutboundEvent('not json', ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(JSON.stringify({ t: 'ev', args: [] }), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent(JSON.stringify({ t: 'ev', channel: IPC.agentStatus }), ctx('viewer'))).toBe(false)+ expect(filterOutboundEvent('not json', ctx('owner'))).toBe(true)+ })++ it('subagent live output has no node id: it is delivered only for a subagent a shared node started', () => {+ const owners = new Map<string, string>()+ const v = ctx('viewer')+ const chunk = (toolUseId: string) => ev(IPC.agentSubagentActivity, { toolUseId, chunk: 'secret' })+ // Nothing learned yet: dropped.+ expect(filterOutboundEvent(chunk('t1'), v, owners)).toBe(false)+ expect(filterOutboundEvent(chunk('t1'), v)).toBe(false)+ // A start on a SHARED node teaches t1 → n1; one on a non-shared node teaches t2 → n2.+ expect(filterOutboundEvent(ev(IPC.agentStatus, { nodeId: 'n1', kind: 'subagent-start', toolUseId: 't1' }), v, owners)).toBe(true)+ expect(filterOutboundEvent(ev(IPC.agentStatus, { nodeId: 'n2', kind: 'subagent-start', toolUseId: 't2' }), v, owners)).toBe(false)+ expect(filterOutboundEvent(chunk('t1'), v, owners)).toBe(true)+ expect(filterOutboundEvent(chunk('t2'), v, owners)).toBe(false)+ // The owner is re-checked at delivery: unsharing the project stops the stream.+ expect(filterOutboundEvent(chunk('t1'), { ...v, sharedProjects: new Set() }, owners)).toBe(false)+ })++ it('the subagent owner map is bounded', () => {+ const owners = new Map<string, string>()+ const v = ctx('viewer')+ for (let i = 0; i < 2000; i++) {+ filterOutboundEvent(ev(IPC.agentStatus, { nodeId: 'n1', kind: 'subagent-start', toolUseId: `t${i}` }), v, owners)+ }+ expect(owners.size).toBeLessThanOrEqual(512)+ expect(owners.has('t1999')).toBe(true)+ expect(owners.has('t0')).toBe(false)+ })+})++describe('wrapSinkForRole', () => {+ const sinkWith = (buffered: () => number) => {+ const text: string[] = []+ const bin: Uint8Array[] = []+ const sink: UiSink = { sendText: (j) => text.push(j), sendBinary: (b) => bin.push(b), bufferedAmount: buffered }+ return { sink, text, bin }+ }++ it('keeps reporting the UNDERLYING socket backlog, never a constant', () => {+ let n = 5+ const { sink } = sinkWith(() => n)+ const w = wrapSinkForRole(sink, () => ctx('viewer'))+ expect(w.bufferedAmount?.()).toBe(5)+ n = 9_000_000+ expect(w.bufferedAmount?.()).toBe(9_000_000)+ })++ it('filters text per the CURRENT context and passes terminal bytes through', () => {+ let role: AccessContext['role'] = 'viewer'+ const { sink, text, bin } = sinkWith(() => 0)+ const w = wrapSinkForRole(sink, () => ctx(role))+ const mutQ = JSON.stringify({ t: 'ev', channel: IPC.canvasMut, args: ['Q', {}] })+ w.sendText(mutQ)+ expect(text).toEqual([])+ role = 'editor'+ w.sendText(mutQ)+ expect(text).toEqual([mutQ])+ w.sendBinary(new Uint8Array([1, 2]))+ expect(bin).toHaveLength(1)+ })++ it('carries the subagent owner map across messages', () => {+ const { sink, text } = sinkWith(() => 0)+ const w = wrapSinkForRole(sink, () => ctx('viewer'))+ const start = JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'n1', kind: 'subagent-start', toolUseId: 't1' }] })+ const chunk = JSON.stringify({ t: 'ev', channel: IPC.agentSubagentActivity, args: [{ toolUseId: 't1', chunk: 'x' }] })+ w.sendText(start)+ w.sendText(chunk)+ expect(text).toEqual([start, chunk])+ })++ it('a context that cannot be built drops the message instead of throwing into the registry', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const { sink, text } = sinkWith(() => 0)+ 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(text).toEqual([])+ expect(warn).toHaveBeenCalledTimes(1)+ } finally {+ warn.mockRestore()+ }+ })+})++describe('narrowResponseForRole', () => {+ const snapshot = [+ { kind: 'subagent-start', nodeId: 'n1', toolUseId: 't1', taskLabel: 'shared task' },+ { kind: 'subagent-start', nodeId: 'n2', toolUseId: 't2', taskLabel: 'private task' }+ ]+ it('trims the subagent snapshot to shared nodes for a non-editor', () => {+ expect(narrowResponseForRole(IPC.agentSubagentSnapshot, snapshot, ctx('viewer'))).toEqual([snapshot[0]])+ expect(narrowResponseForRole(IPC.agentSubagentSnapshot, 'garbage', ctx('viewer'))).toEqual([])+ })+ it('leaves an editor, and every other method, untouched', () => {+ expect(narrowResponseForRole(IPC.agentSubagentSnapshot, snapshot, ctx('editor'))).toBe(snapshot)+ const r = { anything: 1 }+ expect(narrowResponseForRole(IPC.fsRead, r, ctx('viewer'))).toBe(r)+ })+})diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsnew file mode 100644index 000000000..d14475cdc--- /dev/null+++ b/src/core/relay/access-policy.ts@@ -0,0 +1,453 @@+// Hosted-relay roles are a SECURITY BOUNDARY, enforced here, at the one choke point every relay+// peer message crosses (relay-host.ts hooks). The UI only mirrors it.+//+// Two rules the whole file rests on:+// - DENY BY DEFAULT for non-editors, in BOTH directions. Inbound, a method is reachable by a+// Viewer/Commenter only if it is in VIEW/COMMENT below. Outbound, an event reaches them only if+// it is in VIEW_EVENTS / VIEW_EVENT_PREFIXES: the core BROADCASTS to every attached client (the+// debug log stream, whole project documents, account usage…), so an allow-by-default filter+// would hand a viewer everything nobody remembered to list. A channel added tomorrow is+// Editor-only, in and out, until someone decides otherwise.+// - "READ" IS NOT "SAFE": relay peers were fully trusted, so fs:read is not jailed, pty:create on+// any persistKey joins OR SPAWNS (and its options can name an ssh route), and two git "reads"+// are not reads at all — `git diff --no-index` diffs any file on the host, and a `git show` ref+// that starts with `-` is parsed as an option (`--output=<file>` WRITES a file). Every VIEW entry+// therefore carries its own argument check.+//+// Editors and owners pass untouched: Editor is shell access by definition, so gating them would be+// theatre.+import path from 'node:path'+import { IPC } from '../../shared/ipc'+import type { TeamRole } from './team-store'+import type { AccessDecision } from './relay-host'+import type { UiSink } from '../ui-sink-registry'++export interface AccessContext {+ role: TeamRole+ sharedProjects: ReadonlySet<string>+ /** The project a node belongs to, from the persisted canvases. */+ projectOfNode(nodeId: string): string | undefined+ /** The LOCAL cwds of the shared projects. */+ projectCwds(): string[]+ /** `fs.realpath`; null = the path does not resolve. */+ realpath(p: string): string | null+}++type Check = (args: unknown[], ctx: AccessContext) => AccessDecision+const OK: AccessDecision = { allow: true }+const no = (message: string): AccessDecision => ({ allow: false, message })+const pass: Check = () => OK++const isEditor = (role: unknown): boolean => role === 'owner' || role === 'editor'++const sharedProject = (id: unknown, ctx: AccessContext): boolean =>+ typeof id === 'string' && ctx.sharedProjects.has(id)++const sharedNode = (id: unknown, ctx: AccessContext): boolean => {+ if (typeof id !== 'string') return false+ const project = ctx.projectOfNode(id)+ return project !== undefined && ctx.sharedProjects.has(project)+}++/** One property of an object payload (our own fixed key names only), else undefined. */+const field = (v: unknown, key: string): unknown =>+ v !== null && typeof v === 'object' ? (v as Record<string, unknown>)[key] : undefined++/**+ * The shared project roots as REAL paths. A project opened through a symlinked folder has a cwd that+ * never equals its files' realpaths, so the cwd is realpathed too (and kept as written when it does+ * not resolve). A relative or empty cwd is never a root: `'' + sep` is a prefix of every path.+ */+function sharedRoots(ctx: AccessContext): string[] {+ const roots: string[] = []+ for (const cwd of ctx.projectCwds()) {+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) continue+ roots.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. */+function within(root: string, p: string): boolean {+ const rel = path.relative(root, p)+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))+}++/** The REAL path of `p` when it is an absolute path inside a shared project root, else null. The+ * file is realpathed, so a symlink planted inside the project that points out of it is outside. */+function realInSharedCwd(p: unknown, ctx: AccessContext): string | null {+ if (typeof p !== 'string' || !path.isAbsolute(p)) return null+ const resolved = ctx.realpath(path.resolve(p))+ if (!resolved) return null+ return sharedRoots(ctx).some((root) => within(root, resolved)) ? resolved : null+}++const READ_JAIL = 'Viewers can only read files inside a shared project.'++const nodeArg0: Check = (a, ctx) => (sharedNode(a[0], ctx) ? OK : no('That terminal is not in a shared project.'))+const pathArg0: Check = (a, ctx) => (realInSharedCwd(a[0], ctx) ? OK : no(READ_JAIL))+const projectArg0: Check = (a, ctx) => (sharedProject(a[0], ctx) ? OK : no('That project is not shared.'))++/** The ONLY create fields a watch-only join keeps. Everything else on `PtyCreateOptions` either+ * shapes a spawn (shell, cwd, account, env) or routes one: `sshRemote.conn` carries `extraArgs`+ * and `execTrusted`, and the join's existence probe runs `ssh` with them BEFORE `joinOnly` refuses+ * anything — an `-oProxyCommand=` there is a command run on this host. */+function viewerCreateOptions(o: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = { persistKey: o.persistKey }+ if (typeof o.cols === 'number') out.cols = o.cols+ if (typeof o.rows === 'number') out.rows = o.rows+ if (typeof o.viewerId === 'string') out.viewerId = o.viewerId+ return { ...out, joinOnly: true, sizeVote: false }+}++/** `git diff` (handler args: cwd, file, staged, untracked). The FILE is jailed as well as the cwd. */+const gitDiff: Check = (a, ctx) => {+ const cwd = realInSharedCwd(a[0], ctx)+ if (!cwd) return no(READ_JAIL)+ const file = a[1]+ // Pathspec magic (`:(top)…`) re-roots the path at the repository, which can sit above the project.+ if (typeof file !== 'string' || file.startsWith(':')) return no(READ_JAIL)+ const target = path.resolve(cwd, file)+ // The handler reads `untracked` truthily, and then runs `git diff --no-index -- /dev/null <file>`,+ // which compares FILES, not a repository: any path on the host. Only a real path inside passes.+ if (a[3]) return realInSharedCwd(target, ctx) ? OK : no(READ_JAIL)+ // A tracked diff: git refuses a pathspec outside the repository and does not follow a symlink in+ // one, so a lexical check is enough — and a deleted file, which has no realpath, stays viewable.+ return sharedRoots(ctx).some((root) => within(root, target)) ? OK : no(READ_JAIL)+}++/** `git show <ref>:<file>` (handler args: cwd, ref, file). A ref starting with `-` becomes an+ * OPTION of `git show`; measured: `--output=<path>` writes the command's output to that path. */+const gitShowFile: Check = (a, ctx) => {+ if (!realInSharedCwd(a[0], ctx)) return no(READ_JAIL)+ const ref = a[1]+ if (ref !== undefined && ref !== null && (typeof ref !== 'string' || ref.startsWith('-'))) {+ return no('That is not a revision name.')+ }+ return typeof a[2] === 'string' ? OK : no(READ_JAIL)+}++export const VIEW: Readonly<Record<string, Check>> = Object.freeze({+ // Narrowed to the shared projects by the host's narrowResponse hook.+ [IPC.workspaceLoad]: pass,+ [IPC.ptyCreate]: (a, ctx) => {+ const o = a[0]+ if (!o || typeof o !== 'object' || Array.isArray(o) || !sharedNode((o as Record<string, unknown>).persistKey, ctx)) {+ return no('Viewers can only watch terminals in a shared project that are already running.')+ }+ return { allow: true, args: [viewerCreateOptions(o as Record<string, unknown>)] }+ },+ // Rewritten to "not looking": a viewer's window never sizes the shared terminal.+ [IPC.ptyResize]: (a) => ({ allow: true, args: [a[0], null, null, ...(a.length > 3 ? [a[3]] : [])] }),+ // Handler args: sessionId, resume, viewerId. A PAUSE is not the sender's own business: it pauses+ // the shared pty process (`PtyManager.setFlow` → `proc.pause()`) for every subscriber until the+ // pausing view resumes or leaves, so a viewer that never resumes freezes the editor's terminal.+ // A viewer may only resume (a no-op for a view that owes no pause); its socket backlog is still+ // bounded by the per-client drop-and-redraw ceiling, which pauses nobody.+ [IPC.ptyFlow]: (a) => (a[1] === true ? OK : no('Viewers never pause a shared terminal.')),+ // Detaches the sender's OWN view only (the core checks `subscribes`); the session keeps running.+ [IPC.ptyKill]: pass,+ [IPC.ptyCapture]: nodeArg0,+ [IPC.ptyReadScrollback]: nodeArg0,+ [IPC.ptyPaneCommand]: nodeArg0,+ [IPC.ptyTmuxStatus]: pass,+ [IPC.fsList]: pathArg0,+ [IPC.fsRead]: pathArg0,+ [IPC.fsReadBinary]: pathArg0,+ [IPC.fsExists]: pathArg0,+ [IPC.gitStatus]: pathArg0,+ [IPC.gitRepoRoot]: pathArg0,+ [IPC.gitDiff]: gitDiff,+ [IPC.gitShowFile]: gitShowFile,+ // Its only other argument's ref (`baseRef`) is refused by the core when it starts with `-`.+ [IPC.gitHistory]: pathArg0,+ // The RESPONSE is trimmed by narrowResponseForRole (it is a response, not an event).+ [IPC.agentSubagentSnapshot]: pass,+ [IPC.presenceHello]: pass,+ [IPC.presenceCursor]: pass,+ [IPC.presenceFocus]: pass,+ [IPC.presenceProject]: pass,+ [IPC.boardLogRead]: projectArg0,+ [IPC.boardLogSubscribe]: projectArg0,+ [IPC.boardLogUnsubscribe]: projectArg0+})++export const COMMENT: Readonly<Record<string, Check>> = Object.freeze({+ [IPC.presenceChat]: pass,+ [IPC.boardLogAppend]: projectArg0+})++/**+ * 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+ * here changes nothing at runtime — non-editors are denied anything not allowlisted — it records+ * that someone DECIDED. This is about what a peer may SEND; what it may RECEIVE is VIEW_EVENTS, so+ * server→client event channels are listed here too (a client cannot invoke them).+ */+export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([+ // Terminals: typing, ending, restarting and signalling a session; host-side probes.+ IPC.ptyWrite,+ IPC.ptyDestroy,+ IPC.ptyRecycle,+ IPC.ptySessionAge,+ IPC.ptySendText,+ IPC.ptyPaneOwner,+ IPC.ptyTerminateForeground,+ IPC.ptyReadSessionName,+ // Workspace, project settings and setup: writes, probes of arbitrary folders, trust, scripts.+ IPC.workspaceSave,+ IPC.workspaceProbeFolder,+ IPC.workspaceProjectFileState,+ IPC.projectSettingsRead,+ IPC.projectSettingsWriteShared,+ IPC.projectSettingsUpdateLocal,+ IPC.projectSettingsLaunchInfo,+ IPC.projectSetupRun,+ IPC.projectSetupCancel,+ IPC.projectSetupConsentSubmit,+ IPC.projectSetupRequestTrust,+ IPC.projectSetupSubscribe,+ IPC.projectSetupUnsubscribe,+ IPC.worktreeMaterializeShared,+ // Host settings, credentials and paths.+ IPC.settingsLoad,+ IPC.settingsSave,+ IPC.agentDiscoverModels,+ IPC.agentGatewayCredentialStatus,+ IPC.agentGatewayCredentialSave,+ IPC.agentGatewayCredentialClear,+ IPC.appUserDataDir,+ IPC.claudeCliCaps,+ // Files: writes, uploads, and unjailed listings / downloads.+ IPC.fsWrite,+ IPC.fsMkdir,+ IPC.filesQuickOpen,+ IPC.filesDownloadTicket,+ IPC.filesSaveUpload,+ IPC.filesSaveCanvasImage,+ // Git: every mutation, plus network, worktree and commit-message (runs an agent CLI) operations.+ IPC.gitInit,+ IPC.gitClone,+ IPC.gitCloneAbort,+ IPC.gitCloneDefaultParent,+ IPC.gitCommit,+ IPC.gitPush,+ IPC.gitPull,+ IPC.gitSync,+ IPC.gitPublish,+ IPC.gitStage,+ IPC.gitUnstage,+ IPC.gitStageAll,+ IPC.gitUnstageAll,+ IPC.gitDiscard,+ IPC.gitSwitchBranch,+ IPC.gitCreateBranch,+ IPC.commitGenerate,+ IPC.gitCommitFiles,+ IPC.gitRemoteCommitUrl,+ IPC.gitMerge,+ IPC.gitRebase,+ IPC.gitDeleteBranch,+ IPC.gitRenameBranch,+ IPC.gitFetch,+ IPC.gitForcePush,+ IPC.gitStashPush,+ IPC.gitStashPop,+ IPC.gitRevert,+ IPC.gitBranchAt,+ IPC.gitCheckoutCommit,+ IPC.gitWorktreeList,+ IPC.gitWorktreeAdd,+ IPC.gitWorktreeMerge,+ IPC.gitWorktreeRemove,+ IPC.gitSetActiveRemote,+ // Agent context, the host debug log, GitHub (host token) and agent control.+ IPC.contextEnsure,+ IPC.logSnapshot,+ IPC.logClear,+ IPC.logSubscribe,+ IPC.logUnsubscribe,+ IPC.githubIssuesSubscribe,+ IPC.githubIssuesUnsubscribe,+ IPC.githubIssuesQuery,+ IPC.githubIssuesRefresh,+ IPC.githubIssuesMove,+ IPC.githubIssuesCreateLabels,+ IPC.githubIssuesClearCache,+ IPC.githubProjectAvatar,+ IPC.githubControlStatus,+ IPC.githubControlApprove,+ IPC.githubControlRevoke,+ IPC.githubControlSelectProvider,+ IPC.githubControlSaveToken,+ IPC.githubControlClearToken,+ IPC.agentHibernated,+ IPC.agentAnswerPermission,+ IPC.agentAckDone,+ // Canvas edits and the one presence cast VIEW does not list.+ IPC.canvasMut,+ IPC.presenceDino,+ // Server→client events (see the doc comment): what a non-editor receives is VIEW_EVENTS.+ IPC.workspaceMigrated,+ IPC.workspaceCorruptRecovered,+ IPC.workspaceExternalChange,+ IPC.workspaceServerChange,+ IPC.projectTrustChanged,+ IPC.projectSetupConsentRequest,+ IPC.projectSetupConsentDismiss,+ IPC.gitCloneProgress,+ IPC.contextUpdate,+ IPC.logBatch,+ IPC.agentStatus,+ IPC.agentUnreadClear,+ IPC.agentSubagentActivity,+ IPC.presenceSync,+ IPC.presencePeer+])++const ROLE_NAME: Readonly<Record<string, string>> = { owner: 'Owners', editor: 'Editors', commenter: 'Commenters', viewer: 'Viewers' }++export function decideAccess(_kind: 'req' | 'cast', method: string, args: unknown[], ctx: AccessContext): AccessDecision {+ if (isEditor(ctx.role)) return OK+ // Own keys only: a method named `constructor` must not find Object.prototype's.+ const check =+ typeof method !== 'string'+ ? undefined+ : Object.hasOwn(VIEW, method)+ ? VIEW[method]+ : ctx.role === 'commenter' && Object.hasOwn(COMMENT, method)+ ? COMMENT[method]+ : undefined+ if (!check) {+ // An unrecognised role is the lowest one, never a new name in the sentence.+ const name = Object.hasOwn(ROLE_NAME, ctx.role) ? ROLE_NAME[ctx.role] : ROLE_NAME.viewer+ return no(`${name} can't do that here. Ask an owner for Editor access.`)+ }+ return check(Array.isArray(args) ? args : [], ctx)+}++/**+ * Which node started each subagent (toolUseId → nodeId), learned from the `subagent-start` events+ * this sink saw. `agent:subagent-activity` carries only `{ toolUseId, chunk }` — no node id — so this+ * is the one way to tell a shared node's subagent transcript from anyone else's. Per sink, bounded.+ */+export type SubagentOwners = Map<string, string>+const SUBAGENT_OWNERS_MAX = 512++function learnSubagentOwner(payload: unknown, owners: SubagentOwners): void {+ if (field(payload, 'kind') !== 'subagent-start') return+ const toolUseId = field(payload, 'toolUseId')+ const nodeId = field(payload, 'nodeId')+ if (typeof toolUseId !== 'string' || typeof nodeId !== 'string') return+ // No delete on subagent-end: the tail flushes its last chunk AFTER the end event.+ const prev = owners.get(toolUseId)+ owners.delete(toolUseId)+ // Two nodes claiming one id: attributable to neither (fails closed; '' is never a shared node).+ owners.set(toolUseId, prev === undefined || prev === nodeId ? nodeId : '')+ while (owners.size > SUBAGENT_OWNERS_MAX) owners.delete(owners.keys().next().value as string)+}++type EventCheck = (args: unknown[], ctx: AccessContext, owners: SubagentOwners | undefined) => boolean+const always: EventCheck = () => true++/** Exact event channels a Viewer/Commenter may RECEIVE. Anything else is dropped for them. */+export const VIEW_EVENTS: Readonly<Record<string, EventCheck>> = Object.freeze({+ [IPC.canvasMut]: (a, ctx) => sharedProject(a[0], ctx),+ [IPC.agentStatus]: (a, ctx) => sharedNode(field(a[0], 'nodeId'), ctx),+ [IPC.agentSubagentActivity]: (a, ctx, owners) => {+ const toolUseId = field(a[0], 'toolUseId')+ return typeof toolUseId === 'string' && sharedNode(owners?.get(toolUseId), ctx)+ },+ [IPC.agentUnreadClear]: (a, ctx) => sharedNode(a[0], ctx),+ // Both carry a whole Project document.+ [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+})++/** Per-name event channels. The pty ones are sent only to a session's SUBSCRIBERS, and a viewer+ * subscribes only through the jailed pty:create above. */+const VIEW_EVENT_PREFIXES: ReadonlyArray<readonly [string, (suffix: string, ctx: AccessContext) => boolean]> = [+ [IPC.ptyExit(''), () => true],+ [IPC.ptySize(''), () => true],+ [IPC.ptyClosed(''), () => true],+ [IPC.ptyRecycled(''), () => true],+ [IPC.ptyResync(''), () => true],+ [IPC.boardLogChanged(''), (projectId, ctx) => sharedProject(projectId, ctx)],+ [IPC.projectSetupEvent(''), (projectId, ctx) => sharedProject(projectId, ctx)]+]++/**+ * true = deliver this sink message to the peer. Editors and owners get everything. For anyone else a+ * message is delivered only if it is an event on an allowlisted channel whose check passes; a+ * message that cannot be attributed (not JSON, not an event, no channel) is dropped, never guessed.+ * `subagentOwners` is the sink's memory of who started which subagent (see wrapSinkForRole);+ * without it, subagent output is never delivered to a non-editor.+ */+export function filterOutboundEvent(json: string, ctx: AccessContext, subagentOwners?: SubagentOwners): boolean {+ if (isEditor(ctx.role)) return true+ let m: unknown+ try {+ m = JSON.parse(json)+ } catch {+ return false+ }+ if (field(m, 't') !== 'ev') return false+ const channel = field(m, 'channel')+ if (typeof channel !== 'string') return false+ const rawArgs = field(m, 'args')+ const args = Array.isArray(rawArgs) ? rawArgs : []+ // Learn BEFORE deciding: a start on a node that is not shared today still names its owner.+ if (channel === IPC.agentStatus && subagentOwners) learnSubagentOwner(args[0], subagentOwners)+ if (Object.hasOwn(VIEW_EVENTS, channel)) return VIEW_EVENTS[channel](args, ctx, subagentOwners)+ for (const [prefix, check] of VIEW_EVENT_PREFIXES) {+ if (channel.startsWith(prefix)) return check(channel.slice(prefix.length), ctx)+ }+ return false+}++/**+ * A response the peer asked for that no argument check can narrow. Only the subagent snapshot today:+ * it holds every running subagent's task text, keyed by node. Editors and every other method pass+ * through unchanged. Wire it into the host's `narrowResponse` hook.+ */+export function narrowResponseForRole(method: string, result: unknown, ctx: AccessContext): unknown {+ if (isEditor(ctx.role) || method !== IPC.agentSubagentSnapshot) return result+ return Array.isArray(result) ? result.filter((e) => sharedNode(field(e, 'nodeId'), 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. Terminal bytes (`sendBinary`) pass: they go only to a session's+ * subscribers. `bufferedAmount` stays the underlying socket's — Stage 2 backpressure and the 8 MB+ * drop ceiling key on it (see relay-host.ts `open`).+ */+export function wrapSinkForRole(sink: UiSink, ctxFor: () => AccessContext): UiSink {+ const owners: SubagentOwners = new Map()+ let warned = false+ return {+ sendText: (json) => {+ let deliver: boolean+ try {+ deliver = filterOutboundEvent(json, ctxFor(), owners)+ } catch (err) {+ // 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 throws (below) must+ // still propagate, so only the decision is guarded.+ if (!warned) {+ warned = true+ console.warn(`[access-policy] could not build the access context; dropping events: ${err instanceof Error ? err.message : String(err)}`)+ }+ return+ }+ if (deliver) sink.sendText(json)+ },+ sendBinary: (buf) => sink.sendBinary(buf),+ bufferedAmount: () => sink.bufferedAmount?.() ?? 0+ }+}