diff --git a/src/main/claude-accounts/oauth-refresh.test.ts b/src/main/claude-accounts/oauth-refresh.test.ts index dd5e01c245a5..05c43d0f54fb 100644 --- a/src/main/claude-accounts/oauth-refresh.test.ts +++ b/src/main/claude-accounts/oauth-refresh.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { applyRefreshedToken, + isOauthTokenExpiredPastGrace, isOauthTokenExpiring, parseClaudeOauthBlob, readRefreshToken, @@ -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( @@ -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 () => ({}) }) diff --git a/src/main/claude-accounts/oauth-refresh.ts b/src/main/claude-accounts/oauth-refresh.ts index cc717ef51ee8..bbebc0cbda9e 100644 --- a/src/main/claude-accounts/oauth-refresh.ts +++ b/src/main/claude-accounts/oauth-refresh.ts @@ -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 = { @@ -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 @@ -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, diff --git a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts index 85d68d30e8b8..f1978b151dbd 100644 --- a/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts +++ b/src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts @@ -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()) @@ -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' }) @@ -207,6 +211,270 @@ 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('re-materializes the active account when the post-failure read-back adopts another account', async () => { + const expired = createClaudeCredentialsJson( + 'one@example.com', + 'one-expired', + null, + Date.now() - 60 * 60 * 1000 + ) + const twoRotated = createClaudeCredentialsJson( + 'two@example.com', + 'two-rotated', + null, + Date.now() + 8 * 60 * 60 * 1000 + ) + const managedAuthPath1 = createManagedClaudeAuth(testState.userDataDir, 'account-1', expired) + const managedAuthPath2 = createManagedClaudeAuth( + testState.userDataDir, + 'account-2', + createClaudeCredentialsJson('two@example.com', 'two-old', null, Date.now() - 60_000) + ) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath1, { email: 'one@example.com' }), + createClaudeAccount('account-2', managedAuthPath2, { email: 'two@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() + + // A Claude signed in as account-2 rotates its token into the shared runtime while + // account-1's refresh is in flight; read-back rightly saves it to account-2. + vi.mocked(refreshClaudeOauthCredentials).mockImplementationOnce(async () => { + testState.legacyKeychainCredentials = twoRotated + return null + }) + await service.syncForCurrentSelection() + + expect(readManagedCredentialsForTest('account-2', managedAuthPath2)).toBe(twoRotated) + expect(testState.legacyKeychainCredentials).toBe(expired) + expect( + readFileSync(join(testState.fakeHomeDir, '.claude', '.credentials.json'), 'utf-8') + ).toBe(expired) + } 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) + } 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 diff --git a/src/main/claude-accounts/runtime-auth-service-test-harness.ts b/src/main/claude-accounts/runtime-auth-service-test-harness.ts index 874e7534ff1a..fa22c721b8df 100644 --- a/src/main/claude-accounts/runtime-auth-service-test-harness.ts +++ b/src/main/claude-accounts/runtime-auth-service-test-harness.ts @@ -42,6 +42,7 @@ export function createElectronMock() { export function createOauthRefreshMock() { return { isOauthTokenExpiring: vi.fn(() => false), + isOauthTokenExpiredPastGrace: vi.fn(() => false), refreshClaudeOauthCredentials: vi.fn(async () => null) } } diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts index ad68d59eadb7..a95d491182e1 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts @@ -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, diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts index f191689a4466..1472cbf7d157 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts @@ -7,7 +7,7 @@ import { type ClaudeAccountSelectionTarget } from '../runtime-selection' import { hasLiveClaudePtys } from '../live-pty-gate' -import { isOauthTokenExpiring } from '../oauth-refresh' +import { isOauthTokenExpiredPastGrace, isOauthTokenExpiring } from '../oauth-refresh' import { writeActiveClaudeKeychainCredentialsForRuntime } from '../keychain' import { ClaudeRuntimeAuthPreparationService } from './runtime-auth-preparation' @@ -242,17 +242,35 @@ export class ClaudeRuntimeAuthSync extends ClaudeRuntimeAuthPreparationService { } // Why: rotate+persist the single-use token to managed storage before materializing (else runtime gets a stale token that fails invalid_grant); skip while a live PTY owns the creds since refreshing would double-rotate it (invalidating one copy) — read-back preserves its refresh instead. + // Why: stop deferring once the token is dead past the grace window — a live Claude using this store would have rotated it by now (read-back adopts that), so it runs on another config dir and the wait never ends. const liveClaudePtys = hasLiveClaudePtys() - if (liveClaudePtys && isOauthTokenExpiring(credentialsJson)) { + const deferToLiveClaude = liveClaudePtys && !isOauthTokenExpiredPastGrace(credentialsJson) + if (deferToLiveClaude && isOauthTokenExpiring(credentialsJson)) { this.managedRefreshDeferredByLivePtyAccountId = activeAccount.id } - if (!liveClaudePtys) { + if (!deferToLiveClaude) { const refreshed = await this.refreshManagedAccountTokenIfNeeded( activeAccount, credentialsJson ) if (refreshed) { credentialsJson = refreshed + } else if (liveClaudePtys && this.lastSyncedAccountId === activeAccount.id) { + // Why: a live Claude may have rotated the runtime token while our refresh was in flight (even on the first sync, before lastWrittenCredentialsJson exists); adopt it or leave it rather than rewrite the stale blob over it. Only a wiped runtime, a rotation read-back filed under another account, or a first sync with nothing to compare against falls through to materialize. + const readBackResult = await this.readBackRefreshedTokens(credentialsJson, { + updateLastWrittenCredentialsJson: true + }) + if ( + (readBackResult.status === 'persisted' && + (await this.readManagedCredentials(activeAccount)) !== credentialsJson) || + (readBackResult.status === 'rejected' && + readBackResult.hasValidChangedRuntimeCredentials) || + (readBackResult.status === 'unchanged' && + credentialsJson === this.lastWrittenCredentialsJson) + ) { + this.hasMaterializedRuntimeAuth = true + return + } } } 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..3042811317f5 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 @@ -422,4 +422,48 @@ describe('fetchClaudeRateLimits', () => { ) expect(usageCall?.[1]?.headers?.Authorization).toBe('Bearer fresh-access') }) + + it('persists a rotated inactive account token even when the fetch is aborted mid-refresh', async () => { + setPlatform('linux') + tempDir = mkdtempSync(join(tmpdir(), 'orca-claude-fetcher-')) + appGetPathMock.mockReturnValue(tempDir) + const ownedAuthPath = join(tempDir, 'claude-accounts', 'account-1', 'auth') + mkdirSync(ownedAuthPath, { recursive: true }) + writeFileSync(join(ownedAuthPath, '.orca-managed-claude-auth'), 'account-1\n', 'utf-8') + const credentialsPath = join(ownedAuthPath, '.credentials.json') + writeFileSync( + credentialsPath, + JSON.stringify({ + claudeAiOauth: { + accessToken: 'stale-access', + refreshToken: 'stale-refresh', + expiresAt: Date.now() - 60_000 + } + }), + 'utf-8' + ) + const controller = new AbortController() + // The server has already consumed the single-use refresh token by the time the + // abort (e.g. app quit) lands, so dropping the rotation would strand the account. + netFetchMock.mockImplementationOnce(async () => { + controller.abort() + return { + ok: true, + json: async () => ({ + access_token: 'fresh-access', + expires_in: 3600, + refresh_token: 'fresh-refresh' + }) + } + }) + + const result = await fetchManagedAccountUsage( + { id: 'account-1', managedAuthPath: ownedAuthPath }, + { signal: controller.signal } + ) + + expect(result.status).not.toBe('ok') + const persisted = JSON.parse(readFileSync(credentialsPath, 'utf-8')) + expect(persisted.claudeAiOauth.refreshToken).toBe('fresh-refresh') + }) }) diff --git a/src/main/rate-limits/claude-managed-account-usage.ts b/src/main/rate-limits/claude-managed-account-usage.ts index ddf7b3df7508..80b9992e0073 100644 --- a/src/main/rate-limits/claude-managed-account-usage.ts +++ b/src/main/rate-limits/claude-managed-account-usage.ts @@ -50,10 +50,8 @@ export async function fetchInactiveClaudeAccountUsage( let token = parseClaudeOAuthCredentialsJson(credentialsJson, 'credentials-file').token if (isOauthTokenExpiring(credentialsJson)) { const refreshed = await refreshClaudeOauthCredentials(credentialsJson) - if (options.signal?.aborted) { - return abortedClaudeRateLimitResult() - } if (refreshed) { + // Why: the server consumed the single-use refresh token already, so persist before honoring an abort. try { await writeClaudeManagedCredentialsJson(location, refreshed) } catch { @@ -62,6 +60,9 @@ export async function fetchInactiveClaudeAccountUsage( credentialsJson = refreshed token = parseClaudeOAuthCredentialsJson(refreshed, 'credentials-file').token } + if (options.signal?.aborted) { + return abortedClaudeRateLimitResult() + } } if (!token) {