The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): send Cloudflare Access headers on OAuth login (#110987)
Austin Pickett03b0c7947262
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.tsindex 3340abfff86..abae4e81a68 100644--- a/apps/desktop/electron/connection-config.test.ts+++ b/apps/desktop/electron/connection-config.test.ts@@ -48,6 +48,7 @@ import {resolveRemoteSshDashboardProfile,resolveTestWsUrl,RT_COOKIE_VARIANTS,+ sanitizeRemoteHeaderValue,savedProfileSsh,tokenPreview,translateSelfProfileQuery,@@ -100,6 +101,25 @@ test('normalizeRemoteHeaders keeps safe proxy headers and drops transport/auth h)})+test('sanitizeRemoteHeaderValue strips CR/LF so a pasted token cannot split a request', () => {+ // Clipboard pastes of access-proxy service tokens routinely carry a trailing+ // newline; a bare CR/LF inside the value is a request-splitting vector once+ // it reaches setHeader / loadURL extraHeaders.+ assert.equal(sanitizeRemoteHeaderValue('client-secret\r\n'), 'client-secret')+ assert.equal(sanitizeRemoteHeaderValue(' client-secret\r '), 'client-secret')+ assert.equal(sanitizeRemoteHeaderValue('a\r\nX-Injected: evil'), 'aX-Injected: evil')+ assert.equal(sanitizeRemoteHeaderValue(undefined), '')+})++test('normalizeRemoteHeaders sanitizes plaintext values at ingest', () => {+ // A trailing newline was already handled by trim(); the gap this pins is an+ // EMBEDDED CR/LF, which trim() leaves intact and which would otherwise reach+ // the request as an injected second header.+ assert.deepEqual(normalizeRemoteHeaders({ 'CF-Access-Client-Secret': 'secret\r\nX-Injected: evil' }), {+ 'CF-Access-Client-Secret': { encoding: 'plain', value: 'secretX-Injected: evil' }+ })+})+test('remoteRequestMatchesBaseUrl treats HTTPS and WSS as the same gateway origin', () => {assert.equal(remoteRequestMatchesBaseUrl(diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.tsindex 07172d3e341..3e620d1be6d 100644--- a/apps/desktop/electron/connection-config.ts+++ b/apps/desktop/electron/connection-config.ts@@ -318,6 +318,23 @@ const FORBIDDEN_REMOTE_HEADER_NAMES = new Set(['x-hermes-session-token'])+/**+ * Strip CR/LF from a header VALUE. Clipboard pastes of access-proxy service+ * tokens routinely carry a trailing newline, and a bare CR/LF inside a header+ * value is a request-splitting vector once it reaches setHeader/extraHeaders.+ * Header NAMES are already constrained by REMOTE_HEADER_NAME_RE above, which+ * admits no whitespace, so values are the only gap.+ *+ * Applied at BOTH ends because a safeStorage envelope stores ciphertext: this+ * call sanitizes plaintext on the way in, and decryptRemoteHeaders sanitizes+ * again on the way out so encrypted-at-rest values get the same treatment.+ */+function sanitizeRemoteHeaderValue(value) {+ return String(value || '')+ .replace(/[\r\n]+/g, '')+ .trim()+}+function normalizeRemoteHeaders(raw) {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {return {}@@ -334,7 +351,7 @@ function normalizeRemoteHeaders(raw) {}if (typeof secret === 'string') {- const value = secret.trim()+ const value = sanitizeRemoteHeaderValue(secret)if (value) {out[headerName] = { encoding: 'plain', value }@@ -1076,6 +1093,7 @@ export {resolveRemoteSshDashboardProfile,resolveTestWsUrl,RT_COOKIE_VARIANTS,+ sanitizeRemoteHeaderValue,savedProfileSsh,tokenPreview,translateSelfProfileQuery,diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 4baab2a6a64..9c0c83fe977 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -121,12 +121,12 @@ import {profileRemoteOverride,profileSshOverride,type RegistryBackendRequestScope,- remoteRequestMatchesBaseUrl,resolveAuthMode,resolveProfileApiRequest,resolveProfileBackendRoute,resolveRemoteSshDashboardProfile,resolveTestWsUrl,+ sanitizeRemoteHeaderValue,savedProfileSsh,tokenPreview,withTransientRetries@@ -351,9 +351,12 @@ import {} from './remote-liveness'import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'import {- applyRemoteRequestHeaders,+ attachRemoteRequestHeaderListener,+ collectRemoteHeaderSources,createRegistryGatewayWsUrlHandler,- createRemoteWsHeaderStore+ createRemoteWsHeaderStore,+ oauthLoginLoadUrlOptions,+ resolveRemoteRequestHeaders} from './remote-ws-headers'import { missingRendererAssets } from './renderer-bundle'import { loadRendererLoadErrorPage } from './renderer-load-error-page'@@ -1711,7 +1714,7 @@ let connectionConfigCache = nulllet connectionConfigCacheMtime = nulllet connectionRegistryCache = nulllet connectionRegistryCacheMtime = null-let remoteHeaderRulesInstalled = false+const remoteHeaderSessions = new WeakSet<object>()const remoteWsHeaderStore = createRemoteWsHeaderStore()const previewWatchers = new Map()let previewShortcutActive = false@@ -7479,6 +7482,7 @@ function getOauthSession() {}oauthSession = session.fromPartition(OAUTH_SESSION_PARTITION)+ installRemoteHeaderRulesOnSession(oauthSession)return oauthSession}@@ -7519,6 +7523,7 @@ function getOauthSessionForUrl(url) {if (!sess) {sess = session.fromPartition(partition)oauthSessionsByPartition.set(partition, sess)+ installRemoteHeaderRulesOnSession(sess)}return sess@@ -7831,7 +7836,11 @@ function openOauthLoginWindow(baseUrl, { silent = false } = {}) {// silent=false loads the public ``/login`` chooser for interactive sign-in.const normalizedBase = normalizeRemoteBaseUrl(baseUrl)const loginUrl = silent ? `${normalizedBase}/` : `${normalizedBase}/login`- win.loadURL(loginUrl).catch(error => {+ const loginHeaders = headersForRemoteRequest(loginUrl)+ rememberLog(+ `OAuth login: attaching ${Object.keys(loginHeaders).length} extra gateway header(s) to ${new URL(normalizedBase).host}`+ )+ win.loadURL(loginUrl, oauthLoginLoadUrlOptions(loginHeaders)).catch(error => {finish(error instanceof Error ? error : new Error(String(error)))})})@@ -9158,7 +9167,12 @@ function decryptRemoteHeaders(headers) {const out = {}for (const [name, secret] of Object.entries(normalized)) {- const value = decryptDesktopSecret(secret)+ // Sanitize AFTER decryption as well as at ingest: a safeStorage envelope+ // stores ciphertext, so normalizeRemoteHeaders never sees its plaintext.+ // This is the single funnel every consumer of header values goes through+ // (login window extraHeaders, onBeforeSendHeaders, electronNet setHeader,+ // and both connection-test paths), so CR/LF can't reach a request here.+ const value = sanitizeRemoteHeaderValue(decryptDesktopSecret(secret))if (value) {out[name] = value@@ -9220,35 +9234,66 @@ function rememberRemoteWsHeaders(wsUrl, headers = {}) {remoteWsHeaderStore.remember(wsUrl, headers)}-function headersForRemoteRequest(requestUrl) {- const exactWsHeaders = remoteWsHeaderStore.headersFor(requestUrl)-- if (exactWsHeaders && Object.keys(exactWsHeaders).length > 0) {- return exactWsHeaders- }+// Decrypted header sources, memoized against the two config caches this+// process already keys off mtime. onBeforeSendHeaders now runs on every OAuth+// partition as well as defaultSession, so without this every subresource+// request would decrypt EVERY registry connection's headers — and a+// safeStorage-encoded value costs a keychain round-trip per read.+// Both readers refresh their cache object whenever the file mtime moves, so+// identity comparison on the cached objects is a correct staleness check.+let remoteHeaderSourcesCache: any = null+let remoteHeaderSourcesConfigKey: any = null+let remoteHeaderSourcesRegistryKey: any = null+function remoteHeaderSources() {const config = readDesktopConnectionConfig()+ const registry = readDesktopConnectionsRegistry()- if (modeIsRemoteLike(config.mode) && config.remote?.url) {- const headers = decryptRemoteHeaders(config.remote.headers)+ if (+ remoteHeaderSourcesCache &&+ remoteHeaderSourcesConfigKey === config &&+ remoteHeaderSourcesRegistryKey === registry+ ) {+ return remoteHeaderSourcesCache+ }++ const sources = collectRemoteHeaderSources({+ connections: (registry?.connections || []).map(entry => ({+ kind: entry.kind,+ url: entry.url,+ headers: decryptRemoteHeaders(entry.headers)+ })),+ v1Remote:+ modeIsRemoteLike(config.mode) && config.remote?.url+ ? { url: config.remote.url, headers: decryptRemoteHeaders(config.remote.headers) }+ : null+ })- if (Object.keys(headers).length > 0 && remoteRequestMatchesBaseUrl(requestUrl, config.remote.url)) {- return headers- }- }+ remoteHeaderSourcesCache = sources+ remoteHeaderSourcesConfigKey = config+ remoteHeaderSourcesRegistryKey = registry- return {}+ return sources}-function installRemoteHeaderRules() {- if (remoteHeaderRulesInstalled) {+function headersForRemoteRequest(requestUrl) {+ return resolveRemoteRequestHeaders(requestUrl, {+ exactHeaders: remoteWsHeaderStore.headersFor(requestUrl),+ sources: remoteHeaderSources()+ })+}++function installRemoteHeaderRulesOnSession(sess) {+ if (!sess || remoteHeaderSessions.has(sess)) {return}- remoteHeaderRulesInstalled = true- session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {- applyRemoteRequestHeaders(details, callback, headersForRemoteRequest)- })+ remoteHeaderSessions.add(sess)+ attachRemoteRequestHeaderListener(sess, headersForRemoteRequest)+}++function installRemoteHeaderRules() {+ installRemoteHeaderRulesOnSession(session.defaultSession)}// Validate + normalize the per-profile remote overrides map read from disk.diff --git a/apps/desktop/electron/remote-ws-headers.test.ts b/apps/desktop/electron/remote-ws-headers.test.tsindex 4aad322736b..fb4e3c9db91 100644--- a/apps/desktop/electron/remote-ws-headers.test.ts+++ b/apps/desktop/electron/remote-ws-headers.test.ts@@ -2,9 +2,13 @@ import { describe, expect, it, vi } from 'vitest'import {applyRemoteRequestHeaders,+ attachRemoteRequestHeaderListener,+ collectRemoteHeaderSources,createRegistryGatewayWsUrlHandler,createRemoteWsHeaderStore,- type RegistryGatewayWsConnection+ oauthLoginLoadUrlOptions,+ type RegistryGatewayWsConnection,+ resolveRemoteRequestHeaders} from './remote-ws-headers'const accessHeaders = {@@ -165,3 +169,47 @@ describe('registry gateway WebSocket headers', () => {expect(store.headersFor('wss://gateway.example/api/ws?token=secret&trace=one')).toEqual({})})})++describe('OAuth login and registry extra headers', () => {+ it('applies Connections extra headers to /login, not only an exact WebSocket URL', () => {+ const sources = collectRemoteHeaderSources({+ connections: [{ kind: 'local' }, { kind: 'remote', url: 'https://gateway.example', headers: accessHeaders }],+ v1Remote: { url: 'https://other.example', headers: { 'CF-Access-Client-Id': 'v1-only' } }+ })++ expect(resolveRemoteRequestHeaders('https://gateway.example/login', { sources })).toEqual(accessHeaders)+ expect(resolveRemoteRequestHeaders('https://gateway.example/api/status', { sources })).toEqual(accessHeaders)+ expect(oauthLoginLoadUrlOptions(accessHeaders)).toEqual({+ extraHeaders: 'CF-Access-Client-Id: client-id\nCF-Access-Client-Secret: client-secret'+ })+ expect(resolveRemoteRequestHeaders('https://other.example/login', { sources })).toEqual({+ 'CF-Access-Client-Id': 'v1-only'+ })+ })++ it('injects extra headers on an OAuth partition session, not only defaultSession', () => {+ const listeners = []++ const oauthSession = {+ webRequest: {+ onBeforeSendHeaders: listener => {+ listeners.push(listener)+ }+ }+ }++ const sources = collectRemoteHeaderSources({+ connections: [{ kind: 'remote', url: 'https://gateway.example', headers: accessHeaders }]+ })++ attachRemoteRequestHeaderListener(oauthSession, url => resolveRemoteRequestHeaders(url, { sources }))++ const callback = vi.fn()+ listeners[0]({ url: 'https://gateway.example/login', requestHeaders: { Origin: 'app://hermes' } }, callback)++ expect(listeners).toHaveLength(1)+ expect(callback).toHaveBeenCalledWith({+ requestHeaders: { Origin: 'app://hermes', ...accessHeaders }+ })+ })+})diff --git a/apps/desktop/electron/remote-ws-headers.ts b/apps/desktop/electron/remote-ws-headers.tsindex 5686ceb6483..d66bdeb5371 100644--- a/apps/desktop/electron/remote-ws-headers.ts+++ b/apps/desktop/electron/remote-ws-headers.ts@@ -1,3 +1,4 @@+import { remoteRequestMatchesBaseUrl } from './connection-config'import { registryGatewayWsUrl } from './plugin-profile-routes'export interface RegistryGatewayWsConnection {@@ -23,6 +24,101 @@ interface RemoteRequestDetails {type RemoteRequestCallback = (result: { requestHeaders?: Record<string, string> }) => void+export interface RemoteHeaderSource {+ headers?: Record<string, string>+ kind?: string+ url?: string+}++interface SessionLike {+ webRequest?: {+ onBeforeSendHeaders?: (+ listener: (details: RemoteRequestDetails, callback: RemoteRequestCallback) => void+ ) => void+ }+}++/**+ * Header blocks that Chromium (login window, renderer WS) may attach to a+ * remote gateway request. Registry Connections are the live source; the v1+ * single-remote block is fallback. Longer base URLs win so a path-prefixed+ * gateway is not shadowed by its origin sibling.+ *+ * Values arrive already sanitized: decryptRemoteHeaders in main.ts strips+ * CR/LF on the single decrypt funnel, so there is no second normalizer here.+ */+export function collectRemoteHeaderSources(input: {+ connections?: RemoteHeaderSource[]+ v1Remote?: null | RemoteHeaderSource+}): RemoteHeaderSource[] {+ const sources: RemoteHeaderSource[] = []++ for (const connection of input.connections || []) {+ if (connection.kind && connection.kind !== 'remote' && connection.kind !== 'cloud') {+ continue+ }++ if (!connection.url || !connection.headers || Object.keys(connection.headers).length === 0) {+ continue+ }++ sources.push({ headers: connection.headers, url: connection.url })+ }++ if (input.v1Remote?.url && input.v1Remote.headers && Object.keys(input.v1Remote.headers).length > 0) {+ sources.push({+ headers: input.v1Remote.headers,+ url: input.v1Remote.url+ })+ }++ return sources.sort((a, b) => String(b.url || '').length - String(a.url || '').length)+}++export function resolveRemoteRequestHeaders(+ requestUrl: string,+ options: { exactHeaders?: Record<string, string>; sources?: RemoteHeaderSource[] } = {}+): Record<string, string> {+ const exact = options.exactHeaders || {}++ if (Object.keys(exact).length > 0) {+ return exact+ }++ for (const source of options.sources || []) {+ if (!source.url || !source.headers) {+ continue+ }++ if (Object.keys(source.headers).length > 0 && remoteRequestMatchesBaseUrl(requestUrl, source.url)) {+ return source.headers+ }+ }++ return {}+}++export function formatLoadUrlExtraHeaders(headers: Record<string, string> = {}): string {+ return Object.entries(headers)+ .map(([name, value]) => `${name}: ${value}`)+ .join('\n')+}++export function oauthLoginLoadUrlOptions(headers: Record<string, string> = {}): { extraHeaders?: string } {+ const extraHeaders = formatLoadUrlExtraHeaders(headers)++ return extraHeaders ? { extraHeaders } : {}+}++export function attachRemoteRequestHeaderListener(+ sessionLike: SessionLike,+ headersForRequest: (requestUrl: string) => Record<string, string>+) {+ sessionLike?.webRequest?.onBeforeSendHeaders?.((details, callback) => {+ applyRemoteRequestHeaders(details, callback, headersForRequest)+ })+}+export function createRemoteWsHeaderStore(limit = 100) {const headersByUrl = new Map<string, Record<string, string>>()