From 7921a715cd09a8b6ff039a0df24c615bfcdcfdf5 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 10 May 2026 14:27:13 -0400 Subject: [PATCH] Address auth read-back review gaps Co-authored-by: Orca --- .../runtime-auth-service.test.ts | 36 +++++++++++ .../claude-accounts/runtime-auth-service.ts | 43 +++++++++---- .../runtime-home-service.test.ts | 35 +++++++++++ .../codex-accounts/runtime-home-service.ts | 62 ++++++++----------- 4 files changed, 128 insertions(+), 48 deletions(-) diff --git a/src/main/claude-accounts/runtime-auth-service.test.ts b/src/main/claude-accounts/runtime-auth-service.test.ts index 011075247..5709e2e37 100644 --- a/src/main/claude-accounts/runtime-auth-service.test.ts +++ b/src/main/claude-accounts/runtime-auth-service.test.ts @@ -112,6 +112,16 @@ function createClaudeCredentialsJson(email: string, accessToken: string): string })}\n` } +function createClaudeCredentialsWithoutEmail(accessToken: string): string { + return `${JSON.stringify({ + claudeAiOauth: { + accessToken, + refreshToken: `${accessToken}-refresh`, + expiresAt: Date.now() + 60_000 + } + })}\n` +} + function readManagedCredentialsForTest(accountId: string, managedAuthPath: string): string | null { if (process.platform === 'darwin') { return testState.managedKeychainCredentials.get(accountId) ?? null @@ -248,4 +258,30 @@ describe('ClaudeRuntimeAuthService', () => { expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials) expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials) }) + + it('preserves unverifiable refreshed runtime credentials instead of overwriting them', async () => { + const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json') + const originalCredentials = createClaudeCredentialsWithoutEmail('original') + const refreshedCredentials = createClaudeCredentialsWithoutEmail('refreshed') + const managedAuthPath = createManagedClaudeAuth( + testState.userDataDir, + 'account-1', + originalCredentials + ) + const settings = createSettings({ + claudeManagedAccounts: [createClaudeAccount('account-1', managedAuthPath)], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + + writeFileSync(runtimeCredentialsPath, refreshedCredentials, 'utf-8') + await service.syncForCurrentSelection() + + expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(originalCredentials) + expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials) + }) }) diff --git a/src/main/claude-accounts/runtime-auth-service.ts b/src/main/claude-accounts/runtime-auth-service.ts index 7b143c597..0a3999b8b 100644 --- a/src/main/claude-accounts/runtime-auth-service.ts +++ b/src/main/claude-accounts/runtime-auth-service.ts @@ -34,6 +34,8 @@ type ClaudeAuthIdentity = { email: string | null } +type ClaudeReadBackResult = 'unchanged' | 'persisted' | 'rejected' | 'unverifiable' + export class ClaudeRuntimeAuthService { private readonly pathResolver = new ClaudeRuntimePathResolver() private mutationQueue: Promise = Promise.resolve() @@ -132,8 +134,14 @@ export class ClaudeRuntimeAuthService { // last wrote, the CLI must have refreshed — so we preserve those tokens // back to managed storage before overwriting runtime with managed state. if (this.lastSyncedAccountId === activeAccount.id) { - await this.readBackRefreshedTokens(activeAccount) - credentialsJson = (await this.readManagedCredentials(activeAccount)) ?? credentialsJson + const readBackResult = await this.readBackRefreshedTokens(activeAccount) + if (readBackResult === 'persisted') { + credentialsJson = (await this.readManagedCredentials(activeAccount)) ?? credentialsJson + } else if (readBackResult === 'unverifiable') { + this.writeRuntimeOauthAccount(this.readManagedOauthAccount(activeAccount)) + this.lastSyncedAccountId = activeAccount.id + return + } } this.writeRuntimeCredentials(credentialsJson) @@ -152,24 +160,30 @@ export class ClaudeRuntimeAuthService { this.lastWrittenCredentialsJson = null } - private async readBackRefreshedTokens(account: ClaudeManagedAccount): Promise { + private async readBackRefreshedTokens( + account: ClaudeManagedAccount + ): Promise { try { if (this.lastWrittenCredentialsJson === null) { - return + return 'unchanged' } const paths = this.pathResolver.getRuntimePaths() if (!existsSync(paths.credentialsPath)) { - return + return 'unchanged' } const runtimeContents = readFileSync(paths.credentialsPath, 'utf-8') if (runtimeContents === this.lastWrittenCredentialsJson) { - return + return 'unchanged' } - if (!this.runtimeCredentialsMatchAccount(runtimeContents, account)) { - return + const matchResult = this.runtimeCredentialsMatchAccount(runtimeContents, account) + if (matchResult === 'unverifiable') { + return 'unverifiable' + } + if (matchResult === 'mismatch') { + return 'rejected' } if (process.platform === 'darwin') { @@ -178,11 +192,13 @@ export class ClaudeRuntimeAuthService { const credentialsPath = join(account.managedAuthPath, '.credentials.json') writeFileAtomically(credentialsPath, runtimeContents, { mode: 0o600 }) } + return 'persisted' } catch (error) { // Why: read-back is best-effort. A transient fs error must not block the // forward sync path — the worst case is one more stale-token cycle, which // is strictly better than failing the entire sync. console.warn('[claude-runtime-auth] Failed to read back refreshed tokens:', error) + return 'rejected' } } @@ -210,20 +226,23 @@ export class ClaudeRuntimeAuthService { private runtimeCredentialsMatchAccount( runtimeCredentialsJson: string, account: ClaudeManagedAccount - ): boolean { + ): 'match' | 'mismatch' | 'unverifiable' { const identity = this.readIdentityFromCredentials(runtimeCredentialsJson) if (!identity) { - return false + return 'mismatch' } // Why: this mirrors the Codex runtime-home guard. If another Claude login // or missed live process rewrites shared runtime credentials, do not // persist those credentials into the selected managed account. + if (!identity.email) { + return 'unverifiable' + } if (account.email && identity.email && this.normalizeField(account.email) !== identity.email) { - return false + return 'mismatch' } - return Boolean(identity.email) + return 'match' } private readIdentityFromCredentials(credentialsJson: string): ClaudeAuthIdentity | null { diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 7d08f1721..b07e7357d 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -648,6 +648,41 @@ describe('CodexRuntimeHomeService', () => { expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(selectedAuth) }) + it('rejects same-email runtime read-back when account ids differ from sparse managed metadata', async () => { + const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json') + writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8') + const selectedAuth = createCodexAuthJson('user@example.com', 'acct-selected', 'selected') + const staleLivePtyAuth = createCodexAuthJson('user@example.com', 'acct-stale', 'stale') + const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', selectedAuth) + const managedAuthPath = join(managedHomePath, 'auth.json') + const settings = createSettings({ + codexManagedAccounts: [ + { + id: 'account-1', + email: 'user@example.com', + managedHomePath, + providerAccountId: null, + workspaceLabel: null, + workspaceAccountId: null, + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + ], + activeCodexManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + + writeFileSync(runtimeAuthPath, staleLivePtyAuth, 'utf-8') + service.syncForCurrentSelection() + + expect(readFileSync(managedAuthPath, 'utf-8')).toBe(selectedAuth) + expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(selectedAuth) + }) + it('skips read-back on first sync after restart (lastWrittenAuthJson is null)', async () => { const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json') // Pre-populate runtime with different content to simulate a CLI refresh while Orca was down diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts index b3296845c..4f768c73d 100644 --- a/src/main/codex-accounts/runtime-home-service.ts +++ b/src/main/codex-accounts/runtime-home-service.ts @@ -176,53 +176,43 @@ export class CodexRuntimeHomeService { // shared runtime home after the user switches accounts. Never persist // that write into the newly active managed account unless the auth claims // still match the account Orca believes is selected. - let hasPositiveMatch = false - if ( - activeAccount.email && - identity.email && - this.normalizeField(activeAccount.email) !== identity.email - ) { + const accountEmail = this.normalizeField(activeAccount.email) + const accountProviderId = this.normalizeField(activeAccount.providerAccountId) + const accountWorkspaceId = this.normalizeField(activeAccount.workspaceAccountId) + const emailMatches = Boolean(accountEmail && identity.email && accountEmail === identity.email) + let hasStrongIdentity = false + if (accountEmail && identity.email && accountEmail !== identity.email) { return false } - if ( - activeAccount.email && - identity.email && - this.normalizeField(activeAccount.email) === identity.email - ) { - hasPositiveMatch = true - } - if ( - activeAccount.providerAccountId && - identity.providerAccountId && - this.normalizeField(activeAccount.providerAccountId) !== identity.providerAccountId - ) { + if (!this.strongIdentityFieldsMatch(accountProviderId, identity.providerAccountId)) { return false } - if ( - activeAccount.providerAccountId && - identity.providerAccountId && - this.normalizeField(activeAccount.providerAccountId) === identity.providerAccountId - ) { - hasPositiveMatch = true + if (accountProviderId && identity.providerAccountId) { + hasStrongIdentity = true } - if ( - activeAccount.workspaceAccountId && - identity.workspaceAccountId && - this.normalizeField(activeAccount.workspaceAccountId) !== identity.workspaceAccountId - ) { + if (!this.strongIdentityFieldsMatch(accountWorkspaceId, identity.workspaceAccountId)) { return false } - if ( - activeAccount.workspaceAccountId && - identity.workspaceAccountId && - this.normalizeField(activeAccount.workspaceAccountId) === identity.workspaceAccountId - ) { - hasPositiveMatch = true + if (accountWorkspaceId && identity.workspaceAccountId) { + hasStrongIdentity = true } - return hasPositiveMatch + return ( + hasStrongIdentity || + (emailMatches && !identity.providerAccountId && !identity.workspaceAccountId) + ) + } + + private strongIdentityFieldsMatch( + accountField: string | null, + runtimeField: string | null + ): boolean { + if (!accountField && !runtimeField) { + return true + } + return Boolean(accountField && runtimeField && accountField === runtimeField) } private readIdentityFromAuthContents(contents: string): CodexAuthIdentity | null {