diff --git a/package.json b/package.json index 58f4805d9374..c06cf84dc0aa 100644 --- a/package.json +++ b/package.json @@ -174,6 +174,7 @@ "sherpa-onnx": "1.12.37", "ssh2": "^1.17.0", "tweetnacl": "^1.0.3", + "undici": "^7.29.0", "ws": "^8.21.3", "yaml": "^2.8.4", "zod": "~4.5.4" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d7481f2e5562..b9521e0e59f7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -185,6 +185,9 @@ importers: tweetnacl: specifier: ^1.0.3 version: 1.0.3 + undici: + specifier: ^7.29.0 + version: 7.29.0 ws: specifier: ^8.21.3 version: 8.21.3 diff --git a/src/main/claude-accounts/oauth-refresh.test.ts b/src/main/claude-accounts/oauth-refresh.test.ts index dd5e01c245a5..318d610fd5d8 100644 --- a/src/main/claude-accounts/oauth-refresh.test.ts +++ b/src/main/claude-accounts/oauth-refresh.test.ts @@ -7,17 +7,25 @@ import { refreshClaudeOauthCredentials } from './oauth-refresh' -const { netFetchMock } = vi.hoisted(() => ({ - netFetchMock: vi.fn() +const { fetchMock, envHttpProxyAgentMock, dispatcherCloseMock } = vi.hoisted(() => ({ + fetchMock: vi.fn(), + envHttpProxyAgentMock: vi.fn(), + dispatcherCloseMock: vi.fn().mockResolvedValue(undefined) })) +// Why: the token endpoint refuses Chromium's stack (orca#18716); the refresh +// must never go through Electron's net.fetch again. vi.mock('electron', () => ({ - net: { fetch: netFetchMock }, - session: { defaultSession: {} } + net: { + fetch: () => { + throw new Error('refresh must not use electron net.fetch') + } + } })) -vi.mock('../network/proxy-settings', () => ({ - ensureElectronProxyFromEnvironment: vi.fn().mockResolvedValue({ source: 'none' }) +vi.mock('undici', () => ({ + fetch: fetchMock, + EnvHttpProxyAgent: envHttpProxyAgentMock })) const NOW = 1_700_000_000_000 @@ -127,37 +135,51 @@ describe('applyRefreshedToken', () => { }) describe('refreshClaudeOauthCredentials', () => { + const NO_PROXY_ENV = {} + beforeEach(() => { vi.clearAllMocks() + envHttpProxyAgentMock.mockImplementation( + function (this: { close: typeof dispatcherCloseMock }) { + this.close = dispatcherCloseMock + } + ) }) afterEach(() => { vi.clearAllMocks() }) - it('returns null without a refresh token (no network call)', async () => { - const result = await refreshClaudeOauthCredentials( - credentials({ refreshToken: undefined }), - NOW - ) - expect(result).toBeNull() - expect(netFetchMock).not.toHaveBeenCalled() - }) - - it('posts a form-urlencoded refresh grant and persists the rotation', async () => { - netFetchMock.mockResolvedValue({ + function okResponse(): { ok: true; json: () => Promise> } { + return { ok: true, json: async () => ({ access_token: 'fresh-access', expires_in: 3600, refresh_token: 'fresh-refresh' }) + } + } + + it('returns null without a refresh token (no network call)', async () => { + const result = await refreshClaudeOauthCredentials(credentials({ refreshToken: undefined }), { + now: NOW, + env: NO_PROXY_ENV }) + expect(result).toBeNull() + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('posts a form-urlencoded refresh grant through Node fetch and persists the rotation', async () => { + fetchMock.mockResolvedValue(okResponse()) - const result = await refreshClaudeOauthCredentials(credentials(), NOW) + const result = await refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: NO_PROXY_ENV + }) - expect(netFetchMock).toHaveBeenCalledTimes(1) - const [url, init] = netFetchMock.mock.calls[0] + expect(fetchMock).toHaveBeenCalledTimes(1) + const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('https://platform.claude.com/v1/oauth/token') expect(init.method).toBe('POST') expect(init.headers['Content-Type']).toBe('application/x-www-form-urlencoded') @@ -165,22 +187,112 @@ describe('refreshClaudeOauthCredentials', () => { expect(body.get('grant_type')).toBe('refresh_token') expect(body.get('refresh_token')).toBe('old-refresh') expect(body.get('client_id')).toBe('9d1c250a-e61b-44d9-88ed-5944d1962f5e') + expect(init.dispatcher).toBeUndefined() + expect(envHttpProxyAgentMock).not.toHaveBeenCalled() const oauth = parseClaudeOauthBlob(result!)! expect(oauth.accessToken).toBe('fresh-access') expect(oauth.refreshToken).toBe('fresh-refresh') }) - it('returns null on a non-ok response and logs the status for diagnosability', async () => { + it('tunnels through the shell proxy with its NO_PROXY list', async () => { + fetchMock.mockResolvedValue(okResponse()) + + await refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: { HTTPS_PROXY: 'http://user:pw@proxy.corp:3128', NO_PROXY: 'localhost,.corp' } + }) + + expect(envHttpProxyAgentMock).toHaveBeenCalledWith({ + httpProxy: 'http://user:pw@proxy.corp:3128', + httpsProxy: 'http://user:pw@proxy.corp:3128', + noProxy: 'localhost,.corp' + }) + expect(fetchMock.mock.calls[0][1].dispatcher).toBeInstanceOf(envHttpProxyAgentMock) + expect(dispatcherCloseMock).toHaveBeenCalledTimes(1) + }) + + it("prefers Orca's configured proxy over the shell's and replaces NO_PROXY with its bypass rules", async () => { + fetchMock.mockResolvedValue(okResponse()) + + await refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: { HTTPS_PROXY: 'http://shell-proxy:8080', NO_PROXY: 'localhost' }, + networkProxySettings: { + httpProxyUrl: 'http://orca-proxy:9090', + httpProxyBypassRules: '*.internal;10.0.0.0/8' + } + }) + + expect(envHttpProxyAgentMock).toHaveBeenCalledWith({ + httpProxy: 'http://orca-proxy:9090', + httpsProxy: 'http://orca-proxy:9090', + noProxy: '*.internal,10.0.0.0/8' + }) + }) + + it('refuses to bypass a SOCKS proxy: no request, null result, warning', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - netFetchMock.mockResolvedValue({ ok: false, status: 429, json: async () => ({}) }) - expect(await refreshClaudeOauthCredentials(credentials(), NOW)).toBeNull() + + const result = await refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: { ALL_PROXY: 'socks5://proxy.corp:1080' } + }) + + expect(result).toBeNull() + expect(fetchMock).not.toHaveBeenCalled() + expect(envHttpProxyAgentMock).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledWith(expect.stringContaining('socks5: proxies are not supported')) + warn.mockRestore() + }) + + it('settles as soon as the caller aborts, without waiting for the request timeout', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const controller = new AbortController() + fetchMock.mockImplementation( + (_url: string, init: { signal: AbortSignal }) => + new Promise((_resolve, reject) => { + init.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) + }) + ) + + const pending = refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: NO_PROXY_ENV, + signal: controller.signal + }) + controller.abort() + + await expect(pending).resolves.toBeNull() + expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true) + warn.mockRestore() + }) + + it('returns null on a non-ok response, logs the status, and drains the body', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const cancel = vi.fn().mockResolvedValue(undefined) + fetchMock.mockResolvedValue({ + ok: false, + status: 429, + body: { cancel }, + json: async () => ({}) + }) + expect( + await refreshClaudeOauthCredentials(credentials(), { now: NOW, env: NO_PROXY_ENV }) + ).toBeNull() expect(warn).toHaveBeenCalledWith(expect.stringContaining('429')) + expect(cancel).toHaveBeenCalledTimes(1) warn.mockRestore() }) - it('returns null when the request throws (never rejects)', async () => { - netFetchMock.mockRejectedValue(new Error('network down')) - await expect(refreshClaudeOauthCredentials(credentials(), NOW)).resolves.toBeNull() + it('returns null when the request throws (never rejects) and still closes the dispatcher', async () => { + fetchMock.mockRejectedValue(new Error('network down')) + await expect( + refreshClaudeOauthCredentials(credentials(), { + now: NOW, + env: { HTTPS_PROXY: 'http://proxy.corp:3128' } + }) + ).resolves.toBeNull() + expect(dispatcherCloseMock).toHaveBeenCalledTimes(1) }) }) diff --git a/src/main/claude-accounts/oauth-refresh.ts b/src/main/claude-accounts/oauth-refresh.ts index cc717ef51ee8..764fb12f03d1 100644 --- a/src/main/claude-accounts/oauth-refresh.ts +++ b/src/main/claude-accounts/oauth-refresh.ts @@ -1,5 +1,9 @@ -import { net, session } from 'electron' -import { ensureElectronProxyFromEnvironment } from '../network/proxy-settings' +import { EnvHttpProxyAgent, fetch as nodeFetch, type Dispatcher } from 'undici' +import { + buildConfiguredProxyEnv, + getProxyUrlFromEnvironment, + type NetworkProxySettings +} from '../../shared/network-proxy' // Why: the OAuth client id and token endpoint are the public Claude Code // values, verified against the installed `claude` binary (2.1.177) and the @@ -113,6 +117,50 @@ export function applyRefreshedToken( return JSON.stringify(parsed) } +export type ClaudeOauthRefreshOptions = { + networkProxySettings?: NetworkProxySettings | null + env?: Record + now?: number + /** Caller cancellation; the request also carries its own timeout. */ + signal?: AbortSignal +} + +const NODE_PROXY_PROTOCOLS = new Set(['http:', 'https:']) + +type RefreshRoute = + | { kind: 'direct' } + | { kind: 'proxy'; dispatcher: Dispatcher } + /** A proxy is configured but undici cannot tunnel through it; never bypass it. */ + | { kind: 'unsupported-proxy'; protocol: string } + +/** + * Proxy for the token request, resolved the way child processes get theirs: + * Orca's configured proxy wins over the shell's, and its bypass list replaces + * NO_PROXY. + */ +function resolveRefreshRoute( + settings: NetworkProxySettings | null | undefined, + env: Record +): RefreshRoute { + const merged = { ...env, ...buildConfiguredProxyEnv(settings) } + const proxy = getProxyUrlFromEnvironment(merged) + if (!proxy.ok || !proxy.value) { + return { kind: 'direct' } + } + const protocol = new URL(proxy.value).protocol + if (!NODE_PROXY_PROTOCOLS.has(protocol)) { + return { kind: 'unsupported-proxy', protocol } + } + return { + kind: 'proxy', + dispatcher: new EnvHttpProxyAgent({ + httpProxy: proxy.value, + httpsProxy: proxy.value, + noProxy: merged.NO_PROXY ?? merged.no_proxy ?? '' + }) + } +} + /** * Refresh the OAuth token for a stored credentials blob. * @@ -123,23 +171,29 @@ export function applyRefreshedToken( */ export async function refreshClaudeOauthCredentials( credentialsJson: string, - now: number = Date.now() + options: ClaudeOauthRefreshOptions = {} ): Promise { const refreshToken = readRefreshToken(credentialsJson) if (!refreshToken) { return null } - await ensureElectronProxyFromEnvironment({ - proxySession: session.defaultSession, - probeUrl: OAUTH_TOKEN_URL - }).catch(() => {}) - + // Why: the token endpoint answers 429 to Chromium's network stack (Electron + // net.fetch) while the same request from Node succeeds (orca#18716), so the + // refresh goes through Node's stack like the `claude` CLI's own refresh. + const route = resolveRefreshRoute(options.networkProxySettings, options.env ?? process.env) + if (route.kind === 'unsupported-proxy') { + // Why: connecting directly would leave the configured egress route; keeping the old token is the safer failure. + console.warn( + `[claude-oauth-refresh] ${route.protocol} proxies are not supported for token refresh; skipping` + ) + return null + } + const dispatcher = route.kind === 'proxy' ? route.dispatcher : undefined try { // Why: the `claude` CLI posts grant_type=refresh_token as - // application/x-www-form-urlencoded with the public client id. net.fetch - // routes through Chromium's stack so the env proxy bridge above applies. - const res = await net.fetch(OAUTH_TOKEN_URL, { + // application/x-www-form-urlencoded with the public client id. + const res = await nodeFetch(OAUTH_TOKEN_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ @@ -147,7 +201,10 @@ export async function refreshClaudeOauthCredentials( refresh_token: refreshToken, client_id: OAUTH_CLIENT_ID }).toString(), - signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS) + signal: options.signal + ? AbortSignal.any([options.signal, AbortSignal.timeout(REFRESH_TIMEOUT_MS)]) + : AbortSignal.timeout(REFRESH_TIMEOUT_MS), + ...(dispatcher ? { dispatcher } : {}) }) if (!res.ok) { // Why: surface the status (never the token) so a throttle (429) or a @@ -156,15 +213,21 @@ export async function refreshClaudeOauthCredentials( // Callers keep the existing credentials on null — a transient 429 just // means the still-valid token is reused until the next attempt. console.warn(`[claude-oauth-refresh] token endpoint returned ${res.status}`) + // Why: an unread undici body can crash the process (orca#8695). + await res.body?.cancel().catch(() => {}) return null } const data = (await res.json()) as TokenEndpointResponse - return applyRefreshedToken(credentialsJson, data, now) + return applyRefreshedToken(credentialsJson, data, options.now ?? Date.now()) } catch (error) { + // Why: undici reports every transport failure as "fetch failed"; the cause carries the real error. console.warn( '[claude-oauth-refresh] token refresh request failed:', - error instanceof Error ? error.message : error + error instanceof Error ? error.message : error, + error instanceof Error && error.cause instanceof Error ? error.cause.message : '' ) return null + } finally { + await dispatcher?.close().catch(() => {}) } } diff --git a/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts b/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts index c01bcb00f6eb..538f57826a43 100644 --- a/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts +++ b/src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts @@ -16,20 +16,32 @@ import { writeManagedClaudeKeychainCredentials } from '../claude-accounts/keychain' -const { netFetchMock, readFileMock, resolveProxyMock, setProxyMock, appGetPathMock } = vi.hoisted( - () => ({ - netFetchMock: vi.fn(), - readFileMock: vi.fn(), - resolveProxyMock: vi.fn(), - setProxyMock: vi.fn(), - appGetPathMock: vi.fn() - }) -) +const { + netFetchMock, + tokenFetchMock, + readFileMock, + resolveProxyMock, + setProxyMock, + appGetPathMock +} = vi.hoisted(() => ({ + netFetchMock: vi.fn(), + tokenFetchMock: vi.fn(), + readFileMock: vi.fn(), + resolveProxyMock: vi.fn(), + setProxyMock: vi.fn(), + appGetPathMock: vi.fn() +})) vi.mock('node:fs/promises', () => ({ readFile: readFileMock })) +// Why: the OAuth refresh goes through Node's stack, not Electron's (orca#18716). +vi.mock('undici', () => ({ + fetch: tokenFetchMock, + EnvHttpProxyAgent: vi.fn() +})) + vi.mock('electron', () => ({ app: { getPath: appGetPathMock @@ -261,7 +273,7 @@ describe('fetchClaudeRateLimits', () => { mkdirSync(ownedAuthPath, { recursive: true }) writeFileSync(join(ownedAuthPath, '.orca-managed-claude-auth'), 'account-1\n', 'utf-8') vi.mocked(readManagedClaudeKeychainCredentials).mockResolvedValueOnce(staleCredentialsJson) - netFetchMock.mockResolvedValueOnce( + tokenFetchMock.mockResolvedValueOnce( new Response( JSON.stringify({ access_token: 'fresh-access', @@ -391,9 +403,9 @@ describe('fetchClaudeRateLimits', () => { 'utf-8' ) - // First net.fetch call is the OAuth refresh (token endpoint); second is the - // usage fetch with the refreshed access token. - netFetchMock.mockResolvedValueOnce({ + // The OAuth refresh (token endpoint) goes through Node fetch; the usage + // fetch with the refreshed access token still goes through net.fetch. + tokenFetchMock.mockResolvedValueOnce({ ok: true, json: async () => ({ access_token: 'fresh-access', diff --git a/src/main/rate-limits/claude-managed-account-usage.ts b/src/main/rate-limits/claude-managed-account-usage.ts index ddf7b3df7508..6899bd20bdab 100644 --- a/src/main/rate-limits/claude-managed-account-usage.ts +++ b/src/main/rate-limits/claude-managed-account-usage.ts @@ -49,7 +49,10 @@ export async function fetchInactiveClaudeAccountUsage( let token = parseClaudeOAuthCredentialsJson(credentialsJson, 'credentials-file').token if (isOauthTokenExpiring(credentialsJson)) { - const refreshed = await refreshClaudeOauthCredentials(credentialsJson) + const refreshed = await refreshClaudeOauthCredentials(credentialsJson, { + networkProxySettings: options.networkProxySettings, + signal: options.signal + }) if (options.signal?.aborted) { return abortedClaudeRateLimitResult() }