Skip to content

The agent that grows with you

fix: authenticate native desktop file downloads per attempt

Teknium28741ef8809e
diff --git a/apps/desktop/electron/gateway-download-transport.test.ts b/apps/desktop/electron/gateway-download-transport.test.ts
new file mode 100644
index 00000000000..3a5bb4abe4e
--- /dev/null
+++ b/apps/desktop/electron/gateway-download-transport.test.ts
@@ -0,0 +1,56 @@
+import { expect, test } from 'vitest'
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import net from 'node:net'
+import http from 'node:http'
+import { downloadViaTokenToFile } from './gateway-download-transport'
+import { destroyKeepaliveAgents } from './api-transport'
+
+test.skipIf(process.platform === 'win32')('download retries mint a new private grant for every wire attempt and preserve remote auth', async () => {
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'download-auth-'))
+ const grants: string[] = []
+ const wire: http.IncomingHttpHeaders[] = []
+ const controls: any[] = []
+ const control = net.createServer(socket => socket.once('data', chunk => {
+ controls.push(JSON.parse(chunk.toString()).params)
+ const ticket = `private-${controls.length}`
+ grants.push(ticket)
+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket } }) + '\n')
+ }))
+ await new Promise<void>(resolve => control.listen(path.join(home, 'gateway.sock'), resolve))
+ await fs.chmod(path.join(home, 'gateway.sock'), 0o600)
+ const server = http.createServer((req, res) => {
+ wire.push(req.headers)
+ if (wire.length === 1) { req.socket.destroy(); return }
+ res.end(Buffer.from([0, 255, 1, 2, 128]))
+ })
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const baseUrl = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`
+ const gatewayEndpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: baseUrl, capabilities: ['session-authority-v1'], supervisor: 'none' }
+ const finish = async (res: http.IncomingMessage) => {
+ const chunks: Buffer[] = []
+ for await (const chunk of res) { chunks.push(Buffer.from(chunk)) }
+ return Buffer.concat(chunks)
+ }
+ try {
+ const bytes = await downloadViaTokenToFile(baseUrl + '/api/fs/download', '', {}, finish, { gatewayDescriptor: { baseUrl, gatewayEndpoint } })
+ expect(bytes).toEqual(Buffer.from([0, 255, 1, 2, 128]))
+ expect(wire.map(h => h['x-hermes-gateway-ticket'])).toEqual(grants)
+ expect(new Set(grants).size).toBe(2)
+ expect(controls).toEqual(grants.map(() => ({ profile_id: home, instance_id: 'owner', purpose: 'native-http' })))
+ expect(wire.every(h => !h.origin && !h['x-hermes-session-token'] && !h.authorization)).toBe(true)
+ await expect(downloadViaTokenToFile(baseUrl + '/api/fs/download', '', {}, finish, { gatewayDescriptor: { baseUrl: baseUrl + '/wrong', gatewayEndpoint } })).rejects.toThrow('origin')
+ expect(wire).toHaveLength(2)
+ await downloadViaTokenToFile(baseUrl, 'remote-static', {}, finish)
+ await downloadViaTokenToFile(baseUrl, null, {}, finish, { bearer: 'remote-bearer' })
+ expect(wire[2]['x-hermes-session-token']).toBe('remote-static')
+ expect(wire[3].authorization).toBe('Bearer remote-bearer')
+ expect(wire.slice(2).every(h => !h['x-hermes-gateway-ticket'])).toBe(true)
+ expect(grants).toHaveLength(2)
+ } finally {
+ destroyKeepaliveAgents()
+ await Promise.all([new Promise<void>(resolve => server.close(() => resolve())), new Promise<void>(resolve => control.close(() => resolve()))])
+ await fs.rm(home, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/gateway-download-transport.ts b/apps/desktop/electron/gateway-download-transport.ts
new file mode 100644
index 00000000000..05da48b066b
--- /dev/null
+++ b/apps/desktop/electron/gateway-download-transport.ts
@@ -0,0 +1,47 @@
+import http from 'node:http'
+import https from 'node:https'
+
+import { downloadAgentFor, withRetry } from './api-transport'
+import { DEFAULT_FETCH_TIMEOUT_MS, resolveTimeoutMs } from './hardening'
+import { nativeGatewayHttpHeaders } from './local-gateway'
+
+// Retry only the connection phase, never a save dialog or a partially saved body.
+export async function downloadViaTokenToFile(url, token, ctx, finalizeGatewayDownload, options: any = {}) {
+ const parsed = new URL(url)
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`)
+ }
+
+ const res: http.IncomingMessage = await withRetry(async () => {
+ const headers = options.gatewayDescriptor
+ ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url)
+ : options.bearer ? { Authorization: `Bearer ${options.bearer}` } : { 'X-Hermes-Session-Token': token }
+
+ return new Promise<http.IncomingMessage>((resolve, reject) => {
+ const client = parsed.protocol === 'https:' ? https : http
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+
+ const req = client.request(parsed, {
+ agent: downloadAgentFor(parsed.protocol), method: 'GET', headers
+ }, response => {
+ req.setTimeout(0)
+ resolve(response)
+ })
+
+ req.on('error', reject)
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`)))
+ req.end()
+ })
+ }, { method: 'GET' })
+
+ // Node does not follow redirects: never send a one-use grant to a new target.
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400) {
+ res.destroy()
+ throw new Error(`Unexpected download redirect (${res.statusCode})`)
+ }
+
+ return finalizeGatewayDownload(res, res.statusCode || 500, res.headers || {}, {
+ ...ctx, abort: () => res.destroy()
+ })
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index b1638610f39..7ca0010db90 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,5 +1,6 @@
import { execFileSync, spawn } from 'node:child_process'
+import type { GatewayEndpoint } from './local-gateway'
import { createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from './local-gateway'
const localGatewayDials = createLocalGatewayDials()
import crypto from 'node:crypto'
@@ -34,7 +35,7 @@ import {
} from 'electron'
import { classifyActiveRuntime } from './active-runtime-state'
-import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'
+import { destroyKeepaliveAgents, jsonAgentFor, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'
import {
@@ -189,6 +190,7 @@ import {
} from './find-in-page'
import { createFirstRunSetupGate } from './first-run-setup-gate'
import { registerFsIpc } from './fs-ipc'
+import { downloadViaTokenToFile } from './gateway-download-transport'
import {
filenameFromContentDisposition,
fsPumpDeps,
@@ -5457,64 +5459,6 @@ function fetchJson(url, token, options: any = {}) {
)
}
-// Token-auth download that streams the response body straight to a
-// user-selected destination (via finalizeGatewayDownload) instead of buffering
-// the whole file in memory. The connect timeout is cleared once headers arrive
-// so a slow save dialog or a large stream doesn't trip it. `options.bearer`
-// switches the header to Authorization (RFC 8252 native flow), matching fetchJson.
-function downloadViaTokenToFile(url, token, ctx, options: any = {}) {
- return new Promise((resolve, reject) => {
- let parsed
-
- try {
- parsed = new URL(url)
- } catch (error) {
- reject(new Error(`Invalid URL: ${error.message}`))
-
- return
- }
-
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))
-
- return
- }
-
- const client = parsed.protocol === 'https:' ? https : http
- const agent = downloadAgentFor(parsed.protocol)
- const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
-
- const req = client.request(
- parsed,
- {
- agent,
- method: 'GET',
- headers: options.bearer ? { Authorization: `Bearer ${options.bearer}` } : { 'X-Hermes-Session-Token': token }
- },
- res => {
- // Headers arrived — the connection phase is done. Drop the idle timeout
- // so it can't abort mid-stream or while the save dialog is open.
- req.setTimeout(0)
- finalizeGatewayDownload(res, res.statusCode || 500, res.headers || {}, {
- ...ctx,
- abort: () => {
- try {
- req.destroy()
- } catch {
- // already finished
- }
- }
- }).then(resolve, reject)
- }
- )
-
- req.on('error', reject)
- req.setTimeout(timeoutMs, () => {
- req.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
- })
- req.end()
- })
-}
function fetchPublicJson(url, options: any = {}) {
// Credential-free JSON GET/POST for public gateway endpoints
@@ -8155,7 +8099,8 @@ function readGatewayErrorText(res): Promise<string> {
}
interface GatewayFileConnection extends RegistryBackendRequestScope {
- authMode?: 'oauth' | 'token'
+ gatewayEndpoint?: GatewayEndpoint
+ authMode?: 'oauth' | 'token' | 'native'
baseUrl: string
token?: null | string
}
@@ -8219,14 +8164,14 @@ async function saveGatewayFile(payload: GatewayFileSavePayload = {}) {
const auth = await gatedFileAuth(connection)
if (auth.kind === 'bearer') {
- return await downloadViaTokenToFile(url, auth.token, ctx, { bearer: auth.token })
+ return await downloadViaTokenToFile(url, auth.token, ctx, finalizeGatewayDownload, { bearer: auth.token })
}
if (auth.kind === 'cookie') {
return await downloadViaOauthSessionToFile(url, ctx)
}
- return await downloadViaTokenToFile(url, auth.token, ctx)
+ return await downloadViaTokenToFile(url, auth.token, ctx, finalizeGatewayDownload, { gatewayDescriptor: connection.gatewayEndpoint ? connection : undefined })
} catch (error) {
// Desktop and the remote gateway update independently. A gateway predating
// /api/fs/download 404s here; fall back (ONLY on 404) to the older capped
@@ -8257,7 +8202,7 @@ async function saveGatewayFileViaDataUrl(
} else if (auth.kind === 'cookie') {
json = await fetchJsonViaOauthSession(url)
} else {
- json = await fetchJson(url, auth.token)
+ json = await fetchJson(url, auth.token, { gatewayDescriptor: connection.gatewayEndpoint ? connection : undefined })
}
const dataUrl =