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(push): desktop host-mode push proves the host key through a host-auth session
review60fb72826d5e
diff --git a/src/core/push-notify.test.ts b/src/core/push-notify.test.tsindex ec887c0df..6c5e39698 100644--- a/src/core/push-notify.test.ts+++ b/src/core/push-notify.test.ts@@ -3,13 +3,18 @@ import fs from 'fs'import os from 'os'import path from 'path'import type { NormalizedAgentEvent } from '@shared/agents/normalize'+import nacl from 'tweetnacl'import {createPushNotify,createLiveUpdatePush,type PushNotifyDeps,+ type PushNotifyHandle,type PushHostIdentity,- type LiveUpdateDeps+ type LiveUpdateDeps,+ type LiveUpdateHandle} from './push-notify'+import { popProverFor } from './relay/relay-pop'+import { createTestPopServer } from './relay/relay-pop.test-server'import {onInboxActionable,onNodeStateChange,@@ -1709,3 +1714,407 @@ describe('push payload ts is Unix MILLISECONDS (the mirror is the source)', () =}})})++// ---- host key proof-of-possession: the hostAuth session (relay-pop.ts) ----------------------+// A PoP-enabled backend latches a host once it has proven possession of its key, and from then on+// refuses an unproven host-mode send (403 pop_required). The host proves once through+// /v1/push/host-auth and attaches the session it gets (`hostAuth`) to notify and live-update.+// Without a prover nothing changes: no challenge, no field (every test above runs that way).+describe('host-mode push proves possession of the host key (hostAuth session)', () => {+ const MIN = 60_000+ const keys = nacl.box.keyPair()+ const PUB = Buffer.from(keys.publicKey).toString('base64')+ const PROVEN: PushHostIdentity = { ...IDENTITY, hostPublicKeyB64: PUB, prove: popProverFor(keys) }++ type Init = { body: string; signal?: AbortSignal; headers: Record<string, string> }+ type Answer = unknown | Promise<unknown>+ type Route = (init: Init) => Answer+ /** A real Response: the only kind a key-proof refusal check may read. */+ const json = (status: number, body: unknown): Response => new Response(JSON.stringify(body), { status })+ /** A bare answer with no clone()/json(): reading it throws, so a test using it pins "not read". */+ const bare = (status: number): { ok: boolean; status: number } => ({ ok: status >= 200 && status < 300, status })++ let pop: ReturnType<typeof createTestPopServer>+ let sessions: number+ const challengeOk: Route = (init) => json(200, pop.issue(JSON.parse(init.body).hostPublicKeyB64, 'push'))+ /** The backend's /v1/push/host-auth: verify with purpose push + subject hostDeviceId, then a new session. */+ const hostAuthOk: Route = (init) => {+ const b = JSON.parse(init.body)+ const proven = pop.verify({+ hostPublicKeyB64: b.hostPublicKeyB64,+ purpose: 'push',+ subject: IDENTITY.hostDeviceId,+ popChallenge: b.popChallenge,+ popProof: b.popProof+ })+ return proven ? json(200, { hostAuth: `HA-${++sessions}`, exp: 0 }) : json(403, { error: 'pop_invalid' })+ }++ function route(r: { challenge?: Route; hostAuth?: Route; notify?: Route; live?: Route } = {}): void {+ fetchMock = vi.fn(async (url: string, init: Init) => {+ if (url.endsWith('/v1/relay/challenge')) return (r.challenge ?? challengeOk)(init)+ if (url.endsWith('/v1/push/host-auth')) return (r.hostAuth ?? hostAuthOk)(init)+ if (url.endsWith('/v1/push/notify')) return (r.notify ?? (() => bare(200)))(init)+ if (url.endsWith('/v1/push/live-update')) return (r.live ?? (() => bare(200)))(init)+ throw new Error(`unexpected fetch ${url}`)+ })+ }+ const paths = (): string[] => fetchMock.mock.calls.map((c) => String(c[0]).replace('https://api.nodeterm.dev', ''))+ const callsTo = (suffix: string): Array<[string, Init]> =>+ fetchMock.mock.calls.filter((c) => String(c[0]).endsWith(suffix)) as Array<[string, Init]>+ const bodyTo = (suffix: string, i = -1): Record<string, unknown> => JSON.parse(callsTo(suffix).at(i)![1].body)++ beforeEach(() => {+ vi.useFakeTimers()+ clock = 0+ sessions = 0+ pop = createTestPopServer()+ route()+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ /** A notify service over PROVEN with a manual event source; `send` emits one event on a fresh node. */+ function notify(over: Partial<PushNotifyDeps> = {}): { h: PushNotifyHandle; send: () => Promise<void> } {+ const em = makeEmitter()+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getHostIdentity: () => PROVEN, ...over }))+ let n = 0+ return {+ h,+ async send() {+ em.emit(iev({ nodeId: `n${++n}`, title: `t${n}` }))+ await vi.advanceTimersByTimeAsync(2000)+ }+ }+ }++ it('first flush: challenge, host-auth, then the notify carrying the session', async () => {+ const { h, send } = notify()+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/relay/challenge')).toEqual({ hostPublicKeyB64: PUB, purpose: 'push' })+ const auth = bodyTo('/v1/push/host-auth')+ expect(Object.keys(auth).sort()).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'popChallenge', 'popProof'])+ expect(auth).toMatchObject({ hostDeviceId: 'host-device-1', hostPublicKeyB64: PUB })+ const body = bodyTo('/v1/push/notify')+ expect(body).toMatchObject({ hostDeviceId: 'host-device-1', hostPublicKeyB64: PUB, hostLabel: 'niova', hostAuth: 'HA-1' })+ expect(body.events).toHaveLength(1)+ h.stop()+ })++ it('a second flush inside 10 minutes reuses the session: ONE call, the notify', async () => {+ const { h, send } = notify()+ await send()+ fetchMock.mockClear()+ clock = 10 * MIN - 1+ await send()+ expect(paths()).toEqual(['/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')+ h.stop()+ })++ it('after 10 minutes on our own clock the flush proves again', async () => {+ const { h, send } = notify()+ await send()+ fetchMock.mockClear()+ clock = 10 * MIN+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')+ h.stop()+ })++ it.each(['pop_invalid', 'pop_required'])(+ 'a notify answered 403 %s clears the session: the next flush proves again',+ async (error) => {+ let n = 0+ route({ notify: () => (++n === 1 ? json(403, { error }) : bare(200)) })+ const { h, send } = notify()+ await send()+ fetchMock.mockClear()+ clock = 6000+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')+ h.stop()+ }+ )++ it('a 403 that is not a key-proof refusal (forbidden) keeps the session', async () => {+ let n = 0+ route({ notify: () => (++n === 1 ? json(403, { error: 'forbidden' }) : bare(200)) })+ const { h, send } = notify()+ await send()+ fetchMock.mockClear()+ clock = 6000+ await send()+ expect(paths()).toEqual(['/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')+ h.stop()+ })++ it.each<[string, { challenge?: Route; hostAuth?: Route }]>([+ ['the challenge answering 503', { challenge: () => bare(503) }],+ ['the challenge answering 500', { challenge: () => bare(500) }],+ ['the challenge answering 429', { challenge: () => bare(429) }],+ ['a challenge network error', { challenge: () => Promise.reject(new TypeError('fetch failed')) }],+ ['a malformed challenge 200', { challenge: () => json(200, { nope: true }) }],+ // A server key the proof cannot use: the all-zero key gives a degenerate shared secret.+ ['a challenge with an unusable server key', { challenge: () => json(200, { challenge: 'c.x', serverPublicKeyB64: 'A'.repeat(43) + '=' }) }],+ ['host-auth answering 503', { hostAuth: () => bare(503) }],+ ['host-auth answering 429', { hostAuth: () => bare(429) }],+ ['host-auth refusing the proof (403 pop_invalid)', { hostAuth: () => json(403, { error: 'pop_invalid' }) }],+ ['host-auth refusing the host (403 forbidden)', { hostAuth: () => json(403, { error: 'forbidden' }) }],+ ['a host-auth network error', { hostAuth: () => Promise.reject(new TypeError('fetch failed')) }],+ ['a malformed host-auth 200', { hostAuth: () => json(200, { nope: true }) }],+ // The backend reads an EMPTY hostAuth as present-but-invalid: it must never be sent.+ ['a host-auth 200 with an empty session', { hostAuth: () => json(200, { hostAuth: '', exp: 0 }) }]+ ])('%s drops the host notify for that batch (never an unproven send) and throws nothing', async (_label, r) => {+ route(r)+ const { h, send } = notify()+ await expect(send()).resolves.toBeUndefined()+ expect(callsTo('/v1/push/notify')).toHaveLength(0)+ h.stop()+ })++ it('a dropped host leg does not drop the granted leg of the same flush', async () => {+ route({ challenge: () => bare(503) })+ const { h, send } = notify({ getGrants: () => [{ deviceId: 'dev-A', grant: 'tok-A' }] })+ await send()+ const sent = callsTo('/v1/push/notify')+ expect(sent).toHaveLength(1)+ expect(sent[0][1].headers.authorization).toBe('Bearer tok-A')+ expect(JSON.parse(sent[0][1].body)).not.toHaveProperty('hostAuth')+ h.stop()+ })++ it.each([404, 405])('an old backend (challenge %i) gets the legacy notify: no hostAuth field', async (status) => {+ route({ challenge: () => bare(status) })+ const { h, send } = notify()+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])+ expect(Object.keys(bodyTo('/v1/push/notify'))).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'hostLabel', 'events'])+ h.stop()+ })++ it('host-auth answering 404 (no session route) sends the legacy notify', async () => {+ route({ hostAuth: () => bare(404) })+ const { h, send } = notify()+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/push/notify')).not.toHaveProperty('hostAuth')+ h.stop()+ })++ it('an old backend is remembered: the next flush inside 10 minutes asks no challenge', async () => {+ route({ challenge: () => bare(404) })+ const { h, send } = notify()+ await send()+ fetchMock.mockClear()+ clock = 6000+ await send()+ expect(paths()).toEqual(['/v1/push/notify'])+ expect(bodyTo('/v1/push/notify')).not.toHaveProperty('hostAuth')+ fetchMock.mockClear()+ clock = 10 * MIN+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])+ h.stop()+ })++ it('a legacy notify answered 403 forgets the old-backend verdict: the next flush asks again and proves', async () => {+ // A proxy answers the challenge 404 while the backend redeploys; the unproven notify lands on the+ // fresh backend, which requires a proof from this latched host. That batch is only dropped, and+ // the 403 is judged by its status alone (an unproven send's body is never read).+ let redeploying = true+ let n = 0+ route({+ challenge: (init) => (redeploying ? bare(404) : challengeOk(init)),+ notify: () => (++n === 1 ? bare(403) : bare(200))+ })+ const { h, send } = notify()+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/notify'])+ redeploying = false+ fetchMock.mockClear()+ clock = 6000+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')+ h.stop()+ })++ it('without a prover nothing changes: no challenge, no hostAuth (byte-identical legacy)', async () => {+ const { h, send } = notify({ getHostIdentity: () => ({ ...PROVEN, prove: undefined }) })+ await send()+ expect(paths()).toEqual(['/v1/push/notify'])+ expect(Object.keys(bodyTo('/v1/push/notify'))).toEqual(['hostDeviceId', 'hostPublicKeyB64', 'hostLabel', 'events'])+ h.stop()+ })++ it('a new host key (or device id) proves again instead of reusing the old session', async () => {+ let id: PushHostIdentity = PROVEN+ const { h, send } = notify({ getHostIdentity: () => id })+ await send()+ const rotated = nacl.box.keyPair()+ id = { ...IDENTITY, hostPublicKeyB64: Buffer.from(rotated.publicKey).toString('base64'), prove: popProverFor(rotated) }+ fetchMock.mockClear()+ clock = 6000+ await send()+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/notify'])+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-2')+ h.stop()+ })++ it('a challenge that never answers is aborted by the 8 s post timeout: that batch is dropped', async () => {+ route({+ challenge: (init) =>+ new Promise((_resolve, reject) => init.signal?.addEventListener('abort', () => reject(new Error('aborted'))))+ })+ const { h, send } = notify()+ await send() // the flush starts at 2 s and waits on the challenge+ await vi.advanceTimersByTimeAsync(7999)+ expect(callsTo('/v1/relay/challenge')[0][1].signal?.aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(1)+ expect(callsTo('/v1/relay/challenge')[0][1].signal?.aborted).toBe(true)+ await vi.advanceTimersByTimeAsync(0)+ expect(callsTo('/v1/push/host-auth')).toHaveLength(0)+ expect(callsTo('/v1/push/notify')).toHaveLength(0)+ h.stop()+ })++ it('ONE 8 s timer covers the challenge and the host-auth post (a slow challenge leaves it the rest)', async () => {+ route({+ challenge: (init) => new Promise((resolve) => setTimeout(() => resolve(challengeOk(init)), 5000)),+ hostAuth: (init) =>+ new Promise((_resolve, reject) => init.signal?.addEventListener('abort', () => reject(new Error('aborted'))))+ })+ const { h, send } = notify()+ await send()+ await vi.advanceTimersByTimeAsync(5000) // the challenge answers; host-auth now hangs+ expect(callsTo('/v1/push/host-auth')).toHaveLength(1)+ const signal = callsTo('/v1/push/host-auth')[0][1].signal+ expect(signal).toBe(callsTo('/v1/relay/challenge')[0][1].signal)+ await vi.advanceTimersByTimeAsync(2999)+ expect(signal?.aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(1) // 8 s after the challenge went out, not 8 s after host-auth+ expect(signal?.aborted).toBe(true)+ await vi.advanceTimersByTimeAsync(0)+ expect(callsTo('/v1/push/notify')).toHaveLength(0)+ h.stop()+ })++ it('failing proofs back off: a second failure in a row holds the next attempt for 5 s', async () => {+ // Each attempt is a /v1/relay/challenge, whose per-IP budget the relay host-token mint shares.+ let up = false+ route({ challenge: (init) => (up ? challengeOk(init) : bare(503)) })+ const { h, send } = notify()+ await send() // t=2 s: failure 1, the next batch may try again at once+ await send() // t=4 s: failure 2, nothing before t=9 s+ expect(callsTo('/v1/relay/challenge')).toHaveLength(2)+ up = true+ clock = 4000+ await send() // t=6 s: held — dropped without a request+ expect(callsTo('/v1/relay/challenge')).toHaveLength(2)+ expect(callsTo('/v1/push/notify')).toHaveLength(0)+ clock = 9000+ await send() // t=8 s on the timers, 9 s on the clock: tries, proves, sends+ expect(callsTo('/v1/relay/challenge')).toHaveLength(3)+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')+ h.stop()+ })++ it('overlapping flushes share ONE proof in flight', async () => {+ let answer: (() => void) | null = null+ route({+ challenge: (init) =>+ new Promise((resolve) => {+ answer = () => resolve(challengeOk(init))+ })+ })+ const em = makeEmitter()+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe, getHostIdentity: () => PROVEN }))+ for (let i = 0; i < 12; i++) em.emit(iev({ nodeId: `m${i}`, title: `t${i}` }))+ await vi.advanceTimersByTimeAsync(2000) // flush A (10 events) waits on the challenge+ await vi.advanceTimersByTimeAsync(2000) // flush B (2 events) starts while A still waits+ expect(callsTo('/v1/relay/challenge')).toHaveLength(1)+ answer!()+ await vi.advanceTimersByTimeAsync(0)+ expect(callsTo('/v1/relay/challenge')).toHaveLength(1)+ expect(callsTo('/v1/push/host-auth')).toHaveLength(1)+ expect(callsTo('/v1/push/notify').map((c) => JSON.parse(c[1].body).hostAuth)).toEqual(['HA-1', 'HA-1'])+ h.stop()+ })++ describe('live-update', () => {+ function live(): { h: LiveUpdateHandle; edge: (nodeId: string) => Promise<void> } {+ const st = emitter<NodeStateChange>()+ const h = createLiveUpdatePush({+ subscribeStateChange: st.subscribe,+ subscribeNowChange: () => () => {},+ getHostIdentity: () => PROVEN,+ mobilePushEnabled: () => true,+ mobileLiveActivities: () => true,+ isPackaged: () => true,+ env: {},+ fetchImpl: fetchMock as unknown as typeof fetch,+ now: () => clock,+ batchWindowMs: 1000+ })+ return {+ h,+ async edge(nodeId) {+ st.emit({ nodeId, event: 'start', state: 'working', ts: clock })+ await vi.advanceTimersByTimeAsync(1000)+ }+ }+ }++ it('proves once and carries the cached session on every post', async () => {+ const { h, edge } = live()+ await edge('a')+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/live-update'])+ expect(bodyTo('/v1/push/live-update')).toMatchObject({ hostPublicKeyB64: PUB, hostAuth: 'HA-1' })+ fetchMock.mockClear()+ clock = 9 * MIN+ await edge('b')+ expect(paths()).toEqual(['/v1/push/live-update'])+ expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-1')+ h.stop()+ })++ it('a live-update answered 403 pop_invalid clears the session; a transient challenge drops the batch', async () => {+ let n = 0+ let challengeUp = true+ route({+ challenge: (init) => (challengeUp ? challengeOk(init) : bare(503)),+ live: () => (++n === 1 ? json(403, { error: 'pop_invalid' }) : bare(200))+ })+ const { h, edge } = live()+ await edge('a')+ challengeUp = false+ fetchMock.mockClear()+ await edge('b') // must prove again, cannot, and so sends nothing+ expect(paths()).toEqual(['/v1/relay/challenge'])+ challengeUp = true+ fetchMock.mockClear()+ await edge('c')+ expect(paths()).toEqual(['/v1/relay/challenge', '/v1/push/host-auth', '/v1/push/live-update'])+ expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-2')+ h.stop()+ })++ it('its session is its own: notify proving does not stand in for live-update', async () => {+ const n = notify()+ const l = live()+ await n.send()+ await l.edge('a')+ expect(callsTo('/v1/push/host-auth')).toHaveLength(2)+ expect(bodyTo('/v1/push/notify').hostAuth).toBe('HA-1')+ expect(bodyTo('/v1/push/live-update').hostAuth).toBe('HA-2')+ n.h.stop()+ l.h.stop()+ })+ })+})diff --git a/src/core/push-notify.ts b/src/core/push-notify.tsindex 7c27016e6..63d661245 100644--- a/src/core/push-notify.ts+++ b/src/core/push-notify.ts@@ -14,6 +14,7 @@import type { InboxEvent, NodeStateChange, NodeNowChange } from './agent-status-mirror'import type { PushGrant } from './push-grants'+import { fetchPopChallenge, popRefusalOf, type PopProver } from './relay/relay-pop'const DEFAULT_API_BASE = 'https://api.nodeterm.dev'// Batch actionable events landing close together into one POST (≤10 events/call per the contract).@@ -41,6 +42,9 @@ export interface PushHostIdentity {hostPublicKeyB64: stringhostLabel: stringhasPairedPhone: boolean+ /** Proves possession of the host key for a PoP-enabled backend (relay-pop.ts). The secret stays in+ * the prover's closure; absent ⇒ host-mode push stays legacy. */+ prove?: PopProver}/** The per-event body the backend `/v1/push/notify` expects (a subset of InboxEvent). */@@ -209,6 +213,171 @@ async function postJson(}}+// ---- Host-mode proof of possession: the hostAuth session ------------------------------------+// A PoP-enabled backend latches a host the first time it proves it holds its key, and from then on+// refuses an unproven host-mode notify or live-update (403 pop_required). The host proves once —+// `/v1/relay/challenge` (purpose `push`) then `POST /v1/push/host-auth` — and attaches the session it+// gets (`hostAuth`) to every host-mode post until it re-proves. Push never stops anything, so nothing+// here is terminal: a batch that cannot be proven is DROPPED, exactly like a network error, because an+// unproven send from a latched host is refused anyway. Only a challenge answered 404/405 means "this+// backend predates the proof" (relay-pop.ts), and only then does the post go out legacy.++// The server's session TTL is 15 min; re-prove on OUR clock, well inside it, so a skewed clock or a+// long batch window never presents an expired session.+const HOST_AUTH_REPROVE_MS = 10 * 60_000+// Earliest next proving attempt after the Nth failure in a row (the last entry repeats). The first+// retry is free — a blip costs one batch, not the next minute — but a backend that keeps refusing+// (no live pairing, a proof it never accepts, its own 429) is asked once a minute, not once a batch:+// the live-update stream flushes up to once a second, and every attempt spends the per-IP+// /v1/relay/challenge budget the relay host-token mint needs too.+const HOST_AUTH_RETRY_MS = [0, 5_000, 15_000, 60_000]++export interface HostAuthCache {+ /** The session token to attach, undefined for legacy (no prover, or an old backend), or 'drop'+ * when a failure means this batch must not go out unproven. Never '' — the backend reads an+ * empty `hostAuth` as present-but-invalid. */+ get(identity: PushHostIdentity): Promise<string | undefined | 'drop'>+ /** Forget the session (or the old-backend verdict): the next batch proves again. */+ invalidate(): void+}++/**+ * One hostAuth session per sender (notify and live-update each own one: they are independent streams+ * and each re-proves at most every 10 minutes). The "old backend" verdict is cached the same way, so+ * a backend without the routes costs one challenge per 10 minutes rather than one per batch. The+ * challenge, the host-auth post and its body read share ONE `FETCH_TIMEOUT_MS` timer: nothing else+ * bounds a stalled challenge, and the batch waits on it. Concurrent `get`s share the proof in flight.+ */+export function createHostAuthCache(d: { apiBase: string; fetchImpl: typeof fetch; now: () => number }): HostAuthCache {+ // token undefined = the backend predates the proof (challenge 404/405, or no host-auth route).+ let cached: { key: string; token: string | undefined; at: number } | null = null+ let inflight: { key: string; result: Promise<string | undefined | 'drop'> } | null = null+ let failures = 0+ let retryAt = 0++ async function establish(id: PushHostIdentity, prove: PopProver): Promise<string | undefined | 'drop'> {+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ try {+ const ch = await fetchPopChallenge({+ apiBase: d.apiBase,+ hostPublicKeyB64: id.hostPublicKeyB64,+ purpose: 'push',+ fetch: d.fetchImpl,+ signal: ctrl.signal+ })+ // Never unproven after a transient failure: a latched host's unproven send is refused.+ if (!ch.ok) return ch.unsupported ? undefined : 'drop'+ let popProof: string+ try {+ popProof = prove({+ challenge: ch.challenge,+ serverPublicKeyB64: ch.serverPublicKeyB64,+ purpose: 'push',+ subject: id.hostDeviceId+ })+ } catch {+ return 'drop' // a server key the proof cannot use (malformed, or low-order)+ }+ let res: Response+ try {+ res = await d.fetchImpl(`${d.apiBase}/v1/push/host-auth`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ hostDeviceId: id.hostDeviceId,+ hostPublicKeyB64: id.hostPublicKeyB64,+ popChallenge: ch.challenge,+ popProof+ }),+ signal: ctrl.signal+ })+ } catch {+ return 'drop'+ }+ if (res.status === 404) return undefined // a backend with the challenge but no session route+ if (!res.ok) return 'drop' // 403 forbidden (no live pairing) / pop_invalid, 429, 5xx+ const json = (await res.json().catch(() => null)) as { hostAuth?: unknown } | null+ if (!json || typeof json.hostAuth !== 'string' || !json.hostAuth) return 'drop'+ return json.hostAuth+ } finally {+ clearTimeout(timer)+ }+ }++ return {+ invalidate() {+ cached = null+ },+ async get(id) {+ if (!id.prove) return undefined+ const key = `${id.hostPublicKeyB64}\n${id.hostDeviceId}`+ if (cached && cached.key === key && d.now() - cached.at < HOST_AUTH_REPROVE_MS) return cached.token+ if (inflight && inflight.key === key) return inflight.result+ if (d.now() < retryAt) return 'drop'+ const result = establish(id, id.prove)+ inflight = { key, result }+ try {+ const r = await result+ if (r === 'drop') {+ failures+++ retryAt = d.now() + HOST_AUTH_RETRY_MS[Math.min(failures, HOST_AUTH_RETRY_MS.length) - 1]+ } else {+ failures = 0+ retryAt = 0+ cached = { key, token: r, at: d.now() }+ }+ return r+ } finally {+ if (inflight?.result === result) inflight = null+ }+ }+ }+}++/** Read a JSON body within `ms` (null past it, or on a body that is not JSON). A response body can+ * stall after its headers, and `postJson`'s timer stops at the headers. */+async function jsonWithin(res: Response, ms: number): Promise<unknown> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ res.json().catch(() => null),+ new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), ms)+ })+ ])+ } finally {+ clearTimeout(timer)+ }+}++/**+ * The host-mode post, shared by notify and live-update: attach the session when there is one (the+ * field only when it is a non-empty string), and forget it when the backend refuses it. The refusal+ * is read ONLY from a 403 to a post that carried a session: an unproven post's body is never+ * read — a 403 there (a latched host behind an old-backend verdict, or no live pairing) just+ * forgets the verdict, so the next batch asks for a challenge again.+ */+async function postHostMode(+ fetchImpl: typeof fetch,+ cache: HostAuthCache,+ url: string,+ host: PushHostIdentity,+ payload: Record<string, unknown>+): Promise<void> {+ const hostAuth = await cache.get(host)+ if (hostAuth === 'drop') return+ const res = await postJson(fetchImpl, url, {+ hostDeviceId: host.hostDeviceId,+ hostPublicKeyB64: host.hostPublicKeyB64,+ hostLabel: host.hostLabel,+ ...payload,+ ...(hostAuth ? { hostAuth } : {})+ })+ if (!res || res.status !== 403 || !host.prove) return+ if (!hostAuth || popRefusalOf(403, await jsonWithin(res, FETCH_TIMEOUT_MS))) cache.invalidate()+}+export interface PushNotifyDeps {/** Subscribe to actionable inbox events. In production this is `onInboxActionable`. */subscribe: (cb: (e: InboxEvent) => void) => () => void@@ -293,6 +462,9 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {const batchWindowMs = deps.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MSconst throttleMs = deps.throttleMs ?? DEFAULT_THROTTLE_MS+ // This sender's own hostAuth session (the host-mode proof of possession, above).+ const hostAuth = createHostAuthCache({ apiBase, fetchImpl, now })+const buffer: PushNotifyEvent[] = []// Presence-aware hold queue: while the user is present, accepted alerts wait here (with the mirror// event id, so the away-flush can drop any that got resolved meanwhile). Bounded, oldest-dropped.@@ -406,13 +578,9 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {const url = `${apiBase}/v1/push/notify`if (target.host) {- // Relay-identity body — byte-identical to the pre-grants shape.- await postJson(fetchImpl, url, {- hostDeviceId: target.host.hostDeviceId,- hostPublicKeyB64: target.host.hostPublicKeyB64,- hostLabel: target.host.hostLabel,- events- })+ // Relay-identity body — byte-identical to the pre-grants shape when no prover is set, and+ // carrying `hostAuth` once the host has proven possession of its key.+ await postHostMode(fetchImpl, hostAuth, url, target.host, { events })}// …and the grants, in the SAME flush (see resolveSendTarget: a paired phone must not silence// the SSH-only ones). PER HOST: each event goes only under the grants swept from the host its@@ -574,6 +742,9 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {const batchWindowMs = deps.batchWindowMs ?? DEFAULT_LIVE_BATCH_WINDOW_MSconst coalesceMs = deps.coalesceMs ?? DEFAULT_LIVE_COALESCE_MS+ // Its own hostAuth session, independent of notify's (each re-proves at most every 10 minutes).+ const hostAuth = createHostAuthCache({ apiBase, fetchImpl, now })+const buffer: LiveUpdateItem[] = []// Per-node coalescing of activity/context ticks.const lastNowSentAt = new Map<string, number>()@@ -752,13 +923,9 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {const url = `${apiBase}/v1/push/live-update`if (target.host) {- // Relay-identity body — byte-identical to the pre-grants shape.- await postJson(fetchImpl, url, {- hostDeviceId: target.host.hostDeviceId,- hostPublicKeyB64: target.host.hostPublicKeyB64,- hostLabel: target.host.hostLabel,- updates- })+ // Relay-identity body — byte-identical to the pre-grants shape when no prover is set, and+ // carrying `hostAuth` once the host has proven possession of its key.+ await postHostMode(fetchImpl, hostAuth, url, target.host, { updates })}// …and the grants, in the SAME flush (see resolveSendTarget), PER HOST exactly like notify:// an update goes only under the grants swept from its node's host. One POST per live grant,diff --git a/src/main/index.ts b/src/main/index.tsindex de78adbea..75babe97a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -360,7 +360,8 @@ import { initStandingHost } from './remote/standing-host'import { initRelayHost } from './remote/relay-host-service'import { PIN_ROLES, phonePins, retireLegacyPinFile } from './remote/approved-devices'import { revokeAllPhones, revokePeerKey } from './remote/peer-revoke'-import { publicKeyToB64 } from './remote/e2ee'+import { publicKeyToB64, type KeyPair } from './remote/e2ee'+import { popProverFor } from '../core/relay/relay-pop'import { connectRelayClient, type RelayClientSession } from './remote/relay-client'import { relayPtyDataKey } from '../shared/relay-pty-channel'import { decodeOffer } from './remote/pairing'@@ -2336,6 +2337,9 @@ app.whenReady().then(async () => {remoteGrants.markDead(grant)}let pushHostKeyB64: string | null = null+ // The same key pair, kept so push can prove possession of it (relay-pop.ts). Only a prover closed+ // over it ever leaves this scope (`popProverFor`); the secret key itself is never passed on.+ let pushHostKeys: KeyPair | null = nulllet pushHasPairedPhone = falseconst refreshPushIdentity = async (): Promise<void> => {try {@@ -2352,10 +2356,13 @@ app.whenReady().then(async () => {// a Keychain ACL prompt even though there is nobody to notify.if (!pushHasPairedPhone) {pushHostKeyB64 = null+ pushHostKeys = nullreturn}try {- pushHostKeyB64 = publicKeyToB64((await loadOrCreateKeyPair()).publicKey)+ const kp = await loadOrCreateKeyPair()+ pushHostKeys = kp+ pushHostKeyB64 = publicKeyToB64(kp.publicKey)} catch {// Keyring locked / transient read error: keep the last-known key (never clobber identity).}@@ -2414,7 +2421,9 @@ app.whenReady().then(async () => {hostDeviceId: getDeviceId(),hostPublicKeyB64: pushHostKeyB64,hostLabel: hostname(),- hasPairedPhone: pushHasPairedPhone+ hasPairedPhone: pushHasPairedPhone,+ // Host-mode push proves possession of the host key through a hostAuth session.+ prove: pushHostKeys ? popProverFor(pushHostKeys) : undefined}: null,// Granted-mode fallback (unpaired / no relay identity → push to SSH-dropped grants; see the@@ -2453,7 +2462,9 @@ app.whenReady().then(async () => {hostDeviceId: getDeviceId(),hostPublicKeyB64: pushHostKeyB64,hostLabel: hostname(),- hasPairedPhone: pushHasPairedPhone+ hasPairedPhone: pushHasPairedPhone,+ // Host-mode push proves possession of the host key through a hostAuth session.+ prove: pushHostKeys ? popProverFor(pushHostKeys) : undefined}: null,getGrants: allPushGrants,diff --git a/src/main/push-prove-wiring.test.ts b/src/main/push-prove-wiring.test.tsnew file mode 100644index 000000000..704858e24--- /dev/null+++ b/src/main/push-prove-wiring.test.ts@@ -0,0 +1,34 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * SOURCE-LEVEL pins for the desktop's host-mode push proof (relay-pop.ts, the hostAuth session in+ * core/push-notify.ts). `PushHostIdentity.prove` is OPTIONAL, so a `getHostIdentity` literal that+ * leaves it out is well-typed and passes every unit test — and ships a desktop whose pushes stop+ * the day the backend latches its key. Both senders build their own identity literal, so each is+ * pinned. The behaviour is proven against real code in `core/push-notify.test.ts`.+ */+const main = readFileSync(new URL('./index.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++/** The argument block of the first `name({` call: up to the line that closes it at 2 spaces. */+function callBlock(name: string): string {+ const at = main.indexOf(` ${name}({`)+ expect(at).toBeGreaterThan(-1)+ return main.slice(at, main.indexOf('\n })\n', at))+}++describe('desktop push proves possession of the host key', () => {+ it.each(['createPushNotify', 'createLiveUpdatePush'])('%s hands a prover over the host key pair', (name) => {+ const block = callBlock(name)+ const identity = block.slice(block.indexOf('getHostIdentity:'), block.indexOf(': null,'))+ expect(identity).toContain('hostPublicKeyB64: pushHostKeyB64,')+ expect(identity).toContain('prove: pushHostKeys ? popProverFor(pushHostKeys) : undefined')+ })++ it('keeps the key pair beside its public key, and clears both together', () => {+ const at = main.indexOf('const refreshPushIdentity = async')+ const refresh = main.slice(at, main.indexOf('void refreshPushIdentity()', at))+ expect(refresh).toMatch(/pushHostKeyB64 = null\n\s+pushHostKeys = null/)+ expect(refresh).toMatch(/const kp = await loadOrCreateKeyPair\(\)\n\s+pushHostKeys = kp\n\s+pushHostKeyB64 = publicKeyToB64\(kp\.publicKey\)/)+ })+})