diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 3a2f407e6..bd9c07ea8 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -132,6 +132,32 @@ function createManagedAuth(rootDir: string, accountId: string, auth: string): st return managedHomePath } +function encodeJwtPart(value: Record): string { + return Buffer.from(JSON.stringify(value)).toString('base64url') +} + +function createCodexAuthJson(email: string, accountId: string, refreshToken: string): string { + const idToken = [ + encodeJwtPart({ alg: 'none', typ: 'JWT' }), + encodeJwtPart({ + email, + 'https://api.openai.com/auth': { + chatgpt_account_id: accountId, + workspace_account_id: accountId + } + }), + '' + ].join('.') + + return `${JSON.stringify({ + tokens: { + id_token: idToken, + account_id: accountId, + refresh_token: refreshToken + } + })}\n` +} + describe('CodexRuntimeHomeService', () => { beforeEach(() => { vi.resetModules() @@ -510,11 +536,9 @@ describe('CodexRuntimeHomeService', () => { it('reads back CLI-refreshed tokens into managed storage on subsequent sync', async () => { const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json') writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8') - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - '{"tokens":"original"}\n' - ) + const originalAuth = createCodexAuthJson('user@example.com', 'acct-1', 'original') + const refreshedAuth = createCodexAuthJson('user@example.com', 'acct-1', 'refreshed') + const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', originalAuth) const managedAuthPath = join(managedHomePath, 'auth.json') const settings = createSettings({ codexManagedAccounts: [ @@ -522,9 +546,9 @@ describe('CodexRuntimeHomeService', () => { id: 'account-1', email: 'user@example.com', managedHomePath, - providerAccountId: null, + providerAccountId: 'acct-1', workspaceLabel: null, - workspaceAccountId: null, + workspaceAccountId: 'acct-1', createdAt: 1, updatedAt: 1, lastAuthenticatedAt: 1 @@ -538,13 +562,50 @@ describe('CodexRuntimeHomeService', () => { const service = new CodexRuntimeHomeService(store as never) // Simulate CLI refreshing the token in ~/.codex/auth.json - writeFileSync(runtimeAuthPath, '{"tokens":"refreshed"}\n', 'utf-8') + writeFileSync(runtimeAuthPath, refreshedAuth, 'utf-8') // Next sync should read back the refreshed token to managed storage service.syncForCurrentSelection() - expect(readFileSync(managedAuthPath, 'utf-8')).toBe('{"tokens":"refreshed"}\n') - expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"refreshed"}\n') + expect(readFileSync(managedAuthPath, 'utf-8')).toBe(refreshedAuth) + expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(refreshedAuth) + }) + + it('rejects runtime read-back from a different Codex identity', async () => { + const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json') + writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8') + const selectedAuth = createCodexAuthJson('selected@example.com', 'acct-selected', 'selected') + const staleLivePtyAuth = createCodexAuthJson('stale@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: 'selected@example.com', + managedHomePath, + providerAccountId: 'acct-selected', + workspaceLabel: null, + workspaceAccountId: 'acct-selected', + 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) + + // Simulate an old live Codex PTY from another account refreshing the + // shared runtime auth after Orca has already selected account-1. + 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 () => { diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts index 3ec95ecfa..06f5023e7 100644 --- a/src/main/codex-accounts/runtime-home-service.ts +++ b/src/main/codex-accounts/runtime-home-service.ts @@ -18,6 +18,12 @@ import type { CodexManagedAccount } from '../../shared/types' import type { Store } from '../persistence' import { writeFileAtomically } from './fs-utils' +type CodexAuthIdentity = { + email: string | null + providerAccountId: string | null + workspaceAccountId: string | null +} + export class CodexRuntimeHomeService { // Why: tracks whether auth.json is currently managed by Orca. When null, // Orca does NOT own auth.json and must not overwrite external changes @@ -92,7 +98,7 @@ export class CodexRuntimeHomeService { // 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) { - this.readBackRefreshedTokens(activeAuthPath) + this.readBackRefreshedTokens(activeAccount, activeAuthPath) } this.lastSyncedAccountId = activeAccount.id @@ -107,7 +113,10 @@ export class CodexRuntimeHomeService { this.lastWrittenAuthJson = null } - private readBackRefreshedTokens(managedAuthPath: string): void { + private readBackRefreshedTokens( + activeAccount: CodexManagedAccount, + managedAuthPath: string + ): void { try { const runtimeAuthPath = this.getRuntimeAuthPath() if (!existsSync(runtimeAuthPath)) { @@ -123,6 +132,10 @@ export class CodexRuntimeHomeService { return } + if (!this.runtimeAuthMatchesAccount(runtimeContents, activeAccount)) { + return + } + writeFileAtomically(managedAuthPath, runtimeContents, { mode: 0o600 }) } catch (error) { // Why: read-back is best-effort. A transient fs error must not block the @@ -150,6 +163,124 @@ export class CodexRuntimeHomeService { return accounts.find((account) => account.id === activeAccountId) ?? null } + private runtimeAuthMatchesAccount( + runtimeAuthContents: string, + activeAccount: CodexManagedAccount + ): boolean { + const identity = this.readIdentityFromAuthContents(runtimeAuthContents) + if (!identity) { + return false + } + + // Why: old live Codex PTYs can still write refreshed tokens into the + // 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. + if ( + activeAccount.email && + identity.email && + this.normalizeField(activeAccount.email) !== identity.email + ) { + return false + } + + if ( + activeAccount.providerAccountId && + identity.providerAccountId && + this.normalizeField(activeAccount.providerAccountId) !== identity.providerAccountId + ) { + return false + } + + if ( + activeAccount.workspaceAccountId && + identity.workspaceAccountId && + this.normalizeField(activeAccount.workspaceAccountId) !== identity.workspaceAccountId + ) { + return false + } + + return Boolean(identity.email || identity.providerAccountId || identity.workspaceAccountId) + } + + private readIdentityFromAuthContents(contents: string): CodexAuthIdentity | null { + let raw: Record + try { + raw = JSON.parse(contents) as Record + } catch { + return null + } + + const tokens = this.readRecordClaim(raw, 'tokens') + const idToken = this.normalizeField( + this.readStringClaim(tokens, 'id_token') ?? this.readStringClaim(tokens, 'idToken') + ) + const payload = idToken ? this.parseJwtPayload(idToken) : null + const authClaims = this.readRecordClaim(payload, 'https://api.openai.com/auth') + const profileClaims = this.readRecordClaim(payload, 'https://api.openai.com/profile') + + return { + email: this.normalizeField( + this.readStringClaim(payload, 'email') ?? this.readStringClaim(profileClaims, 'email') + ), + providerAccountId: this.normalizeField( + this.readStringClaim(tokens, 'account_id') ?? + this.readStringClaim(tokens, 'accountId') ?? + this.readStringClaim(authClaims, 'chatgpt_account_id') ?? + this.readStringClaim(payload, 'chatgpt_account_id') + ), + workspaceAccountId: this.normalizeField( + this.readStringClaim(authClaims, 'workspace_account_id') ?? + this.readStringClaim(tokens, 'account_id') ?? + this.readStringClaim(tokens, 'accountId') ?? + this.readStringClaim(payload, 'chatgpt_account_id') + ) + } + } + + private parseJwtPayload(token: string): Record | null { + const parts = token.split('.') + if (parts.length < 2) { + return null + } + + let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/') + while (payload.length % 4 !== 0) { + payload += '=' + } + + try { + const json = Buffer.from(payload, 'base64').toString('utf-8') + return JSON.parse(json) as Record + } catch { + return null + } + } + + private readRecordClaim( + value: Record | null, + key: string + ): Record | null { + const claim = value?.[key] + if (!claim || typeof claim !== 'object' || Array.isArray(claim)) { + return null + } + return claim as Record + } + + private readStringClaim(value: Record | null, key: string): string | null { + const claim = value?.[key] + return typeof claim === 'string' ? claim : null + } + + private normalizeField(value: string | null | undefined): string | null { + if (!value) { + return null + } + const trimmed = value.trim() + return trimmed === '' ? null : trimmed + } + private safeMigrateLegacyManagedState(): void { try { this.migrateLegacyManagedStateIfNeeded()