Harden managed auth read-back state machine
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable max-lines -- test suite covers Claude runtime auth refresh, identity guards, and snapshot restore cases */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
chmodSync,
|
||||
@@ -6,6 +7,7 @@ import {
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
@@ -77,17 +79,22 @@ function createStore(settings: GlobalSettings) {
|
||||
function createManagedClaudeAuth(
|
||||
rootDir: string,
|
||||
accountId: string,
|
||||
credentialsJson: string
|
||||
credentialsJson: string,
|
||||
oauthAccountJson = `{"accountUuid":"${accountId}"}\n`
|
||||
): string {
|
||||
const managedAuthPath = join(rootDir, 'claude-accounts', accountId, 'auth')
|
||||
mkdirSync(managedAuthPath, { recursive: true })
|
||||
writeFileSync(join(managedAuthPath, '.credentials.json'), credentialsJson, 'utf-8')
|
||||
writeFileSync(join(managedAuthPath, 'oauth-account.json'), `{"accountUuid":"${accountId}"}\n`)
|
||||
writeFileSync(join(managedAuthPath, 'oauth-account.json'), oauthAccountJson, 'utf-8')
|
||||
testState.managedKeychainCredentials.set(accountId, credentialsJson)
|
||||
return managedAuthPath
|
||||
}
|
||||
|
||||
function createClaudeAccount(id: string, managedAuthPath: string): ClaudeManagedAccount {
|
||||
function createClaudeAccount(
|
||||
id: string,
|
||||
managedAuthPath: string,
|
||||
overrides: Partial<ClaudeManagedAccount> = {}
|
||||
): ClaudeManagedAccount {
|
||||
return {
|
||||
id,
|
||||
email: 'user@example.com',
|
||||
@@ -97,14 +104,20 @@ function createClaudeAccount(id: string, managedAuthPath: string): ClaudeManaged
|
||||
organizationName: null,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
lastAuthenticatedAt: 1
|
||||
lastAuthenticatedAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function createClaudeCredentialsJson(email: string, accessToken: string): string {
|
||||
function createClaudeCredentialsJson(
|
||||
email: string,
|
||||
accessToken: string,
|
||||
organizationUuid: string | null = null
|
||||
): string {
|
||||
return `${JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
email,
|
||||
...(organizationUuid ? { organizationUuid } : {}),
|
||||
accessToken,
|
||||
refreshToken: `${accessToken}-refresh`,
|
||||
expiresAt: Date.now() + 60_000
|
||||
@@ -112,9 +125,13 @@ function createClaudeCredentialsJson(email: string, accessToken: string): string
|
||||
})}\n`
|
||||
}
|
||||
|
||||
function createClaudeCredentialsWithoutEmail(accessToken: string): string {
|
||||
function createClaudeCredentialsWithoutEmail(
|
||||
accessToken: string,
|
||||
organizationUuid: string | null = null
|
||||
): string {
|
||||
return `${JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
...(organizationUuid ? { organizationUuid } : {}),
|
||||
accessToken,
|
||||
refreshToken: `${accessToken}-refresh`,
|
||||
expiresAt: Date.now() + 60_000
|
||||
@@ -207,6 +224,32 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe('{"token":"rotated"}\n')
|
||||
})
|
||||
|
||||
it('tightens credential file permissions when unchanged content is already present', async () => {
|
||||
if (process.platform === 'win32') {
|
||||
return
|
||||
}
|
||||
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
'{"token":"managed"}\n'
|
||||
)
|
||||
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()
|
||||
chmodSync(runtimeCredentialsPath, 0o644)
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(statSync(runtimeCredentialsPath).mode & 0o777).toBe(0o600)
|
||||
})
|
||||
|
||||
it('reads back refreshed credentials when the Claude identity still matches', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original')
|
||||
@@ -259,7 +302,116 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
|
||||
it('preserves unverifiable refreshed runtime credentials instead of overwriting them', async () => {
|
||||
it('rejects runtime read-back from the same Claude email in a different organization', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const selectedCredentials = createClaudeCredentialsJson('user@example.com', 'selected', 'org-b')
|
||||
const staleCredentials = createClaudeCredentialsJson('user@example.com', 'stale', 'org-a')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
selectedCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, { organizationUuid: 'org-b' })
|
||||
],
|
||||
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, staleCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
|
||||
it('rejects same-email Claude read-back using stored managed organization identity', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const selectedCredentials = createClaudeCredentialsJson('user@example.com', 'selected', 'org-b')
|
||||
const staleCredentials = createClaudeCredentialsJson('user@example.com', 'stale', 'org-a')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
selectedCredentials
|
||||
)
|
||||
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, staleCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
|
||||
it('rejects same-email Claude read-back using stored oauth-account organization identity', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const selectedCredentials = createClaudeCredentialsJson('user@example.com', 'selected')
|
||||
const staleCredentials = createClaudeCredentialsJson('user@example.com', 'stale', 'org-a')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
selectedCredentials,
|
||||
'{"organizationUuid":"org-b"}\n'
|
||||
)
|
||||
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, staleCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
|
||||
it('rejects no-email Claude read-back when organization identity conflicts', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const selectedCredentials = createClaudeCredentialsJson('user@example.com', 'selected', 'org-b')
|
||||
const staleCredentials = createClaudeCredentialsWithoutEmail('stale', 'org-a')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
selectedCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, { organizationUuid: 'org-b' })
|
||||
],
|
||||
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, staleCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
|
||||
it('rejects unverifiable refreshed runtime credentials', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsWithoutEmail('original')
|
||||
const refreshedCredentials = createClaudeCredentialsWithoutEmail('refreshed')
|
||||
@@ -280,8 +432,319 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
|
||||
writeFileSync(runtimeCredentialsPath, refreshedCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(originalCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(originalCredentials)
|
||||
})
|
||||
|
||||
it('restores the system default after rejecting unverifiable managed credentials', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials = createClaudeCredentialsJson('system@example.com', 'system')
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials, 'utf-8')
|
||||
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()
|
||||
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(systemCredentials)
|
||||
})
|
||||
|
||||
it('restores system default after same-identity managed Claude refresh on deselect', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials = createClaudeCredentialsJson('system@example.com', 'system')
|
||||
const managedCredentials = createClaudeCredentialsJson('user@example.com', 'managed', 'org-1')
|
||||
const externalCredentials = createClaudeCredentialsJson('user@example.com', 'external', 'org-1')
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials, 'utf-8')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
managedCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, {
|
||||
organizationUuid: 'org-1'
|
||||
})
|
||||
],
|
||||
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, externalCredentials, 'utf-8')
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(externalCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(systemCredentials)
|
||||
})
|
||||
|
||||
it('restores system default when stale Claude credentials are rejected on deselect', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials = createClaudeCredentialsJson('system@example.com', 'system')
|
||||
const selectedCredentials = createClaudeCredentialsJson('selected@example.com', 'selected')
|
||||
const staleCredentials = createClaudeCredentialsJson('stale@example.com', 'stale')
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials, 'utf-8')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
selectedCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, { email: 'selected@example.com' })
|
||||
],
|
||||
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, staleCredentials, 'utf-8')
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(systemCredentials)
|
||||
})
|
||||
|
||||
it('does not persist unverifiable stale Claude credentials into another active account', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const account1Credentials = createClaudeCredentialsJson('one@example.com', 'one')
|
||||
const account2Credentials = createClaudeCredentialsJson('two@example.com', 'two')
|
||||
const staleUnverifiableCredentials = createClaudeCredentialsWithoutEmail('stale')
|
||||
const managedAuthPath1 = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
account1Credentials
|
||||
)
|
||||
const managedAuthPath2 = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-2',
|
||||
account2Credentials
|
||||
)
|
||||
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)
|
||||
|
||||
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
|
||||
const service = new ClaudeRuntimeAuthService(store as never)
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
settings.activeClaudeManagedAccountId = 'account-2'
|
||||
await service.syncForCurrentSelection()
|
||||
writeFileSync(runtimeCredentialsPath, staleUnverifiableCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-2', managedAuthPath2)).toBe(account2Credentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(account2Credentials)
|
||||
})
|
||||
|
||||
it('keeps external Claude logout when deselecting managed account', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials = createClaudeCredentialsJson('system@example.com', 'system')
|
||||
const managedCredentials = createClaudeCredentialsJson('user@example.com', 'managed')
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials, 'utf-8')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
managedCredentials
|
||||
)
|
||||
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()
|
||||
|
||||
rmSync(runtimeCredentialsPath, { force: true })
|
||||
testState.activeKeychainCredentials = null
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(existsSync(runtimeCredentialsPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('reads back refreshed active keychain credentials on macOS', async () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
return
|
||||
}
|
||||
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original')
|
||||
const refreshedCredentials = createClaudeCredentialsJson('user@example.com', '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()
|
||||
|
||||
testState.activeKeychainCredentials = refreshedCredentials
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(refreshedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials)
|
||||
})
|
||||
|
||||
it('restores system default when mismatched Claude keychain auth appears before deselect', async () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
return
|
||||
}
|
||||
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials = createClaudeCredentialsJson('system@example.com', 'system')
|
||||
const managedCredentials = createClaudeCredentialsJson('user@example.com', 'managed')
|
||||
const externalKeychainCredentials = createClaudeCredentialsJson(
|
||||
'external@example.com',
|
||||
'external'
|
||||
)
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials, 'utf-8')
|
||||
testState.activeKeychainCredentials = systemCredentials
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
managedCredentials
|
||||
)
|
||||
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()
|
||||
|
||||
testState.activeKeychainCredentials = externalKeychainCredentials
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(systemCredentials)
|
||||
expect(testState.activeKeychainCredentials).toBe(systemCredentials)
|
||||
})
|
||||
|
||||
it('captures a fresh system-default snapshot when re-entering managed mode', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const systemCredentials1 = createClaudeCredentialsJson('system1@example.com', 'system1')
|
||||
const systemCredentials2 = createClaudeCredentialsJson('system2@example.com', 'system2')
|
||||
const managedCredentials = createClaudeCredentialsJson('user@example.com', 'managed')
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials1, 'utf-8')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
managedCredentials
|
||||
)
|
||||
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()
|
||||
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
writeFileSync(runtimeCredentialsPath, systemCredentials2, 'utf-8')
|
||||
|
||||
settings.activeClaudeManagedAccountId = 'account-1'
|
||||
await service.syncForCurrentSelection()
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(systemCredentials2)
|
||||
})
|
||||
|
||||
it('reads back refreshed credentials for the outgoing Claude account before switching', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const account1Original = createClaudeCredentialsJson('one@example.com', 'one-original')
|
||||
const account1Refreshed = createClaudeCredentialsJson('one@example.com', 'one-refreshed')
|
||||
const account2Credentials = createClaudeCredentialsJson('two@example.com', 'two')
|
||||
const managedAuthPath1 = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
account1Original
|
||||
)
|
||||
const managedAuthPath2 = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-2',
|
||||
account2Credentials
|
||||
)
|
||||
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)
|
||||
|
||||
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
|
||||
const service = new ClaudeRuntimeAuthService(store as never)
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
writeFileSync(runtimeCredentialsPath, account1Refreshed, 'utf-8')
|
||||
settings.activeClaudeManagedAccountId = 'account-2'
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath1)).toBe(account1Refreshed)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(account2Credentials)
|
||||
})
|
||||
|
||||
it('clears an invalid active Claude account before launch preparation', async () => {
|
||||
const settings = createSettings({
|
||||
activeClaudeManagedAccountId: 'missing-account'
|
||||
})
|
||||
const store = createStore(settings)
|
||||
|
||||
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
|
||||
const service = new ClaudeRuntimeAuthService(store as never)
|
||||
const preparation = await service.prepareForClaudeLaunch()
|
||||
|
||||
expect(store.updateSettings).toHaveBeenCalledWith({ activeClaudeManagedAccountId: null })
|
||||
expect(preparation.stripAuthEnv).toBe(false)
|
||||
expect(preparation.provenance).toBe('system')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* eslint-disable max-lines -- Why: Claude account switching has one safety
|
||||
boundary: runtime auth materialization. Keeping file, Keychain, snapshot, and
|
||||
env-patch semantics together prevents PTY launch and quota fetch paths drifting. */
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { app } from 'electron'
|
||||
import type { ClaudeManagedAccount } from '../../shared/types'
|
||||
@@ -32,9 +32,10 @@ type ClaudeSystemDefaultSnapshot = {
|
||||
|
||||
type ClaudeAuthIdentity = {
|
||||
email: string | null
|
||||
organizationUuid: string | null
|
||||
}
|
||||
|
||||
type ClaudeReadBackResult = 'unchanged' | 'persisted' | 'rejected' | 'unverifiable'
|
||||
type ClaudeReadBackResult = { status: 'unchanged' | 'persisted' | 'rejected' }
|
||||
|
||||
export class ClaudeRuntimeAuthService {
|
||||
private readonly pathResolver = new ClaudeRuntimePathResolver()
|
||||
@@ -69,7 +70,7 @@ export class ClaudeRuntimeAuthService {
|
||||
await this.serializeMutation(async () => {
|
||||
const settings = this.store.getSettings()
|
||||
if (!settings.activeClaudeManagedAccountId) {
|
||||
await this.restoreSystemDefaultSnapshot()
|
||||
await this.restoreSystemDefaultSnapshot({ detectExternalLogin: true })
|
||||
this.lastSyncedAccountId = null
|
||||
return
|
||||
}
|
||||
@@ -106,15 +107,30 @@ export class ClaudeRuntimeAuthService {
|
||||
settings.claudeManagedAccounts,
|
||||
settings.activeClaudeManagedAccountId
|
||||
)
|
||||
const previousAccount = this.getActiveAccount(
|
||||
settings.claudeManagedAccounts,
|
||||
this.lastSyncedAccountId
|
||||
)
|
||||
let outgoingReadBackResult: ClaudeReadBackResult = { status: 'unchanged' }
|
||||
if (previousAccount && previousAccount.id !== activeAccount?.id) {
|
||||
outgoingReadBackResult = await this.readBackRefreshedTokensForAccount(previousAccount, {
|
||||
updateLastWrittenCredentialsJson: true
|
||||
})
|
||||
}
|
||||
if (!activeAccount) {
|
||||
if (settings.activeClaudeManagedAccountId) {
|
||||
this.store.updateSettings({ activeClaudeManagedAccountId: null })
|
||||
}
|
||||
if (this.lastSyncedAccountId !== null) {
|
||||
await this.restoreSystemDefaultSnapshot()
|
||||
await this.restoreSystemDefaultSnapshot({
|
||||
detectExternalLogin: outgoingReadBackResult.status !== 'rejected'
|
||||
})
|
||||
this.lastSyncedAccountId = null
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
await this.captureSystemDefaultSnapshotIfNeeded()
|
||||
await this.captureSystemDefaultSnapshot({ force: this.lastSyncedAccountId === null })
|
||||
|
||||
let credentialsJson = await this.readManagedCredentials(activeAccount)
|
||||
if (!credentialsJson) {
|
||||
@@ -123,7 +139,7 @@ export class ClaudeRuntimeAuthService {
|
||||
)
|
||||
this.store.updateSettings({ activeClaudeManagedAccountId: null })
|
||||
if (this.lastSyncedAccountId !== null) {
|
||||
await this.restoreSystemDefaultSnapshot()
|
||||
await this.restoreSystemDefaultSnapshot({ detectExternalLogin: true })
|
||||
this.lastSyncedAccountId = null
|
||||
}
|
||||
return
|
||||
@@ -134,13 +150,11 @@ 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) {
|
||||
const readBackResult = await this.readBackRefreshedTokens(activeAccount)
|
||||
if (readBackResult === 'persisted') {
|
||||
const readBackResult = await this.readBackRefreshedTokens(activeAccount, credentialsJson, {
|
||||
updateLastWrittenCredentialsJson: true
|
||||
})
|
||||
if (readBackResult.status === 'persisted') {
|
||||
credentialsJson = (await this.readManagedCredentials(activeAccount)) ?? credentialsJson
|
||||
} else if (readBackResult === 'unverifiable') {
|
||||
this.writeRuntimeOauthAccount(this.readManagedOauthAccount(activeAccount))
|
||||
this.lastSyncedAccountId = activeAccount.id
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,47 +175,79 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
|
||||
private async readBackRefreshedTokens(
|
||||
account: ClaudeManagedAccount
|
||||
account: ClaudeManagedAccount,
|
||||
managedCredentialsJson: string,
|
||||
options: { updateLastWrittenCredentialsJson: boolean }
|
||||
): Promise<ClaudeReadBackResult> {
|
||||
try {
|
||||
if (this.lastWrittenCredentialsJson === null) {
|
||||
return 'unchanged'
|
||||
return { status: 'unchanged' }
|
||||
}
|
||||
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
if (!existsSync(paths.credentialsPath)) {
|
||||
return 'unchanged'
|
||||
const runtimeContents = await this.readRuntimeCredentialsForReadBack()
|
||||
if (!runtimeContents) {
|
||||
return { status: 'unchanged' }
|
||||
}
|
||||
|
||||
const runtimeContents = readFileSync(paths.credentialsPath, 'utf-8')
|
||||
if (runtimeContents === this.lastWrittenCredentialsJson) {
|
||||
return 'unchanged'
|
||||
return { status: 'unchanged' }
|
||||
}
|
||||
|
||||
const matchResult = this.runtimeCredentialsMatchAccount(runtimeContents, account)
|
||||
const matchResult = this.runtimeCredentialsMatchAccount(
|
||||
runtimeContents,
|
||||
account,
|
||||
managedCredentialsJson,
|
||||
this.readManagedOauthAccount(account)
|
||||
)
|
||||
if (matchResult === 'unverifiable') {
|
||||
return 'unverifiable'
|
||||
return { status: 'rejected' }
|
||||
}
|
||||
if (matchResult === 'mismatch') {
|
||||
return 'rejected'
|
||||
return { status: 'rejected' }
|
||||
}
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
await writeManagedClaudeKeychainCredentials(account.id, runtimeContents)
|
||||
} else {
|
||||
const credentialsPath = join(account.managedAuthPath, '.credentials.json')
|
||||
writeFileAtomically(credentialsPath, runtimeContents, { mode: 0o600 })
|
||||
await this.writeManagedCredentials(account, runtimeContents)
|
||||
if (options.updateLastWrittenCredentialsJson) {
|
||||
this.writeRuntimeCredentials(runtimeContents)
|
||||
this.lastWrittenCredentialsJson = runtimeContents
|
||||
if (process.platform === 'darwin') {
|
||||
await writeActiveClaudeKeychainCredentials(runtimeContents)
|
||||
}
|
||||
}
|
||||
return 'persisted'
|
||||
return { status: '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'
|
||||
return { status: 'rejected' }
|
||||
}
|
||||
}
|
||||
|
||||
private async readRuntimeCredentialsForReadBack(): Promise<string | null> {
|
||||
if (process.platform === 'darwin') {
|
||||
const keychainCredentials = await readActiveClaudeKeychainCredentials()
|
||||
if (keychainCredentials && keychainCredentials !== this.lastWrittenCredentialsJson) {
|
||||
return keychainCredentials
|
||||
}
|
||||
}
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
if (!existsSync(paths.credentialsPath)) {
|
||||
return null
|
||||
}
|
||||
return readFileSync(paths.credentialsPath, 'utf-8')
|
||||
}
|
||||
|
||||
private async readBackRefreshedTokensForAccount(
|
||||
account: ClaudeManagedAccount,
|
||||
options: { updateLastWrittenCredentialsJson: boolean }
|
||||
): Promise<ClaudeReadBackResult> {
|
||||
const managedCredentialsJson = await this.readManagedCredentials(account)
|
||||
if (!managedCredentialsJson) {
|
||||
return { status: 'unchanged' }
|
||||
}
|
||||
return this.readBackRefreshedTokens(account, managedCredentialsJson, options)
|
||||
}
|
||||
|
||||
private getPreparation(): ClaudeRuntimeAuthPreparation {
|
||||
const settings = this.store.getSettings()
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
@@ -225,16 +271,35 @@ export class ClaudeRuntimeAuthService {
|
||||
|
||||
private runtimeCredentialsMatchAccount(
|
||||
runtimeCredentialsJson: string,
|
||||
account: ClaudeManagedAccount
|
||||
account: ClaudeManagedAccount,
|
||||
managedCredentialsJson: string,
|
||||
managedOauthAccount: unknown
|
||||
): 'match' | 'mismatch' | 'unverifiable' {
|
||||
const identity = this.readIdentityFromCredentials(runtimeCredentialsJson)
|
||||
if (!identity) {
|
||||
return 'mismatch'
|
||||
}
|
||||
const managedIdentity = this.readIdentityFromCredentials(managedCredentialsJson)
|
||||
const managedOauthIdentity = this.readIdentityFromOauthAccount(managedOauthAccount)
|
||||
|
||||
// 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.
|
||||
const selectedOrganizationUuid = this.normalizeField(
|
||||
account.organizationUuid ??
|
||||
managedIdentity?.organizationUuid ??
|
||||
managedOauthIdentity.organizationUuid
|
||||
)
|
||||
if (selectedOrganizationUuid && !identity.organizationUuid) {
|
||||
return 'unverifiable'
|
||||
}
|
||||
if (
|
||||
selectedOrganizationUuid &&
|
||||
identity.organizationUuid &&
|
||||
selectedOrganizationUuid !== identity.organizationUuid
|
||||
) {
|
||||
return 'mismatch'
|
||||
}
|
||||
if (!identity.email) {
|
||||
return 'unverifiable'
|
||||
}
|
||||
@@ -254,7 +319,22 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
const oauth = this.asRecord(parsed.claudeAiOauth)
|
||||
return {
|
||||
email: this.normalizeField(this.readString(oauth, 'email'))
|
||||
email: this.normalizeField(this.readString(oauth, 'email')),
|
||||
organizationUuid: this.normalizeField(
|
||||
this.readString(oauth, 'organizationUuid') ?? this.readString(oauth, 'organizationId')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private readIdentityFromOauthAccount(oauthAccount: unknown): ClaudeAuthIdentity {
|
||||
const oauth = this.asRecord(oauthAccount)
|
||||
return {
|
||||
email: this.normalizeField(
|
||||
this.readString(oauth, 'emailAddress') ?? this.readString(oauth, 'email')
|
||||
),
|
||||
organizationUuid: this.normalizeField(
|
||||
this.readString(oauth, 'organizationUuid') ?? this.readString(oauth, 'organizationId')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +369,18 @@ export class ClaudeRuntimeAuthService {
|
||||
return readFileSync(credentialsPath, 'utf-8')
|
||||
}
|
||||
|
||||
private async writeManagedCredentials(
|
||||
account: ClaudeManagedAccount,
|
||||
credentialsJson: string
|
||||
): Promise<void> {
|
||||
if (process.platform === 'darwin') {
|
||||
await writeManagedClaudeKeychainCredentials(account.id, credentialsJson)
|
||||
return
|
||||
}
|
||||
const credentialsPath = join(account.managedAuthPath, '.credentials.json')
|
||||
writeFileAtomically(credentialsPath, credentialsJson, { mode: 0o600 })
|
||||
}
|
||||
|
||||
private readManagedOauthAccount(account: ClaudeManagedAccount): unknown {
|
||||
const oauthPath = join(account.managedAuthPath, 'oauth-account.json')
|
||||
if (!existsSync(oauthPath)) {
|
||||
@@ -301,9 +393,9 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
}
|
||||
|
||||
private async captureSystemDefaultSnapshotIfNeeded(): Promise<void> {
|
||||
private async captureSystemDefaultSnapshot(options: { force: boolean }): Promise<void> {
|
||||
const snapshotPath = this.getSystemDefaultSnapshotPath()
|
||||
if (existsSync(snapshotPath)) {
|
||||
if (!options.force && existsSync(snapshotPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -321,8 +413,13 @@ export class ClaudeRuntimeAuthService {
|
||||
this.writeJson(snapshotPath, snapshot)
|
||||
}
|
||||
|
||||
private async restoreSystemDefaultSnapshot(): Promise<void> {
|
||||
if (this.detectExternalLoginAndUpdateSnapshot()) {
|
||||
private async restoreSystemDefaultSnapshot(options: {
|
||||
detectExternalLogin: boolean
|
||||
}): Promise<void> {
|
||||
const externalState = options.detectExternalLogin
|
||||
? await this.detectExternalLoginAndUpdateSnapshot()
|
||||
: 'none'
|
||||
if (externalState === 'file-logout') {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -338,9 +435,11 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
this.writeRuntimeOauthAccount(snapshot.configOauthAccount)
|
||||
if (process.platform === 'darwin') {
|
||||
await (snapshot.keychainCredentialsJson !== null
|
||||
? writeActiveClaudeKeychainCredentials(snapshot.keychainCredentialsJson)
|
||||
: deleteActiveClaudeKeychainCredentials())
|
||||
if (externalState !== 'keychain-change') {
|
||||
await (snapshot.keychainCredentialsJson !== null
|
||||
? writeActiveClaudeKeychainCredentials(snapshot.keychainCredentialsJson)
|
||||
: deleteActiveClaudeKeychainCredentials())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,23 +447,43 @@ export class ClaudeRuntimeAuthService {
|
||||
// the credentials file while a managed account was active. If the file
|
||||
// differs from what Orca last wrote, that external login becomes the new
|
||||
// system default — no manual "refresh" button needed.
|
||||
private detectExternalLoginAndUpdateSnapshot(): boolean {
|
||||
private async detectExternalLoginAndUpdateSnapshot(): Promise<
|
||||
'none' | 'file-logout' | 'keychain-change'
|
||||
> {
|
||||
if (this.lastWrittenCredentialsJson === null) {
|
||||
return false
|
||||
return 'none'
|
||||
}
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
if (!existsSync(paths.credentialsPath)) {
|
||||
return false
|
||||
const currentKeychainCredentials =
|
||||
process.platform === 'darwin' ? await readActiveClaudeKeychainCredentials() : null
|
||||
if (
|
||||
process.platform === 'darwin' &&
|
||||
currentKeychainCredentials === this.lastWrittenCredentialsJson
|
||||
) {
|
||||
return 'none'
|
||||
}
|
||||
const snapshotPath = this.getSystemDefaultSnapshotPath()
|
||||
rmSync(snapshotPath, { force: true })
|
||||
this.lastWrittenCredentialsJson = null
|
||||
return 'file-logout'
|
||||
}
|
||||
const currentCredentials = readFileSync(paths.credentialsPath, 'utf-8')
|
||||
const currentKeychainCredentials =
|
||||
process.platform === 'darwin' ? await readActiveClaudeKeychainCredentials() : null
|
||||
if (currentCredentials === this.lastWrittenCredentialsJson) {
|
||||
return false
|
||||
if (
|
||||
process.platform === 'darwin' &&
|
||||
currentKeychainCredentials !== this.lastWrittenCredentialsJson
|
||||
) {
|
||||
return 'keychain-change'
|
||||
}
|
||||
return 'none'
|
||||
}
|
||||
// External login detected — adopt current state as the new system default
|
||||
const snapshotPath = this.getSystemDefaultSnapshotPath()
|
||||
rmSync(snapshotPath, { force: true })
|
||||
this.lastWrittenCredentialsJson = null
|
||||
return true
|
||||
return 'file-logout'
|
||||
}
|
||||
|
||||
private readRuntimeOauthAccount(): unknown {
|
||||
@@ -402,9 +521,11 @@ export class ClaudeRuntimeAuthService {
|
||||
this.lastWrittenCredentialsJson === contents &&
|
||||
this.fileContentsEqual(credentialsPath, contents)
|
||||
) {
|
||||
this.ensureOwnerOnlyMode(credentialsPath)
|
||||
return
|
||||
}
|
||||
if (this.fileContentsEqual(credentialsPath, contents)) {
|
||||
this.ensureOwnerOnlyMode(credentialsPath)
|
||||
this.lastWrittenCredentialsJson = contents
|
||||
return
|
||||
}
|
||||
@@ -430,6 +551,17 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
}
|
||||
|
||||
private ensureOwnerOnlyMode(targetPath: string): void {
|
||||
if (process.platform === 'win32') {
|
||||
return
|
||||
}
|
||||
try {
|
||||
chmodSync(targetPath, 0o600)
|
||||
} catch {
|
||||
/* Best effort: the next atomic write will set the restrictive mode. */
|
||||
}
|
||||
}
|
||||
|
||||
private readJsonObject(targetPath: string): Record<string, unknown> {
|
||||
if (!existsSync(targetPath)) {
|
||||
return {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable max-lines -- test suite covers snapshot, migration, auth materialization, and error-resilience scenarios */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
mkdirSync,
|
||||
@@ -181,11 +182,19 @@ describe('CodexRuntimeHomeService', () => {
|
||||
new CodexRuntimeHomeService(store as never)
|
||||
|
||||
expect(
|
||||
readFileSync(
|
||||
join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'),
|
||||
'utf-8'
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'),
|
||||
'utf-8'
|
||||
)
|
||||
)
|
||||
).toBe('{"account":"system"}\n')
|
||||
).toEqual({ authJson: '{"account":"system"}\n' })
|
||||
if (process.platform !== 'win32') {
|
||||
expect(
|
||||
statSync(join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'))
|
||||
.mode & 0o777
|
||||
).toBe(0o600)
|
||||
}
|
||||
})
|
||||
|
||||
it('materializes the active managed account auth into ~/.codex on startup', async () => {
|
||||
@@ -220,11 +229,13 @@ describe('CodexRuntimeHomeService', () => {
|
||||
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"managed"}\n')
|
||||
expect(
|
||||
readFileSync(
|
||||
join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'),
|
||||
'utf-8'
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'),
|
||||
'utf-8'
|
||||
)
|
||||
)
|
||||
).toBe('{"account":"system"}\n')
|
||||
).toEqual({ authJson: '{"account":"system"}\n' })
|
||||
})
|
||||
|
||||
it('restores the system-default snapshot when no managed account is selected', async () => {
|
||||
@@ -263,6 +274,42 @@ describe('CodexRuntimeHomeService', () => {
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"system"}\n')
|
||||
})
|
||||
|
||||
it('removes runtime auth when restoring a no-login system default', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
const managedHomePath = createManagedAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
'{"account":"managed"}\n'
|
||||
)
|
||||
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)
|
||||
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"managed"}\n')
|
||||
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(existsSync(runtimeAuthPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('clears an invalid active account selection and restores the system default snapshot', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
@@ -460,6 +507,44 @@ describe('CodexRuntimeHomeService', () => {
|
||||
expect(mode).toBe(0o600)
|
||||
})
|
||||
|
||||
it('tightens auth.json permissions when unchanged content is already present', async () => {
|
||||
if (process.platform === 'win32') {
|
||||
return
|
||||
}
|
||||
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
const managedHomePath = createManagedAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
'{"account":"managed"}\n'
|
||||
)
|
||||
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)
|
||||
chmodSync(runtimeAuthPath, 0o644)
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(statSync(runtimeAuthPath).mode & 0o777).toBe(0o600)
|
||||
})
|
||||
|
||||
it('does not throw when syncForCurrentSelection encounters an error', async () => {
|
||||
const store = createStore(
|
||||
createSettings({
|
||||
@@ -683,6 +768,81 @@ describe('CodexRuntimeHomeService', () => {
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(selectedAuth)
|
||||
})
|
||||
|
||||
it('reads back same-account refreshes for sparse managed metadata using stored auth identity', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
const originalAuth = createCodexAuthJson('user@example.com', 'acct-selected', 'original')
|
||||
const refreshedAuth = createCodexAuthJson('user@example.com', 'acct-selected', 'refreshed')
|
||||
const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', originalAuth)
|
||||
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, refreshedAuth, 'utf-8')
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(managedAuthPath, 'utf-8')).toBe(refreshedAuth)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(refreshedAuth)
|
||||
})
|
||||
|
||||
it('reads back strong account-id refreshes when the runtime auth has no email', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
const originalAuth = createCodexAuthJson('user@example.com', 'acct-1', 'original')
|
||||
const refreshedAuth = `${JSON.stringify({
|
||||
tokens: {
|
||||
account_id: 'acct-1',
|
||||
refresh_token: 'refreshed'
|
||||
}
|
||||
})}\n`
|
||||
const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', originalAuth)
|
||||
const managedAuthPath = join(managedHomePath, 'auth.json')
|
||||
const settings = createSettings({
|
||||
codexManagedAccounts: [
|
||||
{
|
||||
id: 'account-1',
|
||||
email: 'user@example.com',
|
||||
managedHomePath,
|
||||
providerAccountId: 'acct-1',
|
||||
workspaceLabel: null,
|
||||
workspaceAccountId: 'acct-1',
|
||||
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, refreshedAuth, 'utf-8')
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(managedAuthPath, 'utf-8')).toBe(refreshedAuth)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(refreshedAuth)
|
||||
})
|
||||
|
||||
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
|
||||
@@ -776,7 +936,7 @@ describe('CodexRuntimeHomeService', () => {
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"account2"}\n')
|
||||
})
|
||||
|
||||
it('detects external login on managed→system-default transition', async () => {
|
||||
it('restores system default when unverified runtime auth appears before deselect', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
const managedHomePath = createManagedAuth(
|
||||
@@ -805,19 +965,216 @@ describe('CodexRuntimeHomeService', () => {
|
||||
const { CodexRuntimeHomeService } = await import('./runtime-home-service')
|
||||
const service = new CodexRuntimeHomeService(store as never)
|
||||
|
||||
// External `codex auth login` overwrites runtime auth
|
||||
// A stale or external process overwrites runtime with auth Orca cannot
|
||||
// verify against the outgoing managed account.
|
||||
writeFileSync(runtimeAuthPath, '{"account":"external-login"}\n', 'utf-8')
|
||||
|
||||
// Deselect managed account
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
// Should keep the external login, not restore stale system snapshot
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"external-login"}\n')
|
||||
// Snapshot should be deleted so next capture picks up the external login
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"system"}\n')
|
||||
expect(
|
||||
existsSync(join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'))
|
||||
).toBe(false)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('restores system default after same-identity managed Codex refresh on deselect', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system-old"}\n', 'utf-8')
|
||||
const managedAuth = createCodexAuthJson('user@example.com', 'acct-1', 'managed')
|
||||
const externalAuth = createCodexAuthJson('user@example.com', 'acct-1', 'external')
|
||||
const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', managedAuth)
|
||||
const managedAuthPath = join(managedHomePath, 'auth.json')
|
||||
const settings = createSettings({
|
||||
codexManagedAccounts: [
|
||||
{
|
||||
id: 'account-1',
|
||||
email: 'user@example.com',
|
||||
managedHomePath,
|
||||
providerAccountId: 'acct-1',
|
||||
workspaceLabel: null,
|
||||
workspaceAccountId: 'acct-1',
|
||||
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, externalAuth, 'utf-8')
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(managedAuthPath, 'utf-8')).toBe(externalAuth)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"system-old"}\n')
|
||||
})
|
||||
|
||||
it('restores system default when stale Codex credentials are rejected on deselect', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system-old"}\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)
|
||||
|
||||
writeFileSync(runtimeAuthPath, staleLivePtyAuth, 'utf-8')
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(managedAuthPath, 'utf-8')).toBe(selectedAuth)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"system-old"}\n')
|
||||
})
|
||||
|
||||
it('keeps external Codex logout when deselecting managed account', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system-old"}\n', 'utf-8')
|
||||
const managedHomePath = createManagedAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
'{"account":"managed"}\n'
|
||||
)
|
||||
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)
|
||||
|
||||
rmSync(runtimeAuthPath, { force: true })
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(existsSync(runtimeAuthPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('captures a fresh system-default snapshot when re-entering managed mode', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system-1"}\n', 'utf-8')
|
||||
const managedHomePath = createManagedAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
'{"account":"managed"}\n'
|
||||
)
|
||||
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)
|
||||
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system-2"}\n', 'utf-8')
|
||||
|
||||
settings.activeCodexManagedAccountId = 'account-1'
|
||||
service.syncForCurrentSelection()
|
||||
settings.activeCodexManagedAccountId = null
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"system-2"}\n')
|
||||
})
|
||||
|
||||
it('reads back refreshed tokens for the outgoing Codex account before switching', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
const account1Original = createCodexAuthJson('one@example.com', 'acct-1', 'one-original')
|
||||
const account1Refreshed = createCodexAuthJson('one@example.com', 'acct-1', 'one-refreshed')
|
||||
const account2Auth = createCodexAuthJson('two@example.com', 'acct-2', 'two')
|
||||
const managedHomePath1 = createManagedAuth(testState.userDataDir, 'account-1', account1Original)
|
||||
const managedHomePath2 = createManagedAuth(testState.userDataDir, 'account-2', account2Auth)
|
||||
const managedAuthPath1 = join(managedHomePath1, 'auth.json')
|
||||
const settings = createSettings({
|
||||
codexManagedAccounts: [
|
||||
{
|
||||
id: 'account-1',
|
||||
email: 'one@example.com',
|
||||
managedHomePath: managedHomePath1,
|
||||
providerAccountId: 'acct-1',
|
||||
workspaceLabel: null,
|
||||
workspaceAccountId: 'acct-1',
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
lastAuthenticatedAt: 1
|
||||
},
|
||||
{
|
||||
id: 'account-2',
|
||||
email: 'two@example.com',
|
||||
managedHomePath: managedHomePath2,
|
||||
providerAccountId: 'acct-2',
|
||||
workspaceLabel: null,
|
||||
workspaceAccountId: 'acct-2',
|
||||
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, account1Refreshed, 'utf-8')
|
||||
settings.activeCodexManagedAccountId = 'account-2'
|
||||
service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(managedAuthPath1, 'utf-8')).toBe(account1Refreshed)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(account2Auth)
|
||||
})
|
||||
|
||||
it('does not clobber fresh tokens after clearLastWrittenAuthJson', async () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ semantics from drifting across PTY launch, login, and quota fetch paths. */
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
chmodSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
@@ -24,6 +25,12 @@ type CodexAuthIdentity = {
|
||||
workspaceAccountId: string | null
|
||||
}
|
||||
|
||||
type CodexSystemDefaultSnapshot = {
|
||||
authJson: string | null
|
||||
}
|
||||
|
||||
type CodexReadBackResult = 'unchanged' | 'persisted' | 'rejected'
|
||||
|
||||
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
|
||||
@@ -60,26 +67,44 @@ export class CodexRuntimeHomeService {
|
||||
}
|
||||
|
||||
syncForCurrentSelection(): void {
|
||||
this.captureSystemDefaultSnapshotIfNeeded()
|
||||
|
||||
const settings = this.store.getSettings()
|
||||
if (this.lastSyncedAccountId === null) {
|
||||
this.captureSystemDefaultSnapshot({ force: false })
|
||||
}
|
||||
const activeAccount = this.getActiveAccount(
|
||||
settings.codexManagedAccounts,
|
||||
settings.activeCodexManagedAccountId
|
||||
)
|
||||
const previousAccount = this.getActiveAccount(
|
||||
settings.codexManagedAccounts,
|
||||
this.lastSyncedAccountId
|
||||
)
|
||||
let outgoingReadBackResult: CodexReadBackResult = 'unchanged'
|
||||
if (previousAccount && previousAccount.id !== activeAccount?.id) {
|
||||
outgoingReadBackResult = this.readBackRefreshedTokensForAccount(previousAccount, {
|
||||
updateLastWrittenAuthJson: true
|
||||
})
|
||||
}
|
||||
if (!activeAccount) {
|
||||
if (settings.activeCodexManagedAccountId) {
|
||||
this.store.updateSettings({ activeCodexManagedAccountId: null })
|
||||
}
|
||||
// Why: only restore the snapshot when transitioning FROM a managed
|
||||
// account back to system default. When no managed account was ever
|
||||
// active, auth.json belongs to the user and Orca must not touch it.
|
||||
// This prevents overwriting external auth changes (codex login or other
|
||||
// tools) on every PTY launch / rate-limit fetch.
|
||||
if (this.lastSyncedAccountId !== null) {
|
||||
this.restoreSystemDefaultSnapshot()
|
||||
this.restoreSystemDefaultSnapshot({
|
||||
detectExternalLogin: outgoingReadBackResult !== 'rejected'
|
||||
})
|
||||
this.lastSyncedAccountId = null
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
this.captureSystemDefaultSnapshot({ force: this.lastSyncedAccountId === null })
|
||||
|
||||
const activeAuthPath = join(activeAccount.managedHomePath, 'auth.json')
|
||||
if (!existsSync(activeAuthPath)) {
|
||||
console.warn(
|
||||
@@ -87,7 +112,7 @@ export class CodexRuntimeHomeService {
|
||||
)
|
||||
this.store.updateSettings({ activeCodexManagedAccountId: null })
|
||||
if (this.lastSyncedAccountId !== null) {
|
||||
this.restoreSystemDefaultSnapshot()
|
||||
this.restoreSystemDefaultSnapshot({ detectExternalLogin: true })
|
||||
this.lastSyncedAccountId = null
|
||||
}
|
||||
return
|
||||
@@ -98,7 +123,9 @@ 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(activeAccount, activeAuthPath)
|
||||
this.readBackRefreshedTokens(activeAccount, activeAuthPath, {
|
||||
updateLastWrittenAuthJson: true
|
||||
})
|
||||
}
|
||||
|
||||
this.lastSyncedAccountId = activeAccount.id
|
||||
@@ -115,36 +142,59 @@ export class CodexRuntimeHomeService {
|
||||
|
||||
private readBackRefreshedTokens(
|
||||
activeAccount: CodexManagedAccount,
|
||||
managedAuthPath: string
|
||||
): void {
|
||||
managedAuthPath: string,
|
||||
options: { updateLastWrittenAuthJson: boolean }
|
||||
): CodexReadBackResult {
|
||||
try {
|
||||
const runtimeAuthPath = this.getRuntimeAuthPath()
|
||||
if (!existsSync(runtimeAuthPath)) {
|
||||
return
|
||||
return 'unchanged'
|
||||
}
|
||||
|
||||
if (this.lastWrittenAuthJson === null) {
|
||||
return
|
||||
return 'unchanged'
|
||||
}
|
||||
|
||||
const runtimeContents = readFileSync(runtimeAuthPath, 'utf-8')
|
||||
if (runtimeContents === this.lastWrittenAuthJson) {
|
||||
return
|
||||
return 'unchanged'
|
||||
}
|
||||
|
||||
if (!this.runtimeAuthMatchesAccount(runtimeContents, activeAccount)) {
|
||||
return
|
||||
if (
|
||||
!this.runtimeAuthMatchesAccount(
|
||||
runtimeContents,
|
||||
activeAccount,
|
||||
readFileSync(managedAuthPath, 'utf-8')
|
||||
)
|
||||
) {
|
||||
return 'rejected'
|
||||
}
|
||||
|
||||
writeFileAtomically(managedAuthPath, runtimeContents, { mode: 0o600 })
|
||||
if (options.updateLastWrittenAuthJson) {
|
||||
this.lastWrittenAuthJson = runtimeContents
|
||||
}
|
||||
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('[codex-runtime-home] Failed to read back refreshed tokens:', error)
|
||||
return 'rejected'
|
||||
}
|
||||
}
|
||||
|
||||
private readBackRefreshedTokensForAccount(
|
||||
account: CodexManagedAccount,
|
||||
options: { updateLastWrittenAuthJson: boolean }
|
||||
): CodexReadBackResult {
|
||||
const managedAuthPath = join(account.managedHomePath, 'auth.json')
|
||||
if (!existsSync(managedAuthPath)) {
|
||||
return 'unchanged'
|
||||
}
|
||||
return this.readBackRefreshedTokens(account, managedAuthPath, options)
|
||||
}
|
||||
|
||||
private safeSyncForCurrentSelection(): void {
|
||||
try {
|
||||
this.syncForCurrentSelection()
|
||||
@@ -165,54 +215,60 @@ export class CodexRuntimeHomeService {
|
||||
|
||||
private runtimeAuthMatchesAccount(
|
||||
runtimeAuthContents: string,
|
||||
activeAccount: CodexManagedAccount
|
||||
activeAccount: CodexManagedAccount,
|
||||
managedAuthContents: string
|
||||
): boolean {
|
||||
const identity = this.readIdentityFromAuthContents(runtimeAuthContents)
|
||||
if (!identity) {
|
||||
return false
|
||||
}
|
||||
const managedIdentity = this.readIdentityFromAuthContents(managedAuthContents)
|
||||
|
||||
// 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.
|
||||
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) {
|
||||
const selectedEmail = this.firstNonNull(
|
||||
this.normalizeField(activeAccount.email),
|
||||
managedIdentity?.email
|
||||
)
|
||||
const selectedProviderId = this.firstNonNull(
|
||||
this.normalizeField(activeAccount.providerAccountId),
|
||||
managedIdentity?.providerAccountId
|
||||
)
|
||||
const selectedWorkspaceId = this.firstNonNull(
|
||||
this.normalizeField(activeAccount.workspaceAccountId),
|
||||
managedIdentity?.workspaceAccountId
|
||||
)
|
||||
const emailMatches = Boolean(
|
||||
selectedEmail && identity.email && selectedEmail === identity.email
|
||||
)
|
||||
if (selectedEmail && identity.email && selectedEmail !== identity.email) {
|
||||
return false
|
||||
}
|
||||
if (!this.identityFieldMatches(selectedProviderId, identity.providerAccountId)) {
|
||||
return false
|
||||
}
|
||||
if (!this.identityFieldMatches(selectedWorkspaceId, identity.workspaceAccountId)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!this.strongIdentityFieldsMatch(accountProviderId, identity.providerAccountId)) {
|
||||
return false
|
||||
}
|
||||
if (accountProviderId && identity.providerAccountId) {
|
||||
hasStrongIdentity = true
|
||||
}
|
||||
|
||||
if (!this.strongIdentityFieldsMatch(accountWorkspaceId, identity.workspaceAccountId)) {
|
||||
return false
|
||||
}
|
||||
if (accountWorkspaceId && identity.workspaceAccountId) {
|
||||
hasStrongIdentity = true
|
||||
}
|
||||
|
||||
const hasStrongIdentity = Boolean(
|
||||
(selectedProviderId && identity.providerAccountId) ||
|
||||
(selectedWorkspaceId && identity.workspaceAccountId)
|
||||
)
|
||||
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 identityFieldMatches(selectedField: string | null, runtimeField: string | null): boolean {
|
||||
return !selectedField || Boolean(runtimeField && selectedField === runtimeField)
|
||||
}
|
||||
|
||||
private firstNonNull(...values: (string | null | undefined)[]): string | null {
|
||||
return values.find((value): value is string => Boolean(value)) ?? null
|
||||
}
|
||||
|
||||
private readIdentityFromAuthContents(contents: string): CodexAuthIdentity | null {
|
||||
@@ -473,25 +529,24 @@ export class CodexRuntimeHomeService {
|
||||
writeFileAtomically(diagnosticsPath, `${existingContents}${JSON.stringify(record)}\n`)
|
||||
}
|
||||
|
||||
private captureSystemDefaultSnapshotIfNeeded(): void {
|
||||
private captureSystemDefaultSnapshot(options: { force: boolean }): void {
|
||||
const snapshotPath = this.getSystemDefaultSnapshotPath()
|
||||
if (existsSync(snapshotPath)) {
|
||||
if (!options.force && existsSync(snapshotPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
const runtimeAuthPath = this.getRuntimeAuthPath()
|
||||
if (!existsSync(runtimeAuthPath)) {
|
||||
return
|
||||
const snapshot: CodexSystemDefaultSnapshot = {
|
||||
authJson: existsSync(runtimeAuthPath) ? readFileSync(runtimeAuthPath, 'utf-8') : null
|
||||
}
|
||||
|
||||
writeFileAtomically(snapshotPath, readFileSync(runtimeAuthPath, 'utf-8'))
|
||||
writeFileAtomically(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`, { mode: 0o600 })
|
||||
}
|
||||
|
||||
private restoreSystemDefaultSnapshot(): void {
|
||||
private restoreSystemDefaultSnapshot(options: { detectExternalLogin: boolean }): void {
|
||||
// Why: detect whether an external tool (e.g. `codex auth login`) overwrote
|
||||
// auth.json while a managed account was active. If so, that external login
|
||||
// becomes the new system default — skip the stale snapshot restore.
|
||||
if (this.detectExternalLoginAndUpdateSnapshot()) {
|
||||
if (options.detectExternalLogin && this.detectExternalLoginAndUpdateSnapshot()) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -500,7 +555,17 @@ export class CodexRuntimeHomeService {
|
||||
return
|
||||
}
|
||||
|
||||
this.writeRuntimeAuth(readFileSync(snapshotPath, 'utf-8'))
|
||||
const snapshot = this.readSystemDefaultSnapshot(snapshotPath)
|
||||
if (!snapshot) {
|
||||
this.writeRuntimeAuth(readFileSync(snapshotPath, 'utf-8'))
|
||||
return
|
||||
}
|
||||
if (snapshot.authJson === null) {
|
||||
rmSync(this.getRuntimeAuthPath(), { force: true })
|
||||
this.lastWrittenAuthJson = null
|
||||
return
|
||||
}
|
||||
this.writeRuntimeAuth(snapshot.authJson)
|
||||
}
|
||||
|
||||
// Why: mirrors ClaudeRuntimeAuthService.detectExternalLoginAndUpdateSnapshot().
|
||||
@@ -514,7 +579,10 @@ export class CodexRuntimeHomeService {
|
||||
|
||||
const runtimeAuthPath = this.getRuntimeAuthPath()
|
||||
if (!existsSync(runtimeAuthPath)) {
|
||||
return false
|
||||
const snapshotPath = this.getSystemDefaultSnapshotPath()
|
||||
rmSync(snapshotPath, { force: true })
|
||||
this.lastWrittenAuthJson = null
|
||||
return true
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -535,10 +603,52 @@ export class CodexRuntimeHomeService {
|
||||
private writeRuntimeAuth(contents: string): void {
|
||||
// Why: auth.json contains sensitive credentials. Restrict to owner-only
|
||||
// so other users on a shared Linux/macOS machine cannot read it.
|
||||
if (this.fileContentsEqual(this.getRuntimeAuthPath(), contents)) {
|
||||
this.ensureOwnerOnlyMode(this.getRuntimeAuthPath())
|
||||
this.lastWrittenAuthJson = contents
|
||||
return
|
||||
}
|
||||
writeFileAtomically(this.getRuntimeAuthPath(), contents, { mode: 0o600 })
|
||||
this.lastWrittenAuthJson = contents
|
||||
}
|
||||
|
||||
private fileContentsEqual(targetPath: string, contents: string): boolean {
|
||||
try {
|
||||
return existsSync(targetPath) && readFileSync(targetPath, 'utf-8') === contents
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private ensureOwnerOnlyMode(targetPath: string): void {
|
||||
if (process.platform === 'win32') {
|
||||
return
|
||||
}
|
||||
try {
|
||||
chmodSync(targetPath, 0o600)
|
||||
} catch {
|
||||
/* Best effort: the next atomic write will set the restrictive mode. */
|
||||
}
|
||||
}
|
||||
|
||||
private readSystemDefaultSnapshot(snapshotPath: string): CodexSystemDefaultSnapshot | null {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(snapshotPath, 'utf-8')) as unknown
|
||||
if (
|
||||
parsed &&
|
||||
typeof parsed === 'object' &&
|
||||
!Array.isArray(parsed) &&
|
||||
'authJson' in parsed &&
|
||||
(typeof parsed.authJson === 'string' || parsed.authJson === null)
|
||||
) {
|
||||
return parsed as CodexSystemDefaultSnapshot
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
clearSystemDefaultSnapshot(): void {
|
||||
rmSync(this.getSystemDefaultSnapshotPath(), { force: true })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user