Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

164 changes: 138 additions & 26 deletions src/main/claude-accounts/oauth-refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -127,60 +135,164 @@ 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<Record<string, unknown>> } {
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')
const body = new URLSearchParams(init.body)
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)
})
})
91 changes: 77 additions & 14 deletions src/main/claude-accounts/oauth-refresh.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -113,6 +117,50 @@ export function applyRefreshedToken(
return JSON.stringify(parsed)
}

export type ClaudeOauthRefreshOptions = {
networkProxySettings?: NetworkProxySettings | null
env?: Record<string, string | undefined>
now?: number
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/** 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<string, string | undefined>
): 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.
*
Expand All @@ -123,31 +171,40 @@ export function applyRefreshedToken(
*/
export async function refreshClaudeOauthCredentials(
credentialsJson: string,
now: number = Date.now()
options: ClaudeOauthRefreshOptions = {}
): Promise<string | null> {
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({
grant_type: 'refresh_token',
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
Expand All @@ -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}`)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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(() => {})
}
}
Loading