Skip to content

The agent that grows with you

docs: define Desktop gateway ownership and private ticket boundary

Tekniumf0ff6c570109
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index cf887ea54d1..12f3af26163 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -1,5 +1,6 @@
-import { test, expect } from 'vitest'
-import { ensureLocalGateway, createLocalGatewayDials } from './local-gateway'
+import { expect, test } from 'vitest'
+
+import { createLocalGatewayDials, ensureLocalGateway } from './local-gateway'
test('ensure consumes structured readiness without acquiring a child owner', async () => {
const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index e1d741f9785..bf8cc1a9b3d 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -1,5 +1,6 @@
import { spawn } from 'node:child_process'
import crypto from 'node:crypto'
+
import { hiddenWindowsChildOptions } from './windows-child-options'
export function runGatewayEnsure(backend, cwd: string, home: string): Promise<{ code: number; stdout: string }> {
@@ -8,12 +9,15 @@ export function runGatewayEnsure(backend, cwd: string, home: string): Promise<{
let stdout = ''
// Only the bounded ensure client is ours. Never retain/kill its detached owner.
const timer = setTimeout(() => child.kill(), 40_000)
- child.stdout.on('data', data => { stdout += data.toString(); if (stdout.length > 65536) child.kill() })
+ child.stdout.on('data', data => { stdout += data.toString();
+
+ if (stdout.length > 65536) {child.kill()} })
child.stderr.resume()
child.on('error', () => { clearTimeout(timer); reject(new Error('Could not run hermes gateway ensure')) })
child.on('close', code => { clearTimeout(timer); resolve({ code: code ?? 7, stdout }) })
})
}
+
import fs from 'node:fs/promises'
import net from 'node:net'
import path from 'node:path'
@@ -31,39 +35,50 @@ export interface GatewayEndpoint {
export async function ensureLocalGateway(run: () => Promise<{ code: number; stdout: string }>) {
const result = await run()
const payload = JSON.parse(result.stdout)
+
if (result.code !== 0 || payload.state !== 'ready') {
throw new Error(`Gateway ${payload.state || 'inaccessible'} (${payload.reason_code || 'ensure_failed'}). Use hermes gateway status for recovery.`)
}
+
const endpoint: GatewayEndpoint = payload.endpoint
const origin = new URL(endpoint.api_origin)
+
if (!['http:', 'https:'].includes(origin.protocol) || !['127.0.0.1', '[::1]'].includes(origin.hostname)
|| origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash
|| !origin.port || endpoint.runtime_protocol !== 1 || !endpoint.instance_id || !endpoint.profile_id
|| !endpoint.capabilities.includes('session-authority-v1')) {
throw new Error('Invalid local gateway endpoint')
}
+
return { baseUrl: endpoint.api_origin, wsUrl: `${endpoint.api_origin.replace(/^http/, 'ws')}/api/ws?native_dial=unminted`, mode: 'local', source: 'local', authMode: 'native', token: '', gatewayEndpoint: endpoint }
}
-// Credentials never enter public descriptors, logs, renderer URLs or persisted state.
+// A one-use ticket crosses private IPC, then leaves the URL before dialing.
+// Public descriptors and persisted connection state never contain credentials.
export function createLocalGatewayDials() {
const pending = new Map<string, { ticket: string; webContentsId: number; expires: number }>()
+
return {
prepare(origin: string, ticket: string, webContentsId: number) {
- for (const [key, value] of pending) if (value.expires <= Date.now()) pending.delete(key)
- if (pending.size >= 100) throw new Error('Too many pending gateway dials')
+ for (const [key, value] of pending) {if (value.expires <= Date.now()) {pending.delete(key)}}
+
+ if (pending.size >= 100) {throw new Error('Too many pending gateway dials')}
const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${crypto.randomUUID()}`
pending.set(url, { ticket, webContentsId, expires: Date.now() + 25_000 })
+
return `${url}&ticket=${encodeURIComponent(ticket)}`
},
headers(details: { url: string; webContentsId?: number; resourceType: string; requestHeaders?: Record<string, string> }) {
const grant = pending.get(details.url)
- if (!grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') return null
+
+ if (!grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') {return null}
pending.delete(details.url)
- if (grant.expires <= Date.now()) return null
+
+ if (grant.expires <= Date.now()) {return null}
const headers = { ...details.requestHeaders }
- for (const key of Object.keys(headers)) if (['origin', 'sec-websocket-protocol'].includes(key.toLowerCase())) delete headers[key]
- headers['Sec-WebSocket-Protocol'] = details.requestHeaders?.['Sec-WebSocket-Protocol'] || ''
+
+ for (const key of Object.keys(headers)) {if (key.toLowerCase() === 'origin') {delete headers[key]}}
+
return headers
}
}
@@ -72,28 +87,33 @@ export function createLocalGatewayDials() {
async function privateNode(file: string, kind: 'directory' | 'socket' | 'file') {
const node = await fs.lstat(file)
const valid = { directory: node.isDirectory(), socket: node.isSocket(), file: node.isFile() }[kind]
- if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) throw new Error('Unsafe gateway control path')
+
+ if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) {throw new Error('Unsafe gateway control path')}
}
export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint): Promise<string> {
// Named-pipe bootstrap needs the same server-identity validation as Python's
// native bootstrap. Refuse rather than silently use an unauthenticated pipe.
- if (process.platform === 'win32') throw new Error('Native gateway bootstrap on Windows requires the validated named-pipe client')
+ if (process.platform === 'win32') {throw new Error('Native gateway bootstrap on Windows requires the validated named-pipe client')}
const home = endpoint.profile_id
- if (await fs.realpath(home) !== home) throw new Error('Noncanonical gateway profile')
+
+ if (await fs.realpath(home) !== home) {throw new Error('Noncanonical gateway profile')}
await privateNode(home, 'directory')
let socketPath = path.join(home, 'gateway.sock')
+
try { await privateNode(socketPath, 'socket') } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {throw error}
const pointer = path.join(home, 'gateway.sock.path')
await privateNode(pointer, 'file')
const target = (await fs.readFile(pointer, 'utf8')).trim()
const hash = crypto.createHash('sha256').update(home).digest('hex').slice(0, 16)
- if (!path.isAbsolute(target) || path.basename(path.dirname(target)) !== `hermes-gw-${hash}` || path.basename(target) !== 'control.sock') throw new Error('Invalid gateway control pointer')
+
+ if (!path.isAbsolute(target) || path.basename(path.dirname(target)) !== `hermes-gw-${hash}` || path.basename(target) !== 'control.sock') {throw new Error('Invalid gateway control pointer')}
await privateNode(path.dirname(target), 'directory')
await privateNode(target, 'socket')
socketPath = target
}
+
return new Promise((resolve, reject) => {
const socket = net.createConnection(socketPath)
let buffer = ''
@@ -103,14 +123,19 @@ export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint): Promise
socket.on('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose: 'interactive' } }) + '\n'))
socket.on('data', chunk => {
buffer += chunk.toString()
- if (buffer.length > 65536) return socket.destroy(new Error('Oversized gateway ticket response'))
- if (!buffer.includes('\n')) return
+
+ if (buffer.length > 65536) {return socket.destroy(new Error('Oversized gateway ticket response'))}
+
+ if (!buffer.includes('\n')) {return}
+
try {
const reply = JSON.parse(buffer.split('\n')[0])
const grant = reply.result
- if (!reply.ok || reply.protocol !== 1 || reply.id !== 1 || grant?.instance_id !== endpoint.instance_id || grant?.profile_id !== home || typeof grant?.ticket !== 'string') throw new Error('Invalid gateway ticket')
+
+ if (!reply.ok || reply.protocol !== 1 || reply.id !== 1 || grant?.instance_id !== endpoint.instance_id || grant?.profile_id !== home || typeof grant?.ticket !== 'string') {throw new Error('Invalid gateway ticket')}
resolve(grant.ticket)
} catch { reject(new Error('Invalid gateway ticket response')) }
+
socket.destroy()
})
})
diff --git a/apps/desktop/src/AGENTS.md b/apps/desktop/src/AGENTS.md
index 523c13c0b76..57324fa435f 100644
--- a/apps/desktop/src/AGENTS.md
+++ b/apps/desktop/src/AGENTS.md
@@ -3,25 +3,24 @@
Applies on top of `apps/desktop/AGENTS.md` (the judgment guide) and the root `AGENTS.md`.
Root TypeScript style rules apply.
-## The desktop is its own chat surface on a `hermes serve` backend
+## Desktop local execution belongs to the canonical gateway
-Electron + React + nanostores (`@assistant-ui/react`) talking to a `tui_gateway` backend over
-JSON-RPC (`requestGateway(method, params)`); transport lives in the framework-agnostic `apps/shared`
-(`@hermes/shared`: `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard also consumes.
-The desktop has **no build/runtime dependency on the dashboard frontend**: it spawns a headless
-`hermes serve` (`headless_backend=True` → `cmd_dashboard` skips `_build_web_ui` and exports
-`HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists).
-`dashboard` and `serve` share `cmd_dashboard`/`start_server` but neither launches the other. It does
-NOT embed `hermes --tui` — own composer, transcript, slash pipeline.
+Electron + React + nanostores (`@assistant-ui/react`) talks JSON-RPC over the existing
+`@hermes/shared` client. Normal local primary and pooled launches invoke
+`hermes gateway ensure --json`, consume its credential-free endpoint, and authenticate
+WebSockets with fresh private control tickets. The app never acquires the gateway PID as
+an owned child. Closing, switching or evicting a Desktop connection disconnects the viewer;
+only explicit gateway lifecycle commands stop the owner.
-**One backward-compat fallback:** `serve` is newer, so the spawn (`electron/backend-command.ts` +
-`backendSupportsServe()` in `electron/main.ts`) checks whether the resolved runtime registers `serve`
-and ONLY when it does not (older managed install / PATH `hermes` not yet updated) rewrites argv to
-legacy `dashboard --no-open`. Without it a new app against an un-upgraded runtime crashes on an
-unknown subcommand and bricks every mid-upgrade user. Keep it narrow and tested.
+Native tickets cross the private preload IPC transiently, are removed from the URL before
+WebSocket construction, and are offered as subprotocols. Electron removes Origin only for
+an unexpired one-use dial bound to the requesting window. No public dashboard token is
+scraped or added to the public connection descriptor. SSH/URL intent retains its existing
+remote resolution and exposure lifecycle; a remote failure must never start a local owner.
-Lifecycle: `serve` dies with the app by design; the messaging gateway survives it (spawned detached
-via `/api/gateway/*`). Never re-parent the gateway under the backend — `gateway/AGENTS.md`.
+This migration requires the runtime's canonical GUI creation policy and a private HTTP
+API credential path. Do not bypass missing runtime capabilities by relabeling GUI sessions
+as CLI, dropping launch options, or falling back to an independent local serve owner.
## Slash commands: curated client-side, dispatched to the backend
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 55cc1763563..f1ce0c7b754 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -35,10 +35,13 @@ export class HermesGateway extends JsonRpcGatewayClient {
requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS,
socketFactory: url => {
const parsed = new URL(url)
- if (!parsed.searchParams.has('native_dial')) return new WebSocket(url)
+
+ if (!parsed.searchParams.has('native_dial')) {return new WebSocket(url)}
const ticket = parsed.searchParams.get('ticket')
- if (!ticket) throw new Error('Native gateway requires a fresh private ticket')
+
+ if (!ticket) {throw new Error('Native gateway requires a fresh private ticket')}
parsed.searchParams.delete('ticket')
+
return new WebSocket(parsed.toString(), ['hermes-gateway-v1', `hermes-gateway-ticket.${ticket}`])
}
})