Skip to content

The agent that grows with you

fix: authenticate native desktop HTTP with fresh private tickets

Tekniumdd8b9f38344d
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index 12f3af26163..2713789d06b 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -2,6 +2,40 @@ import { expect, test } from 'vitest'
import { createLocalGatewayDials, ensureLocalGateway } from './local-gateway'
+test('native HTTP mints fresh purpose-bound grants without browser credentials', async () => {
+ const fs = await import('node:fs/promises')
+ const os = await import('node:os')
+ const path = await import('node:path')
+ const net = await import('node:net')
+ const { nativeGatewayHttpHeaders } = await import('./local-gateway')
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-http-'))
+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
+ const requests: any[] = []
+
+ 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: { profile_id: home, instance_id: 'owner', ticket: `grant-${requests.length}` } }) + '\n')
+ }))
+
+ await new Promise<void>(resolve => server.listen(path.join(home, 'gateway.sock'), resolve))
+ await fs.chmod(path.join(home, 'gateway.sock'), 0o600)
+
+ try {
+ const descriptor = { gatewayEndpoint: endpoint, baseUrl: endpoint.api_origin }
+ const a = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')
+ const b = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')
+ expect(a).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-1' })
+ expect(b).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-2' })
+ expect(requests.map(r => r.params)).toEqual([1, 2].map(() => ({ profile_id: home, instance_id: 'owner', purpose: 'native-http' })))
+ await expect(nativeGatewayHttpHeaders(descriptor, 'http://127.0.0.1:4567/api/config')).rejects.toThrow('origin')
+ expect(requests).toHaveLength(2)
+ } finally {
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ await fs.rm(home, { recursive: true, force: true })
+ }
+})
+
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' }
const connection = await ensureLocalGateway(async () => ({ code: 0, stdout: JSON.stringify({ state: 'ready', endpoint }) }))
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index bf8cc1a9b3d..d5354230669 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -91,7 +91,15 @@ async function privateNode(file: string, kind: 'directory' | 'socket' | 'file')
if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) {throw new Error('Unsafe gateway control path')}
}
-export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint): Promise<string> {
+export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string) {
+ if (new URL(url).origin !== descriptor.gatewayEndpoint.api_origin || descriptor.baseUrl !== descriptor.gatewayEndpoint.api_origin) {
+ throw new Error('Native gateway HTTP origin mismatch')
+ }
+
+ return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(descriptor.gatewayEndpoint, 'native-http') }
+}
+
+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')}
@@ -120,7 +128,7 @@ export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint): Promise
const deadline = setTimeout(() => socket.destroy(new Error('Gateway ticket deadline')), 5000)
socket.on('error', () => reject(new Error('Gateway ticket bootstrap failed')))
socket.on('close', () => { clearTimeout(deadline); reject(new Error('Gateway ticket connection closed')) })
- 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('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose } }) + '\n'))
socket.on('data', chunk => {
buffer += chunk.toString()
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 3c87900a80b..214ebd1ac78 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,6 +1,6 @@
import { execFileSync, spawn } from 'node:child_process'
-import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, runGatewayEnsure } from './local-gateway'
+import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from './local-gateway'
const localGatewayDials = createLocalGatewayDials()
import crypto from 'node:crypto'
import fs from 'node:fs'
@@ -5346,8 +5346,13 @@ function fetchJson(url, token, options: any = {}) {
// transient transport error; POST/PUT/DELETE only when the request provably
// never reached the server (see shouldRetryRequest) — never double-submit.
return withRetry(
- (requestState: any) =>
- new Promise((resolve, reject) => {
+ async (requestState: any) => {
+ // Mint inside each retry: a grant authorizes exactly one HTTP request.
+ const nativeHeaders = options.gatewayDescriptor
+ ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url)
+ : null
+
+ return new Promise((resolve, reject) => {
const { body, contentType } = options.upload
? multipartBody(options.upload)
: {
@@ -5375,7 +5380,7 @@ function fetchJson(url, token, options: any = {}) {
...headersForRemoteRequest(url),
...(options.headers || {}),
'Content-Type': contentType,
- 'X-Hermes-Session-Token': token,
+ ...(nativeHeaders || { 'X-Hermes-Session-Token': token }),
// RFC 8252 native flow authenticates the gated gateway with a bearer
// token instead of the loopback session-token header. When
// ``options.bearer`` is set we send Authorization: Bearer <token>;
@@ -5446,7 +5451,8 @@ function fetchJson(url, token, options: any = {}) {
}
req.end()
- }),
+ })
+ },
{ method: options.method || 'GET' }
)
}
@@ -11087,7 +11093,7 @@ async function requestJsonForProfile(profile: string, path: string, method: stri
return fetchJsonViaOauthSession(url, { ...opts, headers: conn.headers })
}
- return fetchJson(url, conn.token, { ...opts, headers: conn.headers })
+ return fetchJson(url, conn.token, { ...opts, headers: conn.headers, gatewayDescriptor: conn.gatewayEndpoint ? conn : undefined })
}
async function probeRemoteAuthMode(rawUrl) {
@@ -15631,7 +15637,8 @@ async function fetchJsonForBackend(
body: opts.body,
upload: opts.upload,
timeoutMs: opts.timeoutMs,
- headers: descriptor.headers
+ headers: descriptor.headers,
+ gatewayDescriptor: descriptor.gatewayEndpoint ? descriptor : undefined
})
}
@@ -16326,7 +16333,8 @@ async function handleHermesApiRequest(request) {
method: request?.method,
body: request?.body,
upload: request?.upload,
- timeoutMs
+ timeoutMs,
+ gatewayDescriptor: connection.gatewayEndpoint ? connection : undefined
})
}
} catch (error) {