Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
41 changes: 41 additions & 0 deletions src/main/claude-accounts/oauth-refresh.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
applyRefreshedToken,
isOauthTokenExpiredPastGrace,
isOauthTokenExpiring,
parseClaudeOauthBlob,
readRefreshToken,
Expand Down Expand Up @@ -80,6 +81,33 @@ describe('isOauthTokenExpiring', () => {
})
})

describe('isOauthTokenExpiredPastGrace', () => {
it('is false while the token is valid or only inside the refresh buffer', () => {
expect(isOauthTokenExpiredPastGrace(credentials(), NOW)).toBe(false)
expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW + 60 * 1000 }), NOW)).toBe(
false
)
})

it('is false just after expiry, while a live Claude could still be rotating it', () => {
expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW - 60 * 1000 }), NOW)).toBe(
false
)
})

it('is true once the token has been expired for longer than the grace window', () => {
expect(
isOauthTokenExpiredPastGrace(credentials({ expiresAt: NOW - 60 * 60 * 1000 }), NOW)
).toBe(true)
})

it('is false without numeric expiry metadata, since nothing proves the token is dead', () => {
expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: undefined }), NOW)).toBe(false)
expect(isOauthTokenExpiredPastGrace(credentials({ expiresAt: 'soon' }), NOW)).toBe(false)
expect(isOauthTokenExpiredPastGrace('{}', NOW)).toBe(false)
})
})

describe('applyRefreshedToken', () => {
it('rotates access + refresh token and recomputes expiry', () => {
const updated = applyRefreshedToken(
Expand Down Expand Up @@ -171,6 +199,19 @@ describe('refreshClaudeOauthCredentials', () => {
expect(oauth.refreshToken).toBe('fresh-refresh')
})

it('identifies itself with a non-browser User-Agent', async () => {
// Why: the token endpoint answers 429 to the Chromium User-Agent net.fetch sends by default.
netFetchMock.mockResolvedValue({
ok: true,
json: async () => ({ access_token: 'fresh-access', expires_in: 3600 })
})

await refreshClaudeOauthCredentials(credentials(), NOW)

const [, init] = netFetchMock.mock.calls[0]
expect(init.headers['User-Agent']).toBe('orca-desktop')
})

it('returns null on a non-ok response and logs the status for diagnosability', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
netFetchMock.mockResolvedValue({ ok: false, status: 429, json: async () => ({}) })
Expand Down
27 changes: 26 additions & 1 deletion src/main/claude-accounts/oauth-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,16 @@ import { ensureElectronProxyFromEnvironment } from '../network/proxy-settings'
// after the CLI rotates it (the lossy path that strands stale tokens).
const OAUTH_TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'
const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'
// Why: the token endpoint answers 429 to net.fetch's default Chromium User-Agent
// (and to curl's) whatever the body, so a refresh without one never succeeds.
const OAUTH_REFRESH_USER_AGENT = 'orca-desktop'

// Refresh slightly ahead of expiry so a token doesn't expire mid-launch. The
// CLI uses the same 5-minute skew for its own refresh decision.
const OAUTH_EXPIRY_BUFFER_MS = 5 * 60 * 1000
// A CLI using the token refreshes it ahead of expiry, so a token still expired
// this long after expiresAt has no live CLI rotating it.
const OAUTH_LIVE_ROTATION_GRACE_MS = 10 * 60 * 1000
const REFRESH_TIMEOUT_MS = 10_000

type ClaudeOauthBlob = {
Expand Down Expand Up @@ -74,6 +80,22 @@ export function isOauthTokenExpiring(credentialsJson: string, now: number = Date
return now + OAUTH_EXPIRY_BUFFER_MS >= expiresAt
}

/**
* Whether the stored access token expired longer ago than a live Claude CLI
* would have left it unrotated. Unlike isOauthTokenExpiring, missing expiry
* metadata is false: only a known-dead token may override the live-PTY gate.
*/
export function isOauthTokenExpiredPastGrace(
credentialsJson: string,
now: number = Date.now()
): boolean {
const expiresAt = parseClaudeOauthBlob(credentialsJson)?.expiresAt
if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) {
return false
}
return now >= expiresAt + OAUTH_LIVE_ROTATION_GRACE_MS
}

/**
* Merge a token-endpoint response into the stored credentials, returning the
* updated credentials JSON. Preserves every field the caller already had
Expand Down Expand Up @@ -141,7 +163,10 @@ export async function refreshClaudeOauthCredentials(
// routes through Chromium's stack so the env proxy bridge above applies.
const res = await net.fetch(OAUTH_TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': OAUTH_REFRESH_USER_AGENT
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
Expand Down
216 changes: 212 additions & 4 deletions src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import {
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { isOauthTokenExpiring, refreshClaudeOauthCredentials } from './oauth-refresh'
import {
isOauthTokenExpiredPastGrace,
isOauthTokenExpiring,
refreshClaudeOauthCredentials
} from './oauth-refresh'

vi.mock('electron', () => createElectronMock())

Expand Down Expand Up @@ -173,9 +177,9 @@ describe('ClaudeRuntimeAuthService', () => {
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null)
})

it('does not refresh the active account while a Claude PTY is live', async () => {
const expired = createClaudeCredentialsJson('one@example.com', 'one-expired', null, 1_000)
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired)
it('does not refresh the active account while a Claude PTY is live and the token is only expiring', async () => {
const expiring = createClaudeCredentialsJson('one@example.com', 'one-expiring')
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expiring)
const settings = createSettings({
claudeManagedAccounts: [
createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' })
Expand Down Expand Up @@ -207,6 +211,210 @@ describe('ClaudeRuntimeAuthService', () => {
}
})

it('refreshes the active account despite a live Claude PTY once the token is expired past the grace window', async () => {
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
const expired = createClaudeCredentialsJson(
'one@example.com',
'one-expired',
null,
Date.now() - 60 * 60 * 1000
)
const refreshedCreds = createClaudeCredentialsJson(
'one@example.com',
'one-refreshed',
null,
Date.now() + 8 * 60 * 60 * 1000
)
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired)
const settings = createSettings({
claudeManagedAccounts: [
createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' })
],
activeClaudeManagedAccountId: 'account-1'
})
const store = createStore(settings)

vi.mocked(isOauthTokenExpiring).mockReturnValue(true)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true)
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(refreshedCreds)

const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate')
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
const service = new ClaudeRuntimeAuthService(store as never)

// The live Claude runs on another config dir (nothing lands in ~/.claude), so read-back
// never sees a rotation — the setup where the deferral used to last forever (#20251).
markClaudePtySpawned('pty-live-1')
try {
const preparation = await service.prepareForRateLimitFetch()
expect(refreshClaudeOauthCredentials).toHaveBeenCalled()
expect(preparation.managedRefreshDeferredByLivePty).toBe(false)
expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(refreshedCreds)
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCreds)
} finally {
markClaudePtyExited('pty-live-1')
vi.mocked(isOauthTokenExpiring).mockReturnValue(false)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false)
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null)
}
})

it('keeps a live Claude rotation that lands while a past-grace refresh fails', async () => {
const expired = createClaudeCredentialsJson(
'one@example.com',
'one-expired',
null,
Date.now() - 60 * 60 * 1000
)
const cliRotated = createClaudeCredentialsJson(
'one@example.com',
'cli-rotated',
null,
Date.now() + 8 * 60 * 60 * 1000
)
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired)
const settings = createSettings({
claudeManagedAccounts: [
createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' })
],
activeClaudeManagedAccountId: 'account-1'
})
const store = createStore(settings)

vi.mocked(isOauthTokenExpiring).mockReturnValue(true)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true)

const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate')
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')

markClaudePtySpawned('pty-live-1')
try {
const service = new ClaudeRuntimeAuthService(store as never)
await service.syncForCurrentSelection()
expect(testState.legacyKeychainCredentials).toBe(expired)

// A Claude on Orca's store wins the single-use refresh while Orca's request is in
// flight, so Orca's request fails; rewriting the stale blob would strand both copies.
vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => {
testState.legacyKeychainCredentials = cliRotated
return null
})
await service.syncForCurrentSelection()

expect(testState.legacyKeychainCredentials).toBe(cliRotated)
expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(cliRotated)
} finally {
markClaudePtyExited('pty-live-1')
vi.mocked(isOauthTokenExpiring).mockReturnValue(false)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false)
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null)
}
})

it('does not rewrite the runtime after a failed past-grace refresh when read-back cannot see a rotation yet', async () => {
const expired = createClaudeCredentialsJson(
'one@example.com',
'one-expired',
null,
Date.now() - 60 * 60 * 1000
)
const cliRotated = createClaudeCredentialsJson(
'one@example.com',
'cli-rotated',
null,
Date.now() + 8 * 60 * 60 * 1000
)
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired)
const settings = createSettings({
claudeManagedAccounts: [
createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' })
],
activeClaudeManagedAccountId: 'account-1'
})
const store = createStore(settings)

vi.mocked(isOauthTokenExpiring).mockReturnValue(true)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true)

const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate')
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')

markClaudePtySpawned('pty-live-1')
try {
const service = new ClaudeRuntimeAuthService(store as never)
await service.syncForCurrentSelection()

// The Claude's keychain write is still in flight (reads fail) when Orca re-reads
// after its own refresh fails, so read-back reports 'unchanged'.
vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => {
testState.legacyKeychainCredentials = cliRotated
testState.throwLegacyKeychainRead = true
testState.throwScopedKeychainRead = true
return null
})
await service.syncForCurrentSelection()

expect(testState.legacyKeychainCredentials).toBe(cliRotated)
} finally {
markClaudePtyExited('pty-live-1')
vi.mocked(isOauthTokenExpiring).mockReturnValue(false)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false)
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null)
}
})

it('keeps a live Claude rotation that lands during the first sync after launch', async () => {
const expired = createClaudeCredentialsJson(
'one@example.com',
'one-expired',
null,
Date.now() - 60 * 60 * 1000
)
const cliRotated = createClaudeCredentialsJson(
'one@example.com',
'cli-rotated',
null,
Date.now() + 8 * 60 * 60 * 1000
)
const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired)
const settings = createSettings({
claudeManagedAccounts: [
createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' })
],
activeClaudeManagedAccountId: 'account-1'
})
const store = createStore(settings)
// The previous run materialized this account, and its Claude pane outlived the restart
// in the daemon. Nothing has been written this run, so lastWrittenCredentialsJson is null.
writeFileSync(join(testState.fakeHomeDir, '.claude', '.credentials.json'), expired, 'utf-8')
testState.scopedKeychainCredentials = expired
testState.legacyKeychainCredentials = expired

vi.mocked(isOauthTokenExpiring).mockReturnValue(true)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(true)
vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => {
testState.legacyKeychainCredentials = cliRotated
return null
})

const { markClaudePtySpawned, markClaudePtyExited } = await import('./live-pty-gate')
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')

markClaudePtySpawned('pty-live-1')
try {
const service = new ClaudeRuntimeAuthService(store as never)
await service.syncForCurrentSelection()

expect(testState.legacyKeychainCredentials).toBe(cliRotated)
expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(cliRotated)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} finally {
markClaudePtyExited('pty-live-1')
vi.mocked(isOauthTokenExpiring).mockReturnValue(false)
vi.mocked(isOauthTokenExpiredPastGrace).mockReturnValue(false)
vi.mocked(refreshClaudeOauthCredentials).mockResolvedValue(null)
}
})

it('adopts a rotated-refresh-token runtime credential on cold-start read-back', async () => {
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
// Same expiry on both sides (cold start), but the runtime refresh token has
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export function createElectronMock() {
export function createOauthRefreshMock() {
return {
isOauthTokenExpiring: vi.fn(() => false),
isOauthTokenExpiredPastGrace: vi.fn(() => false),
refreshClaudeOauthCredentials: vi.fn(async () => null)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ export class ClaudeRuntimeAuthManagedCredentials extends ClaudeRuntimeAuthCreden
* managed storage. Returns the refreshed credentials JSON, or null when no
* refresh happened (token valid, no refresh token, or network failure).
*
* Caller guarantees this account isn't the live/active one and runs inside the
* serialized mutation queue, so the single-use refresh token can't rotate concurrently.
* Caller runs inside the serialized mutation queue, so Orca can't rotate the
* single-use refresh token concurrently; runtime-auth-sync.ts owns the live-PTY gate.
*/
protected async refreshManagedAccountTokenIfNeeded(
account: ClaudeManagedAccount,
Expand Down
Loading