hermes-agent/apps/desktop/electron/oauth-session-response.ts
austinpickett adc3678150 fix(desktop): mirror remote session cookies in memory and retry once on 401
The persist:hermes-remote-oauth partition family drops its hermes_session*
cookies in the field (Windows %3A profile folders, lazy hydration, flush
races), and electronNet's useSessionCookies intermittently omits the cookie
entirely → every authed REST call and WS-ticket mint 401s as no_cookie right
after a successful sign-in (#61457).

- New remote-session-cookies.ts: process-lifetime per-origin Set-Cookie
  mirror (memory only, never persisted).
- The login window snapshots the fresh jar into the mirror on success; every
  authed REST response records its Set-Cookie headers.
- fetchJsonViaOauthSession attaches the mirror as an explicit Cookie header
  (an explicit header bypasses the network stack's jar lookup) unless the
  caller supplied its own Cookie.
- On a 401 the mirror is dropped for the origin, one silent re-login is
  forced, and the request is retried once (safe: a 401 means the server
  rejected the request before executing it).

Fixes #61457
2026-09-26 20:47:10 -04:00

92 lines
2.6 KiB
TypeScript

import { Buffer } from 'node:buffer'
import { httpStatusError } from './api-transport'
// Response-stream extraction based on Bartok9's #99135 (original issue #72530).
export interface OauthResponseLike {
on(event: 'data', cb: (chunk: Buffer) => void): void
on(event: 'error', cb: (error: Error) => void): void
on(event: 'end', cb: () => void): void
statusCode?: number
headers: Record<string, string | string[] | undefined>
}
export interface WireOauthResponseOptions {
url: string
isTimedOut: () => boolean
clearTimer: () => void
resolve: (value: unknown) => void
reject: (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 {
const { url, isTimedOut, clearTimer, resolve, reject } = opts
const 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))
}
})
// Electron emits post-header loader failures on the response, not the request.
// Keep the listener after settlement: a late error must not become uncaught.
res.on('error', error => {
if (settled || isTimedOut()) {
return
}
settled = true
chunks.length = 0
clearTimer()
reject(error)
})
res.on('end', () => {
if (settled || isTimedOut()) {
return
}
settled = true
clearTimer()
const text = Buffer.concat(chunks).toString('utf8')
chunks.length = 0
const statusCode = res.statusCode || 500
if (statusCode >= 400) {
reject(httpStatusError(statusCode, text))
return
}
if (!text) {
resolve(null)
return
}
const looksHtml = /^\s*<(?:!doctype|html)/i.test(text)
const contentType = String(res.headers['content-type'] || res.headers['Content-Type'] || '')
if (looksHtml || contentType.includes('text/html')) {
reject(new Error(`Expected JSON from ${url} but got HTML (status ${statusCode}).`))
return
}
try {
resolve(JSON.parse(text))
} catch {
reject(new Error(`Invalid JSON from ${url} (status ${statusCode}): ${text.slice(0, 200)}`))
}
})
}