Skip to content

The agent that grows with you

fix: bootstrap Windows desktop tickets through validated Python pipes

Tekniumf8ba25a99b0e
diff --git a/apps/desktop/electron/local-gateway-python.test.ts b/apps/desktop/electron/local-gateway-python.test.ts
new file mode 100644
index 00000000000..84539c298d4
--- /dev/null
+++ b/apps/desktop/electron/local-gateway-python.test.ts
@@ -0,0 +1,48 @@
+import fs from 'node:fs/promises'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+
+import { expect, test } from 'vitest'
+
+import { mintGatewayTicketWithPython } from './local-gateway-python'
+
+// This exercises the real helper process and protocol on this host. The native
+// probe separately exercises Windows SID checks and HTTP/WS admission.
+test.skipIf(process.platform === 'win32')('Python ticket bridge pins profile, owner, protocol and purpose', async () => {
+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'gw-bridge-')))
+ const root = path.resolve('../..')
+ const python = process.env.HERMES_TEST_PYTHON || path.join(root, '.venv/bin/python')
+ const endpoint = { profile_id: home, instance_id: 'owner', runtime_protocol: 1 }
+ const requests: any[] = []
+ let override = {}
+
+ const server = net.createServer(socket => socket.once('data', chunk => {
+ const request = JSON.parse(chunk.toString())
+ requests.push(request)
+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { ...endpoint, ticket: 'private-grant', ...override } }) + '\n')
+ }))
+
+ await new Promise<void>(resolve => server.listen(path.join(home, 'gateway.sock'), resolve))
+ await fs.chmod(path.join(home, 'gateway.sock'), 0o600)
+ const backend = { command: python, env: { PYTHONPATH: root, HERMES_HOME: '/must-not-win' } }
+ const cwd = path.join(home, 'project')
+ await fs.mkdir(path.join(cwd, 'hermes_cli'), { recursive: true })
+ await fs.writeFile(path.join(cwd, 'hermes_cli', '__init__.py'), '')
+ await fs.writeFile(path.join(cwd, 'hermes_cli', 'gateway_client.py'), 'def _session_ticket(*args, **kwargs):\n return "untrusted-project-ticket"\n')
+
+ try {
+ for (const purpose of ['interactive', 'native-http'] as const) {
+ await expect(mintGatewayTicketWithPython(backend, cwd, endpoint, purpose)).resolves.toBe('private-grant')
+ expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })
+ }
+
+ for (const invalid of [{ instance_id: 'other' }, { profile_id: '/other' }, { runtime_protocol: 2 }, { ticket: '' }]) {
+ override = invalid
+ await expect(mintGatewayTicketWithPython(backend, cwd, endpoint, 'interactive')).rejects.toThrow('Gateway ticket')
+ }
+ } finally {
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ await fs.rm(home, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.ts
new file mode 100644
index 00000000000..0027d10dfc2
--- /dev/null
+++ b/apps/desktop/electron/local-gateway-python.ts
@@ -0,0 +1,72 @@
+import { spawn } from 'node:child_process'
+
+import { hiddenWindowsChildOptions } from './windows-child-options'
+
+interface TicketEndpoint {
+ profile_id: string
+ instance_id: string
+ runtime_protocol: number
+}
+
+// Reuse the runtime's SID-validated, deadline-bounded pipe client. No Node pipe
+// connection may bypass GetNamedPipeServerProcessId / token-owner validation.
+const TICKET_SCRIPT = `
+import json, sys
+from pathlib import Path
+from types import SimpleNamespace
+from hermes_cli.gateway_client import _session_ticket
+request = json.loads(sys.stdin.buffer.read(65537))
+endpoint = SimpleNamespace(**request['endpoint'])
+home = Path(endpoint.profile_id)
+if str(home.resolve()) != endpoint.profile_id or endpoint.runtime_protocol != 1:
+ raise ValueError('invalid ticket endpoint')
+ticket = _session_ticket(home, endpoint, purpose=request['purpose'])
+sys.stdout.write(json.dumps({'ticket': ticket}))
+`
+
+export function mintGatewayTicketWithPython(
+ backend: { command: string; env?: NodeJS.ProcessEnv },
+ cwd: string,
+ endpoint: TicketEndpoint,
+ purpose: 'interactive' | 'native-http'
+): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(backend.command, ['-P', '-c', TICKET_SCRIPT], hiddenWindowsChildOptions({
+ cwd,
+ env: { ...process.env, ...backend.env, HERMES_HOME: endpoint.profile_id, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' },
+ shell: false,
+ stdio: ['pipe', 'pipe', 'pipe']
+ }))
+
+ let stdout = ''
+ const fail = () => reject(new Error('Gateway ticket bootstrap failed'))
+ const timer = setTimeout(() => { child.kill(); fail() }, 10_000)
+ child.on('error', fail)
+ child.stdin.on('error', fail)
+ child.stderr.resume()
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', data => {
+ stdout += data
+
+ if (stdout.length > 65536) { child.kill(); fail() }
+ })
+ child.on('close', code => {
+ clearTimeout(timer)
+
+ if (code !== 0) {
+ fail()
+
+ return
+ }
+
+ try {
+ const reply = JSON.parse(stdout)
+
+ if (typeof reply.ticket !== 'string' || !reply.ticket) { throw new Error() }
+ resolve(reply.ticket)
+ } catch { fail() }
+ })
+ // Identity is data on private stdin, never interpolated into code or a shell.
+ child.stdin.end(JSON.stringify({ endpoint, purpose }))
+ })
+}
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index 6388a42448d..b752ef23648 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -129,10 +129,18 @@ export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: Ga
return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(descriptor.gatewayEndpoint, 'native-http') }
}
+let windowsTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined
+
+export function configureWindowsGatewayTicketClient(client: NonNullable<typeof windowsTicketClient>) {
+ windowsTicketClient = client
+}
+
export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): 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') {
+ if (!windowsTicketClient) {throw new Error('Gateway ticket client is not configured')}
+
+ return windowsTicketClient(endpoint, purpose)
+ }
const home = endpoint.profile_id
if (await fs.realpath(home) !== home) {throw new Error('Noncanonical gateway profile')}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 1ec8e4e21d5..a212cc1e211 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,8 +1,17 @@
import { execFileSync, spawn } from 'node:child_process'
import type { GatewayEndpoint } from './local-gateway'
-import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'
+import { configureWindowsGatewayTicketClient, createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'
+import { mintGatewayTicketWithPython } from './local-gateway-python'
const localGatewayDials = createLocalGatewayDials()
+configureWindowsGatewayTicketClient(async (endpoint, purpose) => {
+ const backend = await ensureRuntime(resolveHermesBackend([]))
+ if (backend.kind !== 'python' || backend.shell) {
+ throw new Error('Gateway ticket bootstrap requires the installed Hermes Python runtime')
+ }
+
+ return mintGatewayTicketWithPython(backend, resolveHermesCwd(), endpoint, purpose)
+})
import crypto from 'node:crypto'
import fs from 'node:fs'
import http from 'node:http'