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(push): granted mode — the Server Edition pushes to SSH-possessed phones

enes6ef722ce2d6e
diff --git a/src/core/push-grants.test.ts b/src/core/push-grants.test.ts
new file mode 100644
index 000000000..eb43d6e9b
--- /dev/null
+++ b/src/core/push-grants.test.ts
@@ -0,0 +1,208 @@
+import { describe, it, expect, vi } from 'vitest'
+import path from 'path'
+import {
+ loadPushGrants,
+ createGrantsAccessor,
+ type GrantsFsLike
+} from './push-grants'
+
+const DIR = '/home/user/.nodeterm/push-grants'
+
+interface FakeFile {
+ content: string
+ mtimeMs: number
+}
+
+/** In-memory fs standing in for the grant directory. Tracks a directory mtime that bumps on any
+ * add/remove (as a real filesystem does), and per-file mtimes the accessor's dead-mark keys on. */
+class FakeFs {
+ private files = new Map<string, FakeFile>()
+ dirMtime = 1000
+ readdirCalls = 0
+
+ put(name: string, content: string, mtimeMs: number, bumpDir = true): void {
+ this.files.set(path.join(DIR, name), { content, mtimeMs })
+ if (bumpDir) this.dirMtime++
+ }
+
+ grant(name: string, grant: string, mtimeMs: number, extra: Record<string, unknown> = {}): void {
+ this.put(name, JSON.stringify({ v: 1, grant, ...extra }), mtimeMs)
+ }
+
+ remove(name: string): void {
+ this.files.delete(path.join(DIR, name))
+ this.dirMtime++
+ }
+
+ fs(): GrantsFsLike {
+ return {
+ readdirSync: (d) => {
+ this.readdirCalls++
+ if (d !== DIR) throw new Error('ENOENT')
+ return [...this.files.keys()].map((p) => path.basename(p))
+ },
+ readFileSync: (p) => {
+ const f = this.files.get(p)
+ if (!f) throw new Error('ENOENT')
+ return f.content
+ },
+ statSync: (p) => {
+ if (p === DIR) return { mtimeMs: this.dirMtime }
+ const f = this.files.get(p)
+ if (!f) throw new Error('ENOENT')
+ return { mtimeMs: f.mtimeMs }
+ }
+ }
+ }
+}
+
+describe('loadPushGrants', () => {
+ it('reads valid *.grant files, parsing deviceId from filename + connectionId from body', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10, { connectionId: 'conn-A' })
+ ff.grant('dev-B.grant', 'tok-B', 20)
+ const got = loadPushGrants(DIR, ff.fs())
+ expect(got).toEqual([
+ { deviceId: 'dev-A', grant: 'tok-A', connectionId: 'conn-A' },
+ { deviceId: 'dev-B', grant: 'tok-B' }
+ ])
+ })
+
+ it('is tolerant: skips non-.grant files, bad JSON, wrong version, and missing grant', () => {
+ const ff = new FakeFs()
+ ff.grant('good.grant', 'tok-good', 10)
+ ff.put('notes.txt', 'ignore me', 10) // wrong extension
+ ff.put('junk.grant', '{not json', 10) // unparseable (half-written)
+ ff.put('v2.grant', JSON.stringify({ v: 2, grant: 'tok-v2' }), 10) // wrong schema version
+ ff.put('nogrant.grant', JSON.stringify({ v: 1 }), 10) // no grant string
+ ff.put('emptygrant.grant', JSON.stringify({ v: 1, grant: '' }), 10) // empty grant
+ ff.put('array.grant', JSON.stringify([1, 2, 3]), 10) // not an object
+ const got = loadPushGrants(DIR, ff.fs())
+ expect(got).toEqual([{ deviceId: 'good', grant: 'tok-good' }])
+ })
+
+ it('returns [] for a missing directory (readdir throws)', () => {
+ const fsi: GrantsFsLike = {
+ readdirSync: () => {
+ throw new Error('ENOENT')
+ },
+ readFileSync: () => '',
+ statSync: () => ({ mtimeMs: 0 })
+ }
+ expect(loadPushGrants(DIR, fsi)).toEqual([])
+ })
+})
+
+describe('createGrantsAccessor', () => {
+ it('caches: no full re-scan while the dir mtime is unchanged and the TTL has not elapsed', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 1000 })
+ expect(acc.get().map((g) => g.grant)).toEqual(['tok-A'])
+ expect(ff.readdirCalls).toBe(1)
+ // A second get() shortly after (dir mtime same) hits the cache — no readdir.
+ clock = 500
+ acc.get()
+ expect(ff.readdirCalls).toBe(1)
+ })
+
+ it('re-scans when the dir mtime changes (a new grant dropped)', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 100000 })
+ expect(acc.get().map((g) => g.grant)).toEqual(['tok-A'])
+ // Still within TTL, but a new file bumps the dir mtime → cheap stat forces a rescan.
+ clock = 10
+ ff.grant('dev-B.grant', 'tok-B', 20)
+ expect(acc.get().map((g) => g.grant).sort()).toEqual(['tok-A', 'tok-B'])
+ expect(ff.readdirCalls).toBe(2)
+ })
+
+ it('re-scans once the TTL elapses even if the dir mtime never moved', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 1000 })
+ acc.get()
+ expect(ff.readdirCalls).toBe(1)
+ // Add a file WITHOUT bumping the dir mtime (bumpDir:false) — only the TTL can surface it.
+ ff.put('dev-B.grant', JSON.stringify({ v: 1, grant: 'tok-B' }), 20, false)
+ clock = 500
+ acc.get()
+ expect(ff.readdirCalls).toBe(1) // TTL not elapsed, mtime unchanged → cached
+ clock = 1500
+ expect(acc.get().map((g) => g.grant).sort()).toEqual(['tok-A', 'tok-B'])
+ expect(ff.readdirCalls).toBe(2)
+ })
+
+ describe('dead-mark lifecycle', () => {
+ it('markDead drops a grant from get() until its file changes', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ ff.grant('dev-B.grant', 'tok-B', 20)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 100000 })
+ expect(acc.get().map((g) => g.grant).sort()).toEqual(['tok-A', 'tok-B'])
+ // A 401/403 for tok-A drops it.
+ acc.markDead('tok-A')
+ expect(acc.get().map((g) => g.grant)).toEqual(['tok-B'])
+ // A rescan with the file UNCHANGED keeps it dead.
+ clock = 10
+ ff.grant('dev-C.grant', 'tok-C', 30) // bumps dir mtime → forces rescan
+ expect(acc.get().map((g) => g.grant).sort()).toEqual(['tok-B', 'tok-C'])
+ })
+
+ it('a re-dropped grant file (new mtime) clears the dead mark', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 100000 })
+ acc.get()
+ acc.markDead('tok-A')
+ expect(acc.get()).toEqual([])
+ // The phone re-mints + re-drops: same file, new mtime (and it happens to carry a new token,
+ // but even the same token with a changed mtime clears the mark).
+ clock = 10
+ ff.grant('dev-A.grant', 'tok-A', 99)
+ expect(acc.get().map((g) => g.grant)).toEqual(['tok-A'])
+ })
+
+ it('a vanished grant file clears its dead mark (no leak)', () => {
+ const ff = new FakeFs()
+ ff.grant('dev-A.grant', 'tok-A', 10)
+ let clock = 0
+ const acc = createGrantsAccessor({ dir: DIR, fs: ff.fs(), now: () => clock, ttlMs: 100000 })
+ acc.get()
+ acc.markDead('tok-A')
+ clock = 10
+ ff.remove('dev-A.grant') // bumps dir mtime → rescan
+ expect(acc.get()).toEqual([])
+ // Re-drop with the same token: not dead-marked (the mark was cleared when the file vanished).
+ clock = 20
+ ff.grant('dev-A.grant', 'tok-A', 40)
+ expect(acc.get().map((g) => g.grant)).toEqual(['tok-A'])
+ })
+ })
+
+ it('fails open: a directory that never exists yields [] and never throws', () => {
+ const acc = createGrantsAccessor({
+ dir: DIR,
+ fs: {
+ readdirSync: () => {
+ throw new Error('ENOENT')
+ },
+ readFileSync: () => {
+ throw new Error('ENOENT')
+ },
+ statSync: () => {
+ throw new Error('ENOENT')
+ }
+ },
+ now: () => 0
+ })
+ expect(acc.get()).toEqual([])
+ expect(() => acc.markDead('x')).not.toThrow()
+ })
+})
diff --git a/src/core/push-grants.ts b/src/core/push-grants.ts
new file mode 100644
index 000000000..e9d594584
--- /dev/null
+++ b/src/core/push-grants.ts
@@ -0,0 +1,208 @@
+// SSH-possession push grants — host-side loader (spec: nodeterm-server/docs/specs/2026-07-21-push-grants.md).
+//
+// A host the phone reaches by plain SSH (the Server Edition on a Linux box) has NO relay identity,
+// so it can push nothing through the backend's host-identity auth. The fix: SSH possession IS the
+// authorization. The phone, which can already write files on the host as the user, drops a signed,
+// device-scoped grant token at `~/.nodeterm/push-grants/<deviceId>.grant`; a host that holds that
+// grant may push to THAT one phone only (Authorization: Bearer <grant>). Compromise of the host
+// adds no new power beyond spamming its own operator.
+//
+// This module reads that directory and hands the live grant list to `push-notify.ts`'s granted
+// mode. It is pure + electron-free (`src/core`): all fs access is behind an injectable seam so the
+// loader is unit-testable, and it is tolerant of junk/partial files (a phone mid-write, or an
+// unrelated file in the dir, must never break the scan).
+
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+
+/** A grant loaded from `<deviceId>.grant`. `connectionId` (the phone's own UUID for the host
+ * connection) rides inside the signed token; it is surfaced here only for diagnostics/routing. */
+export interface PushGrant {
+ /** deviceId parsed from the filename (`<deviceId>.grant`). */
+ deviceId: string
+ /** The signed grant token (the `Authorization: Bearer` value). */
+ grant: string
+ /** The phone's connection UUID, if the file carried one. */
+ connectionId?: string
+}
+
+/** The slice of `fs` the loader needs — injectable so tests drive it without touching disk. */
+export interface GrantsFsLike {
+ readdirSync(dir: string): string[]
+ readFileSync(p: string, enc: 'utf8'): string
+ statSync(p: string): { mtimeMs: number }
+}
+
+const nodeFs: GrantsFsLike = {
+ readdirSync: (d) => fs.readdirSync(d),
+ readFileSync: (p, e) => fs.readFileSync(p, e),
+ statSync: (p) => fs.statSync(p)
+}
+
+/** `~/.nodeterm/push-grants` — where the phone drops `<deviceId>.grant` files over SSH. */
+export function defaultGrantDir(): string {
+ return path.join(os.homedir(), '.nodeterm', 'push-grants')
+}
+
+const GRANT_EXT = '.grant'
+const DEFAULT_TTL_MS = 5 * 60 * 1000
+
+/** Internal scan result — carries the per-file mtime the dead-mark lifecycle keys on. */
+interface ScannedGrant extends PushGrant {
+ mtimeMs: number
+}
+
+/**
+ * Scan `dir` for `*.grant` files, returning the parseable ones. Tolerant at every step: a missing
+ * dir, an unreadable/unstattable file, non-JSON, the wrong schema version, or a missing `grant`
+ * string are all skipped silently (a half-written file simply doesn't appear until it's complete).
+ */
+function scanGrantDir(dir: string, fsi: GrantsFsLike): ScannedGrant[] {
+ let names: string[]
+ try {
+ names = fsi.readdirSync(dir)
+ } catch {
+ // No dir yet (the common case: the phone hasn't dropped anything) — no grants.
+ return []
+ }
+ const out: ScannedGrant[] = []
+ for (const name of names) {
+ if (!name.endsWith(GRANT_EXT)) continue
+ const deviceId = name.slice(0, -GRANT_EXT.length)
+ if (!deviceId) continue
+ const full = path.join(dir, name)
+ let mtimeMs: number
+ try {
+ mtimeMs = fsi.statSync(full).mtimeMs
+ } catch {
+ continue
+ }
+ let text: string
+ try {
+ text = fsi.readFileSync(full, 'utf8')
+ } catch {
+ continue
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ continue
+ }
+ if (!parsed || typeof parsed !== 'object') continue
+ const rec = parsed as { v?: unknown; grant?: unknown; connectionId?: unknown }
+ if (rec.v !== 1) continue
+ if (typeof rec.grant !== 'string' || rec.grant.length === 0) continue
+ out.push({
+ deviceId,
+ grant: rec.grant,
+ ...(typeof rec.connectionId === 'string' ? { connectionId: rec.connectionId } : {}),
+ mtimeMs
+ })
+ }
+ return out
+}
+
+/**
+ * One-shot read of the grant directory. Pure + injectable fs. Returns the parseable grants; junk
+ * and partial files are skipped. (The cached accessor below is what production wires — this is the
+ * primitive it and tests share.)
+ */
+export function loadPushGrants(
+ dir: string = defaultGrantDir(),
+ fsi: GrantsFsLike = nodeFs
+): PushGrant[] {
+ return scanGrantDir(dir, fsi).map(({ deviceId, grant, connectionId }) => ({
+ deviceId,
+ grant,
+ ...(connectionId ? { connectionId } : {})
+ }))
+}
+
+export interface GrantsAccessorOpts {
+ /** Directory holding `<deviceId>.grant` files. Defaults to `~/.nodeterm/push-grants`. */
+ dir?: string
+ /** Injectable fs (tests). Defaults to node `fs`. */
+ fs?: GrantsFsLike
+ /** Injectable clock (tests). Defaults to `Date.now`. */
+ now?: () => number
+ /** Full re-scan interval. Defaults to 5 min (a cheap dir-mtime check forces an early rescan). */
+ ttlMs?: number
+}
+
+export interface GrantsAccessor {
+ /** The live grants, minus any currently dead-marked ones. Cheap: re-scans only on a dir-mtime
+ * change or once the TTL elapses. */
+ get(): PushGrant[]
+ /** Mark a grant dead after a 401/403 — it's dropped from `get()` until its file changes
+ * (mtime/content), which the phone triggers by re-minting + re-dropping. */
+ markDead(grant: string): void
+ /** Test-only: force the next `get()` to re-scan the directory. */
+ _forceRescan(): void
+}
+
+/**
+ * A cached grant accessor for `push-notify.ts`'s granted mode. Re-scans the directory at most once
+ * per `ttlMs`, plus whenever the directory's mtime changes (a file added/removed/re-dropped — the
+ * cheap stat the spec calls for before each send batch). A 401/403 marks a grant dead; the mark is
+ * cleared when that grant's file changes (a different mtime) or vanishes, so a phone that re-mints
+ * and re-drops recovers automatically. Fails open: any fs error yields "no grants", never a throw.
+ */
+export function createGrantsAccessor(opts: GrantsAccessorOpts = {}): GrantsAccessor {
+ const dir = opts.dir ?? defaultGrantDir()
+ const fsi = opts.fs ?? nodeFs
+ const now = opts.now ?? Date.now
+ const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS
+
+ let cache: ScannedGrant[] = []
+ let scannedAt = -Infinity
+ let dirMtime = -1
+ // grant token -> the file's mtime when it was marked dead (so a later change clears the mark).
+ const dead = new Map<string, number>()
+
+ function dirMtimeMs(): number {
+ try {
+ return fsi.statSync(dir).mtimeMs
+ } catch {
+ return -1
+ }
+ }
+
+ function refreshIfNeeded(): void {
+ const t = now()
+ const dm = dirMtimeMs()
+ // Cheap gate: skip the full readdir unless the TTL elapsed or the dir mtime moved (add/remove/
+ // atomic re-drop all touch the directory's mtime).
+ if (t - scannedAt < ttlMs && dm === dirMtime) return
+ cache = scanGrantDir(dir, fsi)
+ scannedAt = t
+ dirMtime = dm
+ // Clear any dead mark whose backing file changed (re-dropped/re-minted) or disappeared.
+ for (const [g, deadMtime] of [...dead]) {
+ const cur = cache.find((r) => r.grant === g)
+ if (!cur || cur.mtimeMs !== deadMtime) dead.delete(g)
+ }
+ }
+
+ return {
+ get() {
+ refreshIfNeeded()
+ return cache
+ .filter((r) => !dead.has(r.grant))
+ .map(({ deviceId, grant, connectionId }) => ({
+ deviceId,
+ grant,
+ ...(connectionId ? { connectionId } : {})
+ }))
+ },
+ markDead(grant: string) {
+ const cur = cache.find((r) => r.grant === grant)
+ dead.set(grant, cur ? cur.mtimeMs : -1)
+ },
+ _forceRescan() {
+ scannedAt = -Infinity
+ dirMtime = -1
+ }
+ }
+}
diff --git a/src/core/push-notify.test.ts b/src/core/push-notify.test.ts
index bd627dd14..112a64363 100644
--- a/src/core/push-notify.test.ts
+++ b/src/core/push-notify.test.ts
@@ -470,6 +470,99 @@ describe('createPushNotify', () => {
})
})
+ describe('granted mode (SSH-possession push grants)', () => {
+ const GRANTS = [
+ { deviceId: 'dev-A', grant: 'tok-A', connectionId: 'conn-A' },
+ { deviceId: 'dev-B', grant: 'tok-B' }
+ ]
+
+ function grantDeps(over: Partial<PushNotifyDeps> = {}): PushNotifyDeps {
+ return baseDeps({
+ getHostIdentity: () => null, // no relay identity → granted mode
+ getGrants: () => GRANTS,
+ hostLabel: () => 'niova',
+ ...over
+ })
+ }
+
+ it('fans one POST out per grant: Bearer auth + hostLabel, and NO host identity fields', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(grantDeps({ subscribe: em.subscribe }))
+ em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ const calls = fetchMock.mock.calls
+ expect(calls.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
+ for (const c of calls) {
+ expect(c[0]).toBe('https://api.nodeterm.dev/v1/push/notify')
+ const body = JSON.parse(c[1].body)
+ expect(body.hostLabel).toBe('niova')
+ expect(body).not.toHaveProperty('hostDeviceId')
+ expect(body).not.toHaveProperty('hostPublicKeyB64')
+ expect(body.events).toHaveLength(1)
+ expect(body.events[0].title).toBe('A')
+ }
+ h.stop()
+ })
+
+ it('marks a grant dead on a 401/403 (only the failing one)', async () => {
+ const dead: string[] = []
+ // tok-A → 403, tok-B → 200 (keyed on the Bearer header).
+ fetchMock.mockImplementation(async (_url: string, init: { headers: Record<string, string> }) => ({
+ status: init.headers.authorization === 'Bearer tok-A' ? 403 : 200
+ }))
+ const em = makeEmitter()
+ const h = createPushNotify(grantDeps({ subscribe: em.subscribe, markGrantDead: (g) => dead.push(g) }))
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(dead).toEqual(['tok-A'])
+ h.stop()
+ })
+
+ it('only POSTs the grants getGrants currently returns (a dead grant is dropped)', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(grantDeps({ subscribe: em.subscribe, getGrants: () => [GRANTS[1]] }))
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok-B')
+ h.stop()
+ })
+
+ it('is inert when no host identity AND no grants', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(grantDeps({ subscribe: em.subscribe, getGrants: () => [] }))
+ em.emit(iev({ nodeId: 'a' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ h.stop()
+ })
+
+ it('honors the master + sub-gates in granted mode', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(grantDeps({ subscribe: em.subscribe, mobilePushEnabled: () => false }))
+ em.emit(iev({ nodeId: 'a' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ h.stop()
+ })
+
+ it('a paired host identity WINS: grants are never consulted (no double-push)', async () => {
+ const getGrants = vi.fn(() => GRANTS)
+ const em = makeEmitter()
+ // getHostIdentity defaults to the paired IDENTITY via baseDeps.
+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getGrants, hostLabel: () => 'niova' }))
+ em.emit(iev({ nodeId: 'a', title: 'A' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const body = bodyOf()
+ expect(body.hostDeviceId).toBe('host-device-1')
+ expect(fetchMock.mock.calls[0][1].headers.authorization).toBeUndefined()
+ expect(getGrants).not.toHaveBeenCalled()
+ h.stop()
+ })
+ })
+
it('stop() unsubscribes so later events are ignored', async () => {
const em = makeEmitter()
const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
@@ -835,6 +928,68 @@ describe('createLiveUpdatePush', () => {
})
})
+ describe('granted mode (SSH-possession push grants)', () => {
+ const GRANTS = [
+ { deviceId: 'dev-A', grant: 'tok-A' },
+ { deviceId: 'dev-B', grant: 'tok-B' }
+ ]
+
+ it('fans a state edge out per grant: Bearer auth + hostLabel, no host identity fields', async () => {
+ const { h, st } = wire({ getHostIdentity: () => null, getGrants: () => GRANTS, hostLabel: () => 'niova' })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ const calls = fetchMock.mock.calls
+ expect(calls.map((c) => c[1].headers.authorization)).toEqual(['Bearer tok-A', 'Bearer tok-B'])
+ for (const c of calls) {
+ expect(c[0]).toBe('https://api.nodeterm.dev/v1/push/live-update')
+ const body = JSON.parse(c[1].body)
+ expect(body.hostLabel).toBe('niova')
+ expect(body).not.toHaveProperty('hostDeviceId')
+ expect(body).not.toHaveProperty('hostPublicKeyB64')
+ expect(body.updates[0]).toMatchObject({ nodeId: 'a', event: 'start', state: 'working', edge: true })
+ }
+ h.stop()
+ })
+
+ it('marks a grant dead on a 401/403', async () => {
+ const dead: string[] = []
+ fetchMock.mockImplementation(async (_url: string, init: { headers: Record<string, string> }) => ({
+ status: init.headers.authorization === 'Bearer tok-B' ? 401 : 200
+ }))
+ const { h, st } = wire({
+ getHostIdentity: () => null,
+ getGrants: () => GRANTS,
+ hostLabel: () => 'niova',
+ markGrantDead: (g) => dead.push(g)
+ })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(dead).toEqual(['tok-B'])
+ h.stop()
+ })
+
+ it('a paired host identity WINS: grants are never consulted (no double-push)', async () => {
+ const getGrants = vi.fn(() => GRANTS)
+ const { h, st } = wire({ getGrants, hostLabel: () => 'niova' })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(liveBodyOf().hostDeviceId).toBe('host-device-1')
+ expect(fetchMock.mock.calls[0][1].headers.authorization).toBeUndefined()
+ expect(getGrants).not.toHaveBeenCalled()
+ h.stop()
+ })
+
+ it('is inert when no host identity AND no grants', async () => {
+ const { h, st } = wire({ getHostIdentity: () => null, getGrants: () => [] })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ h.stop()
+ })
+ })
+
it('stop() unsubscribes both seams so later events are ignored', async () => {
const { h, st, nw } = wire()
h.stop()
diff --git a/src/core/push-notify.ts b/src/core/push-notify.ts
index a2e74b021..a8090bad4 100644
--- a/src/core/push-notify.ts
+++ b/src/core/push-notify.ts
@@ -13,6 +13,7 @@
// constructs this (a documented, deliberate three-surfaces degrade; see src/server/index.ts).
import type { InboxEvent, NodeStateChange, NodeNowChange } from './agent-status-mirror'
+import type { PushGrant } from './push-grants'
const DEFAULT_API_BASE = 'https://api.nodeterm.dev'
// Batch actionable events landing close together into one POST (≤10 events/call per the contract).
@@ -59,11 +60,57 @@ export interface PushNotifyEvent {
ts: number
}
+/** Where a batch is sent: the relay host (legacy) or, in granted mode, a list of grants to
+ * fan the same body out over (once each, Bearer-authorized). */
+type SendTarget =
+ | { mode: 'host'; id: PushHostIdentity }
+ | { mode: 'grants'; grants: PushGrant[] }
+
+/** POST a JSON body with the shared timeout, swallowing network errors (no retry queue — the phone
+ * still polls the mirror). Returns the Response (so granted mode can read 401/403) or null on a
+ * thrown/aborted fetch. When `grant` is set, sends `Authorization: Bearer <grant>` instead of a
+ * host-identity body. */
+async function postJson(
+ fetchImpl: typeof fetch,
+ url: string,
+ body: unknown,
+ grant?: string
+): Promise<Response | null> {
+ const ctrl = new AbortController()
+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
+ try {
+ return await fetchImpl(url, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(grant ? { authorization: `Bearer ${grant}` } : {})
+ },
+ body: JSON.stringify(body),
+ signal: ctrl.signal
+ })
+ } catch {
+ return null
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
export interface PushNotifyDeps {
/** Subscribe to actionable inbox events. In production this is `onInboxActionable`. */
subscribe: (cb: (e: InboxEvent) => void) => () => void
/** The standing relay host identity, or null when none is configured/available. */
getHostIdentity: () => PushHostIdentity | null
+ /** Granted mode (SSH-possession push grants; spec: 2026-07-21-push-grants). When there is no
+ * usable relay host identity but grants exist, the batch is POSTed once PER grant with
+ * `Authorization: Bearer <grant>` (no host identity fields) — the Server Edition's path. Optional:
+ * the desktop leaves it unwired (it uses its relay identity; a host that is both paired AND
+ * granted would double-push the same phone). */
+ getGrants?: () => PushGrant[]
+ /** Mark a grant dead after a 401/403 (dropped until its file changes). Paired with `getGrants`. */
+ markGrantDead?: (grant: string) => void
+ /** `os.hostname()`, passed in to keep core pure — the granted-mode `hostLabel` (a granted send
+ * carries no host identity, so this is the only host label the backend sees). */
+ hostLabel?: () => string
/** The `settings.mobilePushEnabled` gate (default on) — the master switch. */
mobilePushEnabled: () => boolean
/** The `settings.mobilePushNeedsYou` sub-gate (default on): approval + question kinds. */
@@ -121,13 +168,18 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
return true
}
- /** Live identity IFF the service is enabled and there's a paired phone to reach; else null. */
- function liveIdentity(): PushHostIdentity | null {
+ /** Resolve where a batch goes: the relay host (byte-identical legacy behavior) when a paired host
+ * identity is available; else, in granted mode, the live grant list; else null (inert). The
+ * master + DNT/packaged gates apply to both modes; the paired-phone gate is host-mode only (a
+ * grant IS the phone's opt-in). */
+ function resolveTarget(): SendTarget | null {
if (!allowed()) return null
if (!deps.mobilePushEnabled()) return null
const id = deps.getHostIdentity()
- if (!id || !id.hasPairedPhone) return null
- return id
+ if (id && id.hasPairedPhone) return { mode: 'host', id }
+ const grants = deps.getGrants?.() ?? []
+ if (grants.length > 0) return { mode: 'grants', grants }
+ return null
}
function scheduleFlush(): void {
@@ -150,7 +202,7 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
function onEvent(e: InboxEvent): void {
// Cheap gate first: if the service is inert, don't buffer anything.
- if (!liveIdentity()) return
+ if (!resolveTarget()) return
// Per-kind selection: drop before the throttle window is consumed, so a declined kind
// never blocks a later accepted one on the same node.
if (!kindAllowed(e.kind)) return
@@ -182,9 +234,9 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
async function flush(): Promise<void> {
if (buffer.length === 0) return
- // Re-check the gate at flush: identity/setting can change during the batch window.
- const id = liveIdentity()
- if (!id) {
+ // Re-check the gate at flush: identity/grants/setting can change during the batch window.
+ const target = resolveTarget()
+ if (!target) {
buffer.length = 0
return
}
@@ -192,25 +244,28 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
// More than one call's worth accumulated in the window — send the rest right after.
if (buffer.length > 0) scheduleFlush()
- const body = {
- hostDeviceId: id.hostDeviceId,
- hostPublicKeyB64: id.hostPublicKeyB64,
- hostLabel: id.hostLabel,
- events
- }
- const ctrl = new AbortController()
- const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
- try {
- await fetchImpl(`${apiBase}/v1/push/notify`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body),
- signal: ctrl.signal
+ const url = `${apiBase}/v1/push/notify`
+ if (target.mode === 'host') {
+ // Legacy relay-identity body — byte-identical to the pre-grants shape.
+ await postJson(fetchImpl, url, {
+ hostDeviceId: target.id.hostDeviceId,
+ hostPublicKeyB64: target.id.hostPublicKeyB64,
+ hostLabel: target.id.hostLabel,
+ events
})
- } catch {
- // Drop on any network error — v1 has no retry queue (the phone still polls the mirror).
- } finally {
- clearTimeout(timer)
+ return
+ }
+ // Granted mode: one POST per live grant, Bearer-authorized, NO host identity fields —
+ // just `hostLabel` (os.hostname(), injected). A 401/403 marks that grant dead.
+ const label = deps.hostLabel?.()
+ for (const g of target.grants) {
+ const res = await postJson(
+ fetchImpl,
+ url,
+ { ...(label ? { hostLabel: label } : {}), events },
+ g.grant
+ )
+ if (res && (res.status === 401 || res.status === 403)) deps.markGrantDead?.(g.grant)
}
}
@@ -284,6 +339,14 @@ export interface LiveUpdateDeps {
subscribeNowChange: (cb: (c: NodeNowChange) => void) => () => void
/** The standing relay host identity, or null when none is configured/available. */
getHostIdentity: () => PushHostIdentity | null
+ /** Granted mode (SSH-possession push grants; spec: 2026-07-21-push-grants). See the identical
+ * field on `PushNotifyDeps`: no usable host identity + grants present ⇒ one POST per grant,
+ * Bearer-authorized, no host fields. Desktop leaves it unwired. */
+ getGrants?: () => PushGrant[]
+ /** Mark a grant dead after a 401/403 (dropped until its file changes). Paired with `getGrants`. */
+ markGrantDead?: (grant: string) => void
+ /** `os.hostname()`, passed in to keep core pure — the granted-mode `hostLabel`. */
+ hostLabel?: () => string
/** The `settings.mobilePushEnabled` master switch. */
mobilePushEnabled: () => boolean
/** The `settings.mobileLiveActivities` sub-gate (default on). */
@@ -332,13 +395,15 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
return true
}
- function liveIdentity(): PushHostIdentity | null {
+ function resolveTarget(): SendTarget | null {
if (!allowed()) return null
if (!deps.mobilePushEnabled()) return null
if (!deps.mobileLiveActivities()) return null
const id = deps.getHostIdentity()
- if (!id || !id.hasPairedPhone) return null
- return id
+ if (id && id.hasPairedPhone) return { mode: 'host', id }
+ const grants = deps.getGrants?.() ?? []
+ if (grants.length > 0) return { mode: 'grants', grants }
+ return null
}
function nodeTitleOf(nodeId: string): string | undefined {
@@ -359,7 +424,7 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
}
function onStateChange(c: NodeStateChange): void {
- if (!liveIdentity()) return
+ if (!resolveTarget()) return
const title = nodeTitleOf(c.nodeId)
// kind/options/multiSelect/pendingId ride only a needsYou edge (spec:
// interactive-push-live-activities addendum) — belt-and-braces gate on state so a working/done
@@ -426,7 +491,7 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
}
function onNowChange(c: NodeNowChange): void {
- if (!liveIdentity()) return
+ if (!resolveTarget()) return
const t = now()
const last = lastNowSentAt.get(c.nodeId) ?? -Infinity
if (t - last >= coalesceMs) {
@@ -443,33 +508,35 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
async function flush(): Promise<void> {
if (buffer.length === 0) return
- const id = liveIdentity()
- if (!id) {
+ const target = resolveTarget()
+ if (!target) {
buffer.length = 0
return
}
const updates = buffer.splice(0, MAX_UPDATES_PER_CALL)
if (buffer.length > 0) scheduleFlush()
- const body = {
- hostDeviceId: id.hostDeviceId,
- hostPublicKeyB64: id.hostPublicKeyB64,
- hostLabel: id.hostLabel,
- updates
- }
- const ctrl = new AbortController()
- const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
- try {
- await fetchImpl(`${apiBase}/v1/push/live-update`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body),
- signal: ctrl.signal
+ const url = `${apiBase}/v1/push/live-update`
+ if (target.mode === 'host') {
+ // Legacy relay-identity body — byte-identical to the pre-grants shape.
+ await postJson(fetchImpl, url, {
+ hostDeviceId: target.id.hostDeviceId,
+ hostPublicKeyB64: target.id.hostPublicKeyB64,
+ hostLabel: target.id.hostLabel,
+ updates
})
- } catch {
- // Drop on any network error — no retry queue (the phone still polls the mirror).
- } finally {
- clearTimeout(timer)
+ return
+ }
+ // Granted mode: one POST per live grant, Bearer-authorized, NO host identity fields.
+ const label = deps.hostLabel?.()
+ for (const g of target.grants) {
+ const res = await postJson(
+ fetchImpl,
+ url,
+ { ...(label ? { hostLabel: label } : {}), updates },
+ g.grant
+ )
+ if (res && (res.status === 401 || res.status === 403)) deps.markGrantDead?.(g.grant)
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 2cc89a363..63412eecd 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -744,6 +744,12 @@ app.whenReady().then(async () => {
// pinned) — that's the "standing relay host configured/paired" gate. The host public key
// (identity every paired phone pinned) + paired flag load async and refresh on a cheap interval,
// so a mid-run pairing / keyring-unlock is picked up without re-wiring; the getter is sync.
+ //
+ // Desktop stays RELAY-ONLY: it does NOT wire the SSH-possession push grants
+ // (spec: nodeterm-server/docs/specs/2026-07-21-push-grants.md, which the Server Edition uses in
+ // src/server/index.ts). A desktop that a phone both relay-PAIRED and dropped a grant on would
+ // push the same event to the same phone twice — once identity-signed, once grant-authorized. The
+ // grant path is the fallback for hosts with no relay identity; the desktop always has one.
let pushHostKeyB64: string | null = null
let pushHasPairedPhone = false
const refreshPushIdentity = async (): Promise<void> => {
diff --git a/src/server/index.ts b/src/server/index.ts
index e6d5e4887..bd42aedf7 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -28,8 +28,13 @@ import {
flush as flushAgentStatusMirror,
recordAgentEvent,
setMirrorSettingsProvider,
+ onInboxActionable,
+ onNodeStateChange,
+ onNodeNowChange,
type MirrorSettings
} from '../core/agent-status-mirror'
+import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
+import { createGrantsAccessor } from '../core/push-grants'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -225,15 +230,42 @@ export async function startServer(
)
// Sweep stale ~/.nodeterm/pending files on boot + hourly (orphans from killed sessions).
startPendingSweep(os.homedir())
- // Desktop → paired-phone APNs push (spec: apns-push) is DELIBERATELY not wired here. The push
- // service (`src/core/push-notify.ts`) fans actionable inbox events out to a host's relay-PAIRED
- // phones, keyed by the standing relay host's identity (public key + hostDeviceId) and the
- // pinned-device registry. The Server Edition has no standing relay host — no host keypair, no
- // approved-devices store, no host-token mint (all live in src/main/remote/) — so there is no
- // identity to sign the fan-out and no paired-phone list to reach. A phone talks to a server-
- // edition host over SSH and keeps polling the mirror. So the service would be permanently inert
- // here; we leave it unwired rather than construct a no-op. (Three-surfaces rule: documented
- // desktop-only.)
+ // Phone push via SSH-possession GRANTS (spec: nodeterm-server/docs/specs/2026-07-21-push-grants.md).
+ // The Server Edition has no standing relay host identity (no host keypair / approved-devices store /
+ // host-token mint — those live in src/main/remote/), so it cannot use the desktop's identity-signed
+ // fan-out. This contract SUPERSEDES the old "deliberately unwired — no relay identity" decision:
+ // a phone that reaches this host over SSH drops a signed, device-scoped grant at
+ // `~/.nodeterm/push-grants/<deviceId>.grant`, and we push to that phone under it (Authorization:
+ // Bearer <grant>, no host identity). Both senders run in GRANTED mode off one shared accessor (so a
+ // 401/403 dead-mark from either is seen by both). All the usual gates still apply
+ // (mobilePushEnabled / needsYou / done / mobileLiveActivities + DNT env guards). `isPackaged: true`
+ // — the server is a deployment artifact; dev safety comes for free since granted mode is inert until
+ // a phone actually drops a grant file. The DESKTOP keeps its relay-identity path and does NOT use
+ // grants in v1 (a host that is both paired AND granted would double-push the same phone) — see
+ // src/main/index.ts.
+ const pushGrants = createGrantsAccessor()
+ const grantedPushGates = {
+ getHostIdentity: () => null, // no relay identity here — granted mode only
+ getGrants: () => pushGrants.get(),
+ markGrantDead: (grant: string) => pushGrants.markDead(grant),
+ hostLabel: () => os.hostname(),
+ isPackaged: () => true,
+ getNodeTitle: (nodeId: string) => workspaceStore.getNodeTitle(nodeId)
+ }
+ createPushNotify({
+ subscribe: onInboxActionable,
+ ...grantedPushGates,
+ mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,
+ mobilePushNeedsYou: () => settingsStore.get().mobilePushNeedsYou !== false,
+ mobilePushDone: () => settingsStore.get().mobilePushDone !== false
+ })
+ createLiveUpdatePush({
+ subscribeStateChange: onNodeStateChange,
+ subscribeNowChange: onNodeNowChange,
+ ...grantedPushGates,
+ mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,
+ mobileLiveActivities: () => settingsStore.get().mobileLiveActivities !== false
+ })
// `installHooks: false` (tests) skips the merge into the user's real ~/.claude et al —
// the hook it would write points into `dataDir`, which a test then deletes.
if (config.installHooks !== false) {