The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): mirror remote session cookies in memory and retry once on 401
austinpickettadc36781508a
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 72364b48546..782c1cdd6da 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -362,6 +362,7 @@ import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'import { mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'import { wireOauthSessionResponse } from './oauth-session-response'+import { remoteSessionCookies } from './remote-session-cookies'import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'import { bundledPayload, installIdForRoot, type PayloadInfo } from './payload-backend'@@ -7397,6 +7398,23 @@ function warmOauthCookieStore(url?) {// connection-config.ts (cookiesHaveSession / cookiesHaveLiveSession). See// that module for details.+// #61457: snapshot the partition jar's session cookies for this gateway into+// the in-memory mirror. Best-effort: a failed read just means the next+// response's Set-Cookie capture populates the mirror instead.+async function captureRemoteSessionCookiesIntoMirror(baseUrl) {+ const sess = getOauthSessionForUrl(baseUrl)++ if (!sess) {+ return+ }++ try {+ remoteSessionCookies.recordFromJar(baseUrl, await sess.cookies.get({ url: baseUrl }))+ } catch (error) {+ rememberLog(`Remote session cookie mirror capture failed: ${error?.message || error}`)+ }+}+async function hasOauthSessionCookie(baseUrl, { connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}) {const sess = getOauthSessionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind })@@ -7575,6 +7593,9 @@ function openOauthLoginWindow(if (err) {reject(err)} else {+ // #61457: the jar just got the fresh session cookies — mirror them+ // into memory immediately, before the jar can drop them again.+ void captureRemoteSessionCookiesIntoMirror(baseUrl)resolve({ baseUrl, ok: true })}}@@ -7683,86 +7704,131 @@ function openOauthLoginWindow(// JSON request routed through the OAuth session partition so the HttpOnly// session cookie is attached automatically by Electron's net stack. Used for// authed REST against a gated gateway, including minting WS tickets.+//+// #61457: the partition's Chromium jar is not a reliable cookie source — it can+// drop the `hermes_session*` cookies (Windows %3A profile folders, lazy+// hydration, flush races) and `useSessionCookies: true` then intermittently+// omits the cookie → 401 `no_cookie` right after a successful sign-in. Two+// mitigations, both keyed by origin:+// 1. an explicit `Cookie` header built from the in-memory session-cookie+// mirror (remote-session-cookies.ts) — an explicit header bypasses the+// network stack's jar lookup entirely, and every `Set-Cookie` observed+// here (and in the login window) feeds the mirror back; and+// 2. one forced silent re-login + single retry when the gateway still+// answers 401. Safe even for mutations: a 401 means the server rejected+// the request before executing it.function fetchJsonViaOauthSession(url, options: any = {}) {- return new Promise((resolve, reject) => {- const sess = getOauthSessionForUrl(url)+ const attempt = (): Promise<unknown> =>+ new Promise((resolve, reject) => {+ const sess = getOauthSessionForUrl(url)- if (!sess) {- reject(new Error('OAuth session partition is unavailable.'))+ if (!sess) {+ reject(new Error('OAuth session partition is unavailable.'))- return- }+ return+ }- let parsed+ let parsed- try {- parsed = new URL(url)- } catch (error) {- reject(new Error(`Invalid URL: ${error.message}`))+ try {+ parsed = new URL(url)+ } catch (error) {+ reject(new Error(`Invalid URL: ${error.message}`))- return- }+ return+ }- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {- reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))- return- }+ return+ }- const body = serializeJsonBody(options.body)- const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)+ const body = serializeJsonBody(options.body)+ const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)- const request = electronNet.request({- method: options.method || 'GET',- url,- session: sess,- useSessionCookies: true,- redirect: 'follow'- } as any)+ const request = electronNet.request({+ method: options.method || 'GET',+ url,+ session: sess,+ useSessionCookies: true,+ redirect: 'follow'+ } as any)- setJsonRequestHeaders(request)+ setJsonRequestHeaders(request)- for (const [name, value] of Object.entries({ ...headersForRemoteRequest(url), ...(options.headers || {}) })) {- request.setHeader(name, String(value))- }+ const headerBag = { ...headersForRemoteRequest(url), ...(options.headers || {}) }- let timedOut = false+ // Explicit mirror cookies ride last so an existing caller-supplied+ // Cookie header still wins, and the mirror never clobbers intent.+ const mirroredCookies = remoteSessionCookies.cookieHeaderFor(url)- const timer = setTimeout(() => {- timedOut = true+ if (mirroredCookies && headerBag.Cookie === undefined && headerBag.cookie === undefined) {+ headerBag.Cookie = mirroredCookies+ }- try {- request.abort()- } catch {- // already finished+ for (const [name, value] of Object.entries(headerBag)) {+ request.setHeader(name, String(value))}- reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))- }, timeoutMs)+ let timedOut = false- request.on('response', (res: Electron.IncomingMessage): void => {- wireOauthSessionResponse(res, {- url,- isTimedOut: (): boolean => timedOut,- clearTimer: (): void => clearTimeout(timer),- resolve,- reject+ const timer = setTimeout(() => {+ timedOut = true++ try {+ request.abort()+ } catch {+ // already finished+ }++ reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))+ }, timeoutMs)++ request.on('response', (res: Electron.IncomingMessage): void => {+ wireOauthSessionResponse(res, {+ url,+ isTimedOut: (): boolean => timedOut,+ clearTimer: (): void => clearTimeout(timer),+ resolve,+ reject,+ onSetCookies: setCookie => remoteSessionCookies.record(url, setCookie)+ })})- })- request.on('error', error => {- if (timedOut) {- return+ request.on('error', error => {+ if (timedOut) {+ return+ }++ clearTimeout(timer)+ reject(error)+ })++ if (body) {+ request.write(body)}- clearTimeout(timer)- reject(error)+ request.end()})- if (body) {- request.write(body)+ return attempt().catch(async error => {+ if (Number(error?.statusCode) !== 401) {+ throw error+ }++ // Stale mirror + dead jar: force one silent re-login, then retry once.+ remoteSessionCookies.clear(url)++ try {+ await openOauthLoginWindow(new URL(url).origin, { silent: true })+ } catch (reloginError) {+ rememberLog(+ `Remote session re-login after 401 failed for ${new URL(url).host}: ${reloginError?.message || reloginError}`+ )+ throw error}- request.end()+ return attempt()})}diff --git a/apps/desktop/electron/oauth-session-response.ts b/apps/desktop/electron/oauth-session-response.tsindex 94b28d4d8fc..e58c0e477d1 100644--- a/apps/desktop/electron/oauth-session-response.ts+++ b/apps/desktop/electron/oauth-session-response.ts@@ -17,6 +17,8 @@ export interface WireOauthResponseOptions {clearTimer: () => voidresolve: (value: unknown) => voidreject: (error: Error) => void+ /** Observe the response's `Set-Cookie` header(s) at wire time (#61457). */+ onSetCookies?: (setCookie: string | string[] | undefined) => void}export function wireOauthSessionResponse(res: OauthResponseLike, opts: WireOauthResponseOptions): void {@@ -24,6 +26,14 @@ export function wireOauthSessionResponse(res: OauthResponseLike, opts: WireOauthconst chunks: Buffer[] = []let settled = false+ // Headers exist the moment the response event fires — capture before the+ // body drains so a fast body can't race the capture.+ try {+ opts.onSetCookies?.(res.headers['set-cookie'] as string | string[] | undefined)+ } catch {+ // observation must never affect the request+ }+res.on('data', chunk => {if (!settled && !isTimedOut()) {chunks.push(Buffer.from(chunk))diff --git a/apps/desktop/electron/remote-session-cookies.test.ts b/apps/desktop/electron/remote-session-cookies.test.tsnew file mode 100644index 00000000000..774bd0ca26e--- /dev/null+++ b/apps/desktop/electron/remote-session-cookies.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest'++import { originKeyFor, parseSetCookie, RemoteSessionCookieStore } from './remote-session-cookies'++describe('parseSetCookie', () => {+ it('takes the first Name=Value pair and ignores attributes', () => {+ expect(parseSetCookie('hermes_session=abc123; Path=/; HttpOnly; SameSite=Lax')).toEqual({+ name: 'hermes_session',+ value: 'abc123'+ })+ })++ it('returns null for unparsable headers', () => {+ expect(parseSetCookie('')).toBeNull()+ expect(parseSetCookie('nonsense')).toBeNull()+ expect(parseSetCookie('=value')).toBeNull()+ expect(parseSetCookie('name=')).toBeNull()+ })+})++describe('originKeyFor', () => {+ it('keys on protocol+host, ignoring path and port-implicit forms', () => {+ expect(originKeyFor('https://gw.example.com/api/status')).toBe('https://gw.example.com')+ expect(originKeyFor('http://localhost:8734/ws-ticket')).toBe('http://localhost:8734')+ expect(originKeyFor('ftp://gw.example.com')).toBeNull()+ expect(originKeyFor('not a url')).toBeNull()+ })+})++describe('RemoteSessionCookieStore', () => {+ it('records Set-Cookie headers and serializes a Cookie header per origin', () => {+ const store = new RemoteSessionCookieStore()++ store.record('https://gw.example.com/api/auth/login', 'hermes_session=abc; Path=/; HttpOnly')+ store.record('https://gw.example.com/api/other', ['refresh=xyz; Path=/', 'broken'])++ expect(store.cookieHeaderFor('https://gw.example.com/api/auth/ws-ticket')).toBe('hermes_session=abc; refresh=xyz')+ // Origin-scoped: another gateway sees nothing.+ expect(store.cookieHeaderFor('https://other.example.com/api')).toBeNull()+ })++ it('overwrites a cookie when the gateway rotates it', () => {+ const store = new RemoteSessionCookieStore()++ store.record('https://gw.example.com', 'hermes_session=old; Path=/')+ store.record('https://gw.example.com', 'hermes_session=new; Path=/')++ expect(store.cookieHeaderFor('https://gw.example.com/')).toBe('hermes_session=new')+ })++ it('seeds from a session jar read', () => {+ const store = new RemoteSessionCookieStore()++ store.recordFromJar('https://gw.example.com', [+ { name: 'hermes_session', value: 'jar-value' },+ { name: '', value: 'x' },+ { value: 'no-name' }+ ])++ expect(store.cookieHeaderFor('https://gw.example.com/x')).toBe('hermes_session=jar-value')+ })++ it('clear drops only the target origin (or everything)', () => {+ const store = new RemoteSessionCookieStore()++ store.record('https://gw.example.com', 'a=1; Path=/')+ store.record('https://other.example.com', 'b=2; Path=/')++ store.clear('https://gw.example.com/api/status')+ expect(store.cookieHeaderFor('https://gw.example.com/')).toBeNull()+ expect(store.cookieHeaderFor('https://other.example.com/')).toBe('b=2')++ store.clear()+ expect(store.cookieHeaderFor('https://other.example.com/')).toBeNull()+ })+})diff --git a/apps/desktop/electron/remote-session-cookies.ts b/apps/desktop/electron/remote-session-cookies.tsnew file mode 100644index 00000000000..56a422b327a--- /dev/null+++ b/apps/desktop/electron/remote-session-cookies.ts@@ -0,0 +1,146 @@+/**+ * remote-session-cookies.ts+ *+ * In-memory per-origin session-cookie mirror for remote gateways (#61457).+ *+ * The `persist:hermes-remote-oauth` partition family is supposed to keep the+ * dashboard `hermes_session*` cookies on disk, but in the field the Chromium+ * jar can drop them (Windows %3A profile folders, lazy hydration, jar flush+ * races), and `electronNet` with `useSessionCookies: true` then intermittently+ * omits the cookie entirely → every authed REST call and WS-ticket mint 401s+ * as `no_cookie` right after a successful sign-in.+ *+ * This module is the belt-and-braces fix: capture every `Set-Cookie` the+ * gateway sends (login window navigations AND authed REST responses) into a+ * process-lifetime map keyed by origin, and let `fetchJsonViaOauthSession`+ * attach them as an explicit `Cookie` header — an explicit header is never+ * subject to the network stack's jar-lookup flakiness.+ *+ * Secrets stay in process memory only (never persisted to disk), and+ * `clear(origin)` drops a stale identity so an old session can never cross+ * into a newly selected one.+ */++export interface ParsedCookie {+ name: string+ value: string+}++/** `Name=Value` from the first attribute pair of a Set-Cookie header; null when unparsable. */+export function parseSetCookie(header: string): ParsedCookie | null {+ if (typeof header !== 'string' || !header.trim()) {+ return null+ }++ const firstPair = header.split(';', 1)[0] ?? ''+ const eq = firstPair.indexOf('=')++ if (eq <= 0) {+ return null+ }++ const name = firstPair.slice(0, eq).trim()+ const value = firstPair.slice(eq + 1).trim()++ if (!name || !value) {+ return null+ }++ return { name, value }+}++/** `protocol//host` origin key for a request URL; null when not http(s). */+export function originKeyFor(url: string): string | null {+ try {+ const parsed = new URL(url)++ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ return null+ }++ return `${parsed.protocol}//${parsed.host}`+ } catch {+ return null+ }+}++export class RemoteSessionCookieStore {+ private readonly byOrigin = new Map<string, Map<string, string>>()++ /** Record every parsable cookie from a response's `Set-Cookie` header(s). */+ record(url: string, setCookie: string | string[] | undefined | null): void {+ const origin = originKeyFor(url)++ if (!origin || !setCookie) {+ return+ }++ const headers = Array.isArray(setCookie) ? setCookie : [setCookie]+ let jar = this.byOrigin.get(origin)++ for (const header of headers) {+ const parsed = parseSetCookie(header)++ if (!parsed) {+ continue+ }++ if (!jar) {+ jar = new Map()+ this.byOrigin.set(origin, jar)+ }++ jar.set(parsed.name, parsed.value)+ }+ }++ /** Seed the mirror from a session jar read (`sess.cookies.get({url})` results). */+ recordFromJar(url: string, cookies: Array<{ name?: unknown; value?: unknown }> | null | undefined): void {+ const origin = originKeyFor(url)++ if (!origin || !Array.isArray(cookies)) {+ return+ }++ for (const cookie of cookies) {+ if (typeof cookie?.name === 'string' && typeof cookie?.value === 'string' && cookie.name && cookie.value) {+ let jar = this.byOrigin.get(origin)++ if (!jar) {+ jar = new Map()+ this.byOrigin.set(origin, jar)+ }++ jar.set(cookie.name, cookie.value)+ }+ }+ }++ /** Serialize the origin's mirror as a `Cookie` header value; null when empty. */+ cookieHeaderFor(url: string): string | null {+ const origin = originKeyFor(url)+ const jar = origin ? this.byOrigin.get(origin) : undefined++ if (!jar || jar.size === 0) {+ return null+ }++ return [...jar.entries()].map(([name, value]) => `${name}=${value}`).join('; ')+ }++ /** Drop one origin's mirror (stale identity / forced re-login); omit to clear everything. */+ clear(originOrUrl?: string): void {+ if (!originOrUrl) {+ this.byOrigin.clear()++ return+ }++ const origin = originKeyFor(originOrUrl) ?? originOrUrl++ this.byOrigin.delete(origin)+ }+}++/** Process-lifetime mirror used by main.ts. */+export const remoteSessionCookies = new RemoteSessionCookieStore()