Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(main): the session-scoped project-grant ledger + targeting gate (P2/P3)

enes6e01845b1d15
diff --git a/src/main/project-grants.test.ts b/src/main/project-grants.test.ts
new file mode 100644
index 000000000..02ac93d56
--- /dev/null
+++ b/src/main/project-grants.test.ts
@@ -0,0 +1,206 @@
+/**
+ * The session-scoped project-grant ledger + targeting gate (issue #338 PR 1, spec P2/P3 + §3/§5).
+ *
+ * The properties pinned here are the security spine of project targeting:
+ * - a grant is PER-CALLER (P2): caller B presenting an id granted to caller A is refused;
+ * - a grant is SESSION-SCOPED (P3): cleared per-caller on teardown, never persisted — the module
+ * is pure in-memory state with no fs and no electron import (asserted structurally below);
+ * - the gate FAILS CLOSED: unverified, unknown target, SSH target, ungranted target all refuse
+ * with a named error;
+ * - cwd validation resolves ONCE and stats ONCE (P7, CodeQL single-fd posture).
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import {
+ GRANT_CAP,
+ grant,
+ isGranted,
+ atCap,
+ clearCaller,
+ clearAll,
+ gateProjectTarget,
+ validateOpenProjectCwd,
+ PROJECT_TARGETABLE_VERBS,
+ PROJECT_TARGETING_REFUSAL,
+ PROJECT_TARGET_REFUSED,
+ PROJECT_TARGET_SSH_UNSUPPORTED,
+ OPEN_PROJECT_CWD_INVALID
+} from './project-grants'
+
+beforeEach(() => clearAll())
+
+describe('the grant ledger is per-caller (P2)', () => {
+ it('a grant authorizes the granted caller and nobody else', () => {
+ expect(grant('caller-a', 'proj-1')).toBe('ok')
+ expect(isGranted('caller-a', 'proj-1')).toBe(true)
+ // THE pin: caller B using an id granted to caller A is refused. A globally-keyed ledger
+ // passes every single-caller test and fails exactly this one.
+ expect(isGranted('caller-b', 'proj-1')).toBe(false)
+ expect(isGranted('caller-a', 'proj-2')).toBe(false)
+ })
+
+ it('granting the same id twice is idempotent and costs one cap slot', () => {
+ expect(grant('caller-a', 'proj-1')).toBe('ok')
+ expect(grant('caller-a', 'proj-1')).toBe('ok')
+ for (let i = 1; i < GRANT_CAP; i++) expect(grant('caller-a', `proj-extra-${i}`)).toBe('ok')
+ // proj-1 counted once, so exactly GRANT_CAP distinct ids fit.
+ expect(atCap('caller-a')).toBe(true)
+ })
+})
+
+describe('the grant ledger is session-scoped (P3)', () => {
+ it('clearCaller revokes that caller and only that caller', () => {
+ grant('caller-a', 'proj-1')
+ grant('caller-b', 'proj-2')
+ clearCaller('caller-a')
+ expect(isGranted('caller-a', 'proj-1')).toBe(false)
+ expect(isGranted('caller-b', 'proj-2')).toBe(true)
+ })
+
+ it('clearAll empties the ledger (the app-restart lifetime, exercised by beforeEach)', () => {
+ grant('caller-a', 'proj-1')
+ clearAll()
+ expect(isGranted('caller-a', 'proj-1')).toBe(false)
+ })
+
+ it('the module is pure: no fs, no electron, no persistence path to write through', () => {
+ // Structural, in the no-electron.test.ts style: the P3 claim "never persisted" is a property
+ // of the SOURCE — an in-memory Map with no import that could reach a disk or the shell.
+ const src = fs.readFileSync(path.join(__dirname, 'project-grants.ts'), 'utf8')
+ expect(src).not.toMatch(/from ['"]electron(\/[^'"]*)?['"]|require\(['"]electron/)
+ expect(src).not.toMatch(/from ['"](node:)?fs['"]|require\(['"](node:)?fs['"]\)/)
+ expect(src).not.toMatch(/from ['"](node:)?child_process['"]/)
+ })
+})
+
+describe('the per-caller cap (open-project-grant-cap)', () => {
+ it('admits exactly GRANT_CAP grants and refuses the 65th', () => {
+ for (let i = 0; i < GRANT_CAP; i++) {
+ expect(grant('caller-a', `proj-${i}`)).toBe('ok')
+ expect(atCap('caller-a')).toBe(i === GRANT_CAP - 1)
+ }
+ expect(grant('caller-a', 'proj-one-too-many')).toBe('cap')
+ // Refused means refused: the over-cap id was NOT recorded (no silent eviction either — the
+ // first 64 all survive).
+ expect(isGranted('caller-a', 'proj-one-too-many')).toBe(false)
+ expect(isGranted('caller-a', 'proj-0')).toBe(true)
+ expect(isGranted('caller-a', `proj-${GRANT_CAP - 1}`)).toBe(true)
+ // The cap is per caller, not global.
+ expect(atCap('caller-b')).toBe(false)
+ expect(grant('caller-b', 'proj-0')).toBe('ok')
+ })
+})
+
+describe('gateProjectTarget (spec §3/§5) — every branch, fail closed', () => {
+ const base = {
+ verified: true,
+ verb: 'open-claude',
+ targetProjectId: 'proj-t' as string | undefined,
+ callerProjectId: 'proj-own' as string | undefined,
+ targetIsSsh: false as boolean | undefined,
+ granted: false
+ }
+
+ it('is a no-op for a verb that is not a project-targetable open', () => {
+ expect(PROJECT_TARGETABLE_VERBS.has('open-claude')).toBe(true)
+ expect(PROJECT_TARGETABLE_VERBS.has('open-terminal')).toBe(true)
+ expect(PROJECT_TARGETABLE_VERBS.has('open-agent')).toBe(true)
+ expect(PROJECT_TARGETABLE_VERBS.has('show-image')).toBe(false)
+ expect(gateProjectTarget({ ...base, verb: 'list' })).toBe('allow')
+ })
+
+ it('is a no-op when no --project is present', () => {
+ expect(gateProjectTarget({ ...base, targetProjectId: undefined })).toBe('allow')
+ })
+
+ it('refuses an unverified caller with the flat sentence, before anything else', () => {
+ // Even the caller's OWN project: --project requires verified === true (P1's arg half), and
+ // the sentence carries no token/restart advice (a designed refusal, not an outage).
+ const r = gateProjectTarget({ ...base, verified: false, targetProjectId: 'proj-own' })
+ expect(r).toEqual({ refuse: PROJECT_TARGETING_REFUSAL })
+ for (const hint of ['token', 'restart', 'identity']) {
+ expect(PROJECT_TARGETING_REFUSAL.toLowerCase()).not.toContain(hint)
+ }
+ })
+
+ it('refuses an unknown/deleted target id — fail closed, same sentence as ungranted', () => {
+ // targetIsSsh === undefined is "main's own store does not know this project". The refusal
+ // reuses PROJECT_TARGET_REFUSED so a probing caller cannot distinguish "does not exist"
+ // from "exists but not granted" (no project-existence oracle).
+ const r = gateProjectTarget({ ...base, targetIsSsh: undefined, granted: true })
+ expect(r).toEqual({ refuse: PROJECT_TARGET_REFUSED })
+ })
+
+ it('allows the caller its own project, SSH-own included (the legacy live path)', () => {
+ expect(gateProjectTarget({ ...base, targetProjectId: 'proj-own' })).toBe('allow')
+ expect(
+ gateProjectTarget({ ...base, targetProjectId: 'proj-own', targetIsSsh: true })
+ ).toBe('allow')
+ })
+
+ it('refuses an SSH target that is not the caller own project — even a (impossible) granted one', () => {
+ // Grants are only ever minted by local open-project, so a granted SSH id cannot exist; the
+ // SSH check running BEFORE the granted check is the belt for that invariant.
+ const r = gateProjectTarget({ ...base, targetIsSsh: true, granted: true })
+ expect(r).toEqual({ refuse: PROJECT_TARGET_SSH_UNSUPPORTED })
+ })
+
+ it('allows a granted target and refuses an ungranted one with the named sentence', () => {
+ expect(gateProjectTarget({ ...base, granted: true })).toBe('allow')
+ expect(gateProjectTarget({ ...base, granted: false })).toEqual({
+ refuse: PROJECT_TARGET_REFUSED
+ })
+ expect(PROJECT_TARGET_REFUSED).toBe(
+ 'project-target-refused: you may only target your own project or a project id ' +
+ 'open-project returned to you in this session'
+ )
+ })
+
+ it('composes with the real ledger: granted for A, still refused for B (P2 end-to-end)', () => {
+ grant('caller-a', 'proj-t')
+ const forCaller = (caller: string) =>
+ gateProjectTarget({ ...base, granted: isGranted(caller, 'proj-t') })
+ expect(forCaller('caller-a')).toBe('allow')
+ expect(forCaller('caller-b')).toEqual({ refuse: PROJECT_TARGET_REFUSED })
+ })
+})
+
+describe('validateOpenProjectCwd (P7) — resolved once, statted once, fails closed', () => {
+ const dirStat = { isDirectory: () => true }
+ const fileStat = { isDirectory: () => false }
+
+ it('refuses a relative path before touching the filesystem at all', () => {
+ let stats = 0
+ const r = validateOpenProjectCwd('repo/sub', () => ((stats++, dirStat)))
+ expect(r).toEqual({ error: OPEN_PROJECT_CWD_INVALID })
+ expect(stats).toBe(0)
+ expect(validateOpenProjectCwd('', () => dirStat)).toEqual({ error: OPEN_PROJECT_CWD_INVALID })
+ expect(validateOpenProjectCwd('./x', () => dirStat)).toEqual({
+ error: OPEN_PROJECT_CWD_INVALID
+ })
+ })
+
+ it('resolves traversal and stats the RESOLVED path, exactly once', () => {
+ const statted: string[] = []
+ const r = validateOpenProjectCwd('/tmp/a/../b/./c/', (p) => {
+ statted.push(p)
+ return dirStat
+ })
+ // The resolved form — never the raw argument — is what every later step (dedupe, the PR 2
+ // dialog, storage) sees.
+ expect(r).toEqual({ resolved: path.resolve('/tmp/a/../b/./c/') })
+ expect(statted).toEqual([path.resolve('/tmp/a/../b/./c/')])
+ })
+
+ it('refuses a nonexistent path (stat throws) and a non-directory, with the named error', () => {
+ expect(
+ validateOpenProjectCwd('/no/such/dir', () => {
+ throw new Error('ENOENT')
+ })
+ ).toEqual({ error: OPEN_PROJECT_CWD_INVALID })
+ expect(validateOpenProjectCwd('/tmp/some.file', () => fileStat)).toEqual({
+ error: OPEN_PROJECT_CWD_INVALID
+ })
+ })
+})
diff --git a/src/main/project-grants.ts b/src/main/project-grants.ts
new file mode 100644
index 000000000..c06658b41
--- /dev/null
+++ b/src/main/project-grants.ts
@@ -0,0 +1,164 @@
+/**
+ * The session-scoped project-grant ledger + the `--project` targeting gate (issue #338, spec §3).
+ *
+ * WHO MAY TARGET WHAT: a control caller may aim an open verb (`open-terminal`/`open-claude`/
+ * `open-agent`) at (a) its OWN project, or (b) a project id that `open-project` RETURNED TO THAT
+ * SAME CALLER in this app run. Nothing else — arbitrary cross-project targeting is deliberately
+ * not v1 (confused-deputy-adjacent; a future version needs the target project's own capability
+ * consent via the #213 mechanism, which would be a third disjunct in `gateProjectTarget`, not a
+ * redesign).
+ *
+ * IN MEMORY, IN MAIN, NEVER PERSISTED — the browser-ownership-ledger posture
+ * (browser-control-ledger.ts), for the same reason: a grant is a record of consent given to a
+ * RUNNING session, not a durable claim. An app restart clears every grant; a caller's node
+ * teardown (pty destroy/recycle, wired in index.ts) clears that caller's. Recording happens ONLY
+ * in main's control-handler wrapper on `result.ok && verified` — main's own identity verdict for
+ * that request, never anything off the wire or out of project.json.
+ *
+ * PURE on purpose: no electron, no fs, no child_process (project-grants.test.ts asserts this
+ * structurally). It unit-tests like agent-message-scope.ts and cannot persist anything even by
+ * accident.
+ */
+import path from 'node:path'
+
+/** At most this many granted project ids per caller. Beyond it `open-project` REFUSES
+ * (`open-project-grant-cap`) rather than evicting silently — an evicted grant would revoke a
+ * targeting right the human consented to without anyone being told. */
+export const GRANT_CAP = 64
+
+/** callerNodeId -> the project ids open-project returned to that caller this app run. */
+const grants = new Map<string, Set<string>>()
+
+/** Record that `open-project` returned `projectId` to `callerNodeId`. `'cap'` = refused (the set
+ * is full and `projectId` is not already in it); nothing is recorded and nothing is evicted. */
+export function grant(callerNodeId: string, projectId: string): 'ok' | 'cap' {
+ const set = grants.get(callerNodeId) ?? new Set<string>()
+ if (!set.has(projectId) && set.size >= GRANT_CAP) return 'cap'
+ set.add(projectId)
+ grants.set(callerNodeId, set)
+ return 'ok'
+}
+
+/** Was `projectId` granted to `callerNodeId` — THIS caller, not any caller (spec P2)? */
+export function isGranted(callerNodeId: string, projectId: string): boolean {
+ return grants.get(callerNodeId)?.has(projectId) ?? false
+}
+
+/** Is this caller's grant set full? Consulted BEFORE forwarding an `open-project`, so the refusal
+ * arrives before a dialog is ever shown rather than after the human already consented. */
+export function atCap(callerNodeId: string): boolean {
+ return (grants.get(callerNodeId)?.size ?? 0) >= GRANT_CAP
+}
+
+/** Caller-node teardown (pty destroy/recycle): that caller's grants die with its identity. */
+export function clearCaller(callerNodeId: string): void {
+ grants.delete(callerNodeId)
+}
+
+/** Everything gone — the app-restart lifetime, and the test seam. */
+export function clearAll(): void {
+ grants.clear()
+}
+
+/** The open verbs that accept `--project` (spec §2.2). Only these three — `--project` on any
+ * other verb is dead weight the gate deliberately ignores (spec §7.5). */
+export const PROJECT_TARGETABLE_VERBS: ReadonlySet<string> = new Set([
+ 'open-terminal',
+ 'open-claude',
+ 'open-agent'
+])
+
+/** The flat refusal an UNVERIFIED caller's `--project` gets — one sentence, no diagnosis, no
+ * token/restart advice, same posture as the hook server's verified-only refusals. */
+export const PROJECT_TARGETING_REFUSAL = 'Project targeting refused.'
+
+/** The named refusal for an id that is neither the caller's own project nor granted. Also the
+ * answer for an id main's store does not know: refusing unknown ids with the SAME sentence keeps
+ * this from becoming a project-existence oracle. */
+export const PROJECT_TARGET_REFUSED =
+ 'project-target-refused: you may only target your own project or a project id open-project ' +
+ 'returned to you in this session'
+
+/** Targeting an SSH project (other than the caller's own, which takes the legacy live path) is
+ * not v1 (spec B5/§6): the nodes would need host-side materialization this feature defers. */
+export const PROJECT_TARGET_SSH_UNSUPPORTED =
+ 'project-target-ssh-unsupported: opening sessions into an SSH project is not supported — do not retry'
+
+/** `open-project` from an agent whose own project is SSH: the --cwd would be a host path (B5). */
+export const OPEN_PROJECT_LOCAL_ONLY =
+ 'open-project-local-only: open-project is not available from an SSH project — do not retry'
+
+/** The caller's grant set is full (see GRANT_CAP). */
+export const OPEN_PROJECT_GRANT_CAP =
+ 'open-project-grant-cap: this session already holds the maximum number of project grants'
+
+/** The wrapper could not resolve the caller's own project from main's persisted store (a node
+ * saved seconds ago may still be inside the save debounce). Fail closed, but say it is
+ * transient — this is the one refusal here that a short wait can clear. */
+export const OPEN_PROJECT_CALLER_UNRESOLVED =
+ 'open-project-caller-unresolved: the calling node is not in any saved project yet — wait a few seconds and retry once'
+
+/** `--cwd` failed validation: not absolute, not existing, or not a directory. */
+export const OPEN_PROJECT_CWD_INVALID =
+ 'open-project-cwd-invalid: --cwd must be an absolute path to an existing directory'
+
+export type ProjectTargetGate = 'allow' | { refuse: string }
+
+/**
+ * The `--project` targeting gate (spec §3 "consumed" + §5 P1/P2/P8), run in main's control-handler
+ * wrapper BEFORE anything is forwarded to the renderer — the renderer never sees an unauthorized
+ * `--project`. Every input is main's own data: `verified` is the hook server's identity verdict
+ * for THIS request, `callerProjectId` comes from node membership in `persistedCanvases()`,
+ * `targetIsSsh` from `projectMetaFor` (undefined = the store does not know the target), and
+ * `granted` from this module's ledger. Nothing is read off the request except the target id
+ * being judged.
+ *
+ * Branch order is load-bearing: unknown-target refuses before the own-project allow (a project
+ * main cannot resolve is not provably anyone's own), and the SSH refusal runs before the granted
+ * allow (grants are only minted by local open-project, so a granted SSH id cannot exist — this is
+ * the belt for that invariant).
+ */
+export function gateProjectTarget(input: {
+ verified: boolean
+ verb: string
+ targetProjectId: string | undefined
+ callerProjectId: string | undefined
+ targetIsSsh: boolean | undefined
+ granted: boolean
+}): ProjectTargetGate {
+ const { verified, verb, targetProjectId, callerProjectId, targetIsSsh, granted } = input
+ if (!PROJECT_TARGETABLE_VERBS.has(verb)) return 'allow'
+ if (targetProjectId === undefined) return 'allow'
+ if (verified !== true) return { refuse: PROJECT_TARGETING_REFUSAL }
+ if (targetIsSsh === undefined) return { refuse: PROJECT_TARGET_REFUSED }
+ if (callerProjectId !== undefined && targetProjectId === callerProjectId) return 'allow'
+ if (targetIsSsh) return { refuse: PROJECT_TARGET_SSH_UNSUPPORTED }
+ if (granted) return 'allow'
+ return { refuse: PROJECT_TARGET_REFUSED }
+}
+
+/**
+ * Validate + normalize an `open-project --cwd` argument (spec §2.1 step 1, P7). The caller's path
+ * is hostile input: it must be absolute, is resolved ONCE (`path.resolve` collapses `..`/`.`),
+ * and the RESOLVED form is statted ONCE (single fd — no TOCTOU re-walk; `statFn` follows
+ * symlinks, so the directory check is on the real target). The resolved path — never the raw
+ * argument — is what every later step sees: the PR 2 confirm dialog shows it, the dedupe compares
+ * it, the store records it.
+ *
+ * `statFn` is injected (main passes `fs.statSync`) so the rules stay pure and unit-testable.
+ */
+export function validateOpenProjectCwd(
+ raw: string,
+ statFn: (p: string) => { isDirectory(): boolean }
+): { resolved: string } | { error: string } {
+ if (typeof raw !== 'string' || raw.length === 0 || !path.isAbsolute(raw)) {
+ return { error: OPEN_PROJECT_CWD_INVALID }
+ }
+ const resolved = path.resolve(raw)
+ try {
+ if (!statFn(resolved).isDirectory()) return { error: OPEN_PROJECT_CWD_INVALID }
+ } catch {
+ return { error: OPEN_PROJECT_CWD_INVALID }
+ }
+ return { resolved }
+}