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): wire the targeting gate, cwd validation and grant lifecycle (Task 1.4 + V-2)

enes7e6a18f5585a
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 9184a7e6c..ca8bb9066 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -1764,3 +1764,36 @@ describe('the shared project file carries content, not machine identity', () =>
expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(bytes)
})
})
+
+describe('projectMetaFor (issue #338 PR 1) — target exists / is SSH, from the store alone', () => {
+ // The --project targeting gate (src/main/project-grants.ts) learns "does this project exist,
+ // and is it SSH" from main's OWN store — never from anything the caller sent. Same three
+ // entry kinds as persistedCanvases: inline (e.project), ssh (e.ssh), local ref (e.cwd).
+ it('answers for all three entry kinds and undefined for an unknown id', async () => {
+ const store = new WorkspaceStore()
+ const local = project({ id: 'p-local', cwd: projRoot })
+ const inline = project({ id: 'p-inline', cwd: undefined })
+ const ssh = project({
+ id: 'p-ssh',
+ cwd: undefined,
+ ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
+ })
+ await store.save(ws([local, inline, ssh]))
+
+ expect(store.projectMetaFor('p-local')).toEqual({ ssh: false })
+ expect(store.projectMetaFor('p-inline')).toEqual({ ssh: false })
+ expect(store.projectMetaFor('p-ssh')).toEqual({ ssh: true })
+ // Fail closed: an id the store does not know (deleted, invented, another machine's) has no
+ // meta at all — the gate refuses on undefined.
+ expect(store.projectMetaFor('p-gone')).toBeUndefined()
+ expect(store.projectMetaFor('')).toBeUndefined()
+ })
+
+ it('a deleted project stops answering after the save that removed it', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'p-a', cwd: projRoot }), project({ id: 'p-b', cwd: undefined })]))
+ expect(store.projectMetaFor('p-b')).toEqual({ ssh: false })
+ await store.save(ws([project({ id: 'p-a', cwd: projRoot })]))
+ expect(store.projectMetaFor('p-b')).toBeUndefined()
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 7e3816dfb..c0e7470c9 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1144,6 +1144,26 @@ export class WorkspaceStore {
return out
}
+ /**
+ * Does this project exist on THIS machine, and is it SSH? The `--project` targeting gate
+ * (issue #338, src/main/project-grants.ts) asks main's own store — never the request — before
+ * any targeted open is forwarded. Same three-entry-kind scan and same id semantics as
+ * `persistedCanvases` (inline keyed by `e.project.id`, ssh/local refs by `e.id`), because the
+ * projectId a grant names there must resolve to the same project here. `undefined` = unknown
+ * to this store (deleted, invented, another machine's) — the gate fails closed on it.
+ */
+ projectMetaFor(projectId: string): { ssh: boolean } | undefined {
+ if (!projectId) return undefined
+ for (const e of this.index?.entries ?? []) {
+ if (e.project) {
+ if (e.project.id === projectId) return { ssh: !!e.project.ssh }
+ continue
+ }
+ if (e.id === projectId) return { ssh: !!e.ssh }
+ }
+ return undefined
+ }
+
/**
* The capability view of one project, for `projectCapabilityGrantedFor`: the STRICT capability
* flags from the shared file (`readProjectCapabilities` — literal `true`, known keys only) plus
diff --git a/src/main/index.ts b/src/main/index.ts
index 083645d27..2e6256f82 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -17,6 +17,18 @@ import { writeFilesToClipboard } from './clipboard-files'
import { pickProjectIcon } from './project-icon-upload'
import { allowGuestNavigation } from './webview-nav'
import { BrowserControlLedger } from './browser-control-ledger'
+import {
+ grant as grantProjectTo,
+ isGranted as projectGrantedTo,
+ atCap as projectGrantsAtCap,
+ clearCaller as clearProjectGrants,
+ gateProjectTarget,
+ validateOpenProjectCwd,
+ PROJECT_TARGETABLE_VERBS,
+ OPEN_PROJECT_LOCAL_ONLY,
+ OPEN_PROJECT_GRANT_CAP,
+ OPEN_PROJECT_CALLER_UNRESOLVED
+} from './project-grants'
import { BrowserLeaseManager, BrowserSession } from './browser-lease'
import { CdpEventBus, type Sendable } from './browser-actions'
import { RefTable } from './browser-refs'
@@ -91,7 +103,7 @@ import {
import { generateCommitMessage, generateGroupName, generateTerminalName } from '../core/commit-message'
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
-import { hookServer } from '../core/agents/hook-server'
+import { hookServer, OPEN_PROJECT_CONTROL_REFUSAL } from '../core/agents/hook-server'
import { askpassServer, ensureAskpassScript } from './remote-ssh/ssh-askpass'
import { appSshAgent } from './remote-ssh/ssh-agent'
import {
@@ -2916,6 +2928,12 @@ app.whenReady().then(async () => {
corePlatform.on(IPC.ptyRecycle, (nodeId: string) =>
pushBrowserLeases(revokeBrowserByOwner(nodeId, browserRevocation))
)
+ // The caller's PROJECT GRANTS die with its node too (issue #338, spec P3) — same teardown
+ // anchor, same reasoning as the browser leases above: a grant is consent given to a running
+ // session, and a recycle mints a fresh identity that must re-earn its targeting rights via
+ // open-project. App restart clears the whole in-memory ledger by construction.
+ corePlatform.on(IPC.ptyDestroy, (nodeId: string) => clearProjectGrants(nodeId))
+ corePlatform.on(IPC.ptyRecycle, (nodeId: string) => clearProjectGrants(nodeId))
// App quit: detach every debugger lease. A second `before-quit` listener alongside the module-
// level flush one (both fire); scoped here so it can reach `browserRevocation`. No push — the
// window is going away. LIFECYCLE, so no tombstone (the in-memory ledger is gone on quit anyway).
@@ -3028,11 +3046,52 @@ app.whenReady().then(async () => {
? { ok: true, message: result.message }
: { ok: false, error: result.message, message: result.message }
}
+ // The caller's OWNING project, by node membership in main's own persisted store — the same
+ // source `resolveDeliveryScope` trusts. `undefined` = not in any saved project (a brand-new
+ // node inside the save debounce, or an id main never saved): the project gates fail closed.
+ const projectIdOfNode = (id: string): string | undefined =>
+ workspaceStore.persistedCanvases().find((c) => c.nodes.some((n) => n.id === id))?.id
hookServer.setControlHandler(async ({ verb, nodeId, args, verified }) => {
// `browser` is answered in MAIN and never forwarded to the renderer's agent-control dispatch:
// the debugger handle and the CDP allowlist are main-side, and the renderer is the more
// attackable half. Every other verb still round-trips to the renderer below.
if (verb === 'browser') return handleBrowserVerb(nodeId, args, verified)
+ // ── `open-project` + `--project` targeting, gated in MAIN before anything is forwarded
+ // (issue #338 PR 1). The renderer never sees an invalid cwd or an unauthorized `--project`.
+ // The verb itself is verified-only at the hook-server route (requiresVerified) — by the time
+ // an open-project reaches this wrapper, `verified` is true; the gates below are main's own
+ // belt plus everything identity cannot answer (SSH caller, cwd validity, the grant cap).
+ if (verb === 'open-project') {
+ const refuse = (error: string) => ({ ok: false, error, message: error })
+ if (!verified) return refuse(OPEN_PROJECT_CONTROL_REFUSAL)
+ const callerProjectId = projectIdOfNode(nodeId)
+ if (!callerProjectId) return refuse(OPEN_PROJECT_CALLER_UNRESOLVED)
+ if (workspaceStore.projectMetaFor(callerProjectId)?.ssh) {
+ // B5: local-only v1 — an SSH-project agent's --cwd would be a host path.
+ return refuse(OPEN_PROJECT_LOCAL_ONLY)
+ }
+ // Refuse the cap BEFORE the renderer would show a dialog (PR 2): a grant that cannot be
+ // recorded must not be consented to first.
+ if (projectGrantsAtCap(nodeId)) return refuse(OPEN_PROJECT_GRANT_CAP)
+ const cwd = validateOpenProjectCwd(args.cwd ?? '', (p) => statSync(p))
+ if ('error' in cwd) return refuse(cwd.error)
+ // The RESOLVED path — never the raw argument — is what the renderer (PR 2's dialog, the
+ // dedupe, the store) sees. Single resolution, in main, right here.
+ args = { ...args, cwd: cwd.resolved }
+ } else if (PROJECT_TARGETABLE_VERBS.has(verb) && args.project !== undefined) {
+ // Open verbs carrying `--project`: own-or-granted only (spec §3, P2), decided against
+ // main's own store + ledger. Anything else is refused without forwarding.
+ const meta = workspaceStore.projectMetaFor(args.project)
+ const gate = gateProjectTarget({
+ verified,
+ verb,
+ targetProjectId: args.project,
+ callerProjectId: projectIdOfNode(nodeId),
+ targetIsSsh: meta?.ssh,
+ granted: projectGrantedTo(nodeId, args.project)
+ })
+ if (gate !== 'allow') return { ok: false, error: gate.refuse, message: gate.refuse }
+ }
const target = getMainWindow()
if (!target) return { ok: false, error: 'window unavailable' }
const requestId = randomUUID()
@@ -3071,6 +3130,18 @@ app.whenReady().then(async () => {
pushBrowserLeases()
}
}
+ // Record a project grant the moment an open-project succeeds — the open-browser ledger
+ // pattern above, same conditions: ONLY when the caller's identity verdict for THIS request
+ // was `verified` (main's own verdict, never anything off the wire) AND the renderer's reply
+ // carries a non-empty projectId. Inert until PR 2: today the renderer's `default:` case
+ // answers `unknown verb: open-project` with ok: false, so nothing is ever recorded — but the
+ // record path ships fail-closed and finished, not stubbed.
+ if (verb === 'open-project' && verified && result.ok) {
+ const opened = result.result as { projectId?: unknown } | undefined
+ if (typeof opened?.projectId === 'string' && opened.projectId) {
+ grantProjectTo(nodeId, opened.projectId)
+ }
+ }
return result
})
initMediaProtocol()
diff --git a/src/main/project-grants.test.ts b/src/main/project-grants.test.ts
index 02ac93d56..19414c323 100644
--- a/src/main/project-grants.test.ts
+++ b/src/main/project-grants.test.ts
@@ -204,3 +204,50 @@ describe('validateOpenProjectCwd (P7) — resolved once, statted once, fails clo
})
})
})
+
+describe('main wiring (structural) — the wrapper records, consumes and clears correctly', () => {
+ // Structural in the control-destructive.test.ts sense and for the same reason: the wiring lives
+ // inside index.ts's setControlHandler wrapper and whenReady closure, which have no unit seam,
+ // and the property pinned — WHEN a grant is recorded and WHEN it dies — is a property of the
+ // source. The behavioural halves (the ledger, the gate, the cwd rules) are proven above against
+ // the real functions.
+ const src = fs.readFileSync(path.join(__dirname, 'index.ts'), 'utf8')
+
+ it('records a grant ONLY under verified && result.ok with a string projectId (the open-browser pattern)', () => {
+ const at = src.indexOf("verb === 'open-project' && verified && result.ok")
+ expect(at).toBeGreaterThan(-1)
+ const block = src.slice(at, at + 400)
+ expect(block).toContain("typeof opened?.projectId === 'string'")
+ expect(block).toContain('grantProjectTo(nodeId, opened.projectId)')
+ // No other call site mints a grant: the record path is the wrapper's, once.
+ expect(src.match(/grantProjectTo\(/g)?.length).toBe(1)
+ })
+
+ it('consumes the ledger per-CALLER and gates before forwarding to the renderer', () => {
+ // The gate reads isGranted(nodeId, …) — the verified caller of THIS request — never a global
+ // or target-derived key, and it runs inside the wrapper before webContents.send.
+ expect(src).toMatch(/granted: projectGrantedTo\(nodeId, args\.project\)/)
+ const gateAt = src.indexOf('gateProjectTarget({')
+ const forwardAt = src.indexOf('target.webContents.send(IPC.agentControl', gateAt)
+ expect(gateAt).toBeGreaterThan(-1)
+ expect(forwardAt).toBeGreaterThan(gateAt)
+ // The target's SSH/existence meta comes from main's own store, never the request.
+ expect(src).toMatch(/workspaceStore\.projectMetaFor\(args\.project\)/)
+ })
+
+ it('clears a caller on BOTH pty teardown paths (destroy + recycle) — spec P3', () => {
+ expect(src).toMatch(
+ /corePlatform\.on\(IPC\.ptyDestroy, \(nodeId: string\) => clearProjectGrants\(nodeId\)\)/
+ )
+ expect(src).toMatch(
+ /corePlatform\.on\(IPC\.ptyRecycle, \(nodeId: string\) => clearProjectGrants\(nodeId\)\)/
+ )
+ })
+
+ it('open-project resolves + replaces the cwd in MAIN before forwarding (P7)', () => {
+ const at = src.indexOf('validateOpenProjectCwd(args.cwd')
+ expect(at).toBeGreaterThan(-1)
+ // The resolved form replaces the raw argument in the forwarded args.
+ expect(src.slice(at, at + 400)).toContain('args = { ...args, cwd: cwd.resolved }')
+ })
+})