Fix Claude auth refresh clobbering live sessions (#1882)
This commit is contained in:
@@ -9,6 +9,10 @@ export function markClaudePtyExited(ptyId: string): void {
|
||||
liveClaudePtyIds.delete(ptyId)
|
||||
}
|
||||
|
||||
export function hasLiveClaudePtys(): boolean {
|
||||
return liveClaudePtyIds.size > 0
|
||||
}
|
||||
|
||||
export function beginClaudeAuthSwitch(): void {
|
||||
if (switchInProgress) {
|
||||
throw new Error('A Claude account switch is already in progress.')
|
||||
|
||||
@@ -995,6 +995,80 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(originalCredentials)
|
||||
})
|
||||
|
||||
it('preserves rejected runtime refreshes while a Claude terminal is live on Windows', async () => {
|
||||
setPlatform('win32')
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original', 'org-a')
|
||||
const refreshedCredentials = createClaudeCredentialsWithoutEmail('refreshed', 'org-a')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
originalCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, { organizationUuid: 'org-a' })
|
||||
],
|
||||
activeClaudeManagedAccountId: 'account-1'
|
||||
})
|
||||
const store = createStore(settings)
|
||||
|
||||
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
|
||||
const { markClaudePtyExited, markClaudePtySpawned } = await import('./live-pty-gate')
|
||||
const service = new ClaudeRuntimeAuthService(store as never)
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
markClaudePtySpawned('live-claude-pty')
|
||||
try {
|
||||
writeFileSync(runtimeCredentialsPath, refreshedCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(refreshedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials)
|
||||
} finally {
|
||||
markClaudePtyExited('live-claude-pty')
|
||||
}
|
||||
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials)
|
||||
})
|
||||
|
||||
it('does not persist live runtime refreshes with conflicting organization identity', async () => {
|
||||
setPlatform('win32')
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original', 'org-a')
|
||||
const conflictingCredentials = createClaudeCredentialsWithoutEmail('refreshed', 'org-b')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
'account-1',
|
||||
originalCredentials
|
||||
)
|
||||
const settings = createSettings({
|
||||
claudeManagedAccounts: [
|
||||
createClaudeAccount('account-1', managedAuthPath, { organizationUuid: 'org-a' })
|
||||
],
|
||||
activeClaudeManagedAccountId: 'account-1'
|
||||
})
|
||||
const store = createStore(settings)
|
||||
|
||||
const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service')
|
||||
const { markClaudePtyExited, markClaudePtySpawned } = await import('./live-pty-gate')
|
||||
const service = new ClaudeRuntimeAuthService(store as never)
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
markClaudePtySpawned('live-claude-pty')
|
||||
try {
|
||||
writeFileSync(runtimeCredentialsPath, conflictingCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(originalCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(conflictingCredentials)
|
||||
} finally {
|
||||
markClaudePtyExited('live-claude-pty')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects unverifiable refreshed runtime credentials', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsWithoutEmail('original')
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
resolveOwnedClaudeManagedAuthPath,
|
||||
writeClaudeManagedAuthFile
|
||||
} from './managed-auth-path'
|
||||
import { hasLiveClaudePtys } from './live-pty-gate'
|
||||
import { ClaudeRuntimePathResolver } from './runtime-paths'
|
||||
import {
|
||||
deleteActiveClaudeKeychainCredentialsStrict,
|
||||
@@ -47,7 +48,9 @@ type ClaudeAuthIdentity = {
|
||||
organizationUuid: string | null
|
||||
}
|
||||
|
||||
type ClaudeReadBackResult = { status: 'unchanged' | 'persisted' | 'rejected' }
|
||||
type ClaudeReadBackResult =
|
||||
| { status: 'unchanged' | 'persisted' }
|
||||
| { status: 'rejected'; runtimeCredentialsChanged: boolean; runtimeCredentialsJson?: string }
|
||||
type ClaudeReadBackMatch =
|
||||
| { kind: 'matched'; account: ClaudeManagedAccount; managedCredentialsJson: string }
|
||||
| { kind: 'none' | 'ambiguous' }
|
||||
@@ -250,6 +253,34 @@ export class ClaudeRuntimeAuthService {
|
||||
if (updatedCredentialsJson && this.isValidCredentialsJsonObject(updatedCredentialsJson)) {
|
||||
credentialsJson = updatedCredentialsJson
|
||||
}
|
||||
} else if (
|
||||
readBackResult.status === 'rejected' &&
|
||||
readBackResult.runtimeCredentialsChanged &&
|
||||
hasLiveClaudePtys()
|
||||
) {
|
||||
if (
|
||||
readBackResult.runtimeCredentialsJson &&
|
||||
this.liveRuntimeCredentialsCanUpdateActiveAccount(
|
||||
readBackResult.runtimeCredentialsJson,
|
||||
activeAccount,
|
||||
credentialsJson,
|
||||
this.readManagedOauthAccount(activeAccount)
|
||||
)
|
||||
) {
|
||||
// Why: this Claude process was launched under the active managed
|
||||
// account, but persistence still needs positive account proof.
|
||||
await this.writeManagedCredentials(activeAccount, readBackResult.runtimeCredentialsJson)
|
||||
credentialsJson = readBackResult.runtimeCredentialsJson
|
||||
} else {
|
||||
// Why: while Claude is running, an unknown refresh can still belong
|
||||
// to a live session. Rewriting stale managed auth logs that session out.
|
||||
console.warn(
|
||||
'[claude-runtime-auth] Preserving changed Claude runtime credentials while live Claude terminals are running'
|
||||
)
|
||||
this.lastSyncedAccountId = activeAccount.id
|
||||
this.hasMaterializedRuntimeAuth = true
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,6 +350,7 @@ export class ClaudeRuntimeAuthService {
|
||||
credentialsJson: string
|
||||
match: Extract<ClaudeReadBackMatch, { kind: 'matched' }>
|
||||
}[] = []
|
||||
const ambiguousCandidates: string[] = []
|
||||
let sawAmbiguousCandidate = false
|
||||
for (const runtimeContents of changedCandidates) {
|
||||
if (!this.isValidCredentialsJsonObject(runtimeContents)) {
|
||||
@@ -327,6 +359,7 @@ export class ClaudeRuntimeAuthService {
|
||||
const match = await this.findManagedAccountForRuntimeCredentials(runtimeContents)
|
||||
if (match.kind === 'ambiguous') {
|
||||
sawAmbiguousCandidate = true
|
||||
ambiguousCandidates.push(runtimeContents)
|
||||
continue
|
||||
}
|
||||
if (match.kind !== 'matched') {
|
||||
@@ -348,7 +381,12 @@ export class ClaudeRuntimeAuthService {
|
||||
if (sawAmbiguousCandidate) {
|
||||
console.warn('[claude-runtime-auth] Refusing ambiguous Claude auth read-back')
|
||||
}
|
||||
return { status: 'rejected' }
|
||||
return {
|
||||
status: 'rejected',
|
||||
runtimeCredentialsChanged: true,
|
||||
runtimeCredentialsJson:
|
||||
ambiguousCandidates.length === 1 ? ambiguousCandidates[0] : undefined
|
||||
}
|
||||
}
|
||||
const { credentialsJson: runtimeContents, match } =
|
||||
this.chooseFreshestReadBackCandidate(acceptedCandidates)
|
||||
@@ -368,7 +406,11 @@ export class ClaudeRuntimeAuthService {
|
||||
// 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 { status: 'rejected' }
|
||||
return {
|
||||
status: 'rejected',
|
||||
runtimeCredentialsChanged:
|
||||
this.runtimeCredentialsChangedSinceLastWrite(baselineCredentialsJson)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -498,6 +540,36 @@ export class ClaudeRuntimeAuthService {
|
||||
return 'match'
|
||||
}
|
||||
|
||||
private liveRuntimeCredentialsCanUpdateActiveAccount(
|
||||
runtimeCredentialsJson: string,
|
||||
account: ClaudeManagedAccount,
|
||||
managedCredentialsJson: string,
|
||||
managedOauthAccount: unknown
|
||||
): boolean {
|
||||
const match = this.runtimeCredentialsMatchAccount(
|
||||
runtimeCredentialsJson,
|
||||
account,
|
||||
managedCredentialsJson,
|
||||
managedOauthAccount
|
||||
)
|
||||
if (match === 'match') {
|
||||
return true
|
||||
}
|
||||
const identity = this.readIdentityFromCredentials(runtimeCredentialsJson)
|
||||
const managedIdentity = this.readIdentityFromCredentials(managedCredentialsJson)
|
||||
const managedOauthIdentity = this.readIdentityFromOauthAccount(managedOauthAccount)
|
||||
const selectedOrganizationUuid = this.normalizeField(
|
||||
account.organizationUuid ??
|
||||
managedIdentity?.organizationUuid ??
|
||||
managedOauthIdentity.organizationUuid
|
||||
)
|
||||
return (
|
||||
match === 'unverifiable' &&
|
||||
Boolean(selectedOrganizationUuid) &&
|
||||
identity?.organizationUuid === selectedOrganizationUuid
|
||||
)
|
||||
}
|
||||
|
||||
private readIdentityFromCredentials(credentialsJson: string): ClaudeAuthIdentity | null {
|
||||
let parsed: Record<string, unknown>
|
||||
try {
|
||||
@@ -1014,6 +1086,21 @@ export class ClaudeRuntimeAuthService {
|
||||
return currentCredentialsJson === previouslyWrittenCredentialsJson
|
||||
}
|
||||
|
||||
private runtimeCredentialsChangedSinceLastWrite(baselineCredentialsJson: string): boolean {
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
try {
|
||||
const currentCredentialsJson = existsSync(paths.credentialsPath)
|
||||
? readFileSync(paths.credentialsPath, 'utf-8')
|
||||
: null
|
||||
return (
|
||||
currentCredentialsJson !== null &&
|
||||
currentCredentialsJson !== (this.lastWrittenCredentialsJson ?? baselineCredentialsJson)
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private restoreRuntimeCredentials(credentialsJson: string | null): void {
|
||||
const paths = this.pathResolver.getRuntimePaths()
|
||||
if (credentialsJson !== null) {
|
||||
|
||||
@@ -122,6 +122,7 @@ import {
|
||||
setLocalPtyProvider,
|
||||
unregisterSshPtyProvider
|
||||
} from './pty'
|
||||
import { hasLiveClaudePtys } from '../claude-accounts/live-pty-gate'
|
||||
|
||||
const POWERSHELL_PROFILE_COMMAND = expect.stringMatching(
|
||||
/\. \$PROFILE[\s\S]*ORCA_OPENCODE_CONFIG_DIR[\s\S]*ORCA_PI_CODING_AGENT_DIR[\s\S]*UTF8/
|
||||
@@ -347,6 +348,29 @@ describe('registerPtyHandlers', () => {
|
||||
}
|
||||
|
||||
describe('spawn environment', () => {
|
||||
it('marks local Claude launches live until the PTY is killed', async () => {
|
||||
const prepareClaudeAuth = vi.fn(async () => ({
|
||||
configDir: '/tmp/claude',
|
||||
envPatch: {},
|
||||
stripAuthEnv: false,
|
||||
provenance: 'managed:account-1'
|
||||
}))
|
||||
registerPtyHandlers(mainWindow as never, undefined, undefined, undefined, prepareClaudeAuth)
|
||||
|
||||
const spawnResult = (await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
command: 'claude'
|
||||
})) as { id: string }
|
||||
|
||||
expect(prepareClaudeAuth).toHaveBeenCalledTimes(1)
|
||||
expect(hasLiveClaudePtys()).toBe(true)
|
||||
|
||||
await handlers.get('pty:kill')!(null, { id: spawnResult.id })
|
||||
|
||||
expect(hasLiveClaudePtys()).toBe(false)
|
||||
})
|
||||
|
||||
it('defaults LANG to en_US.UTF-8 when not inherited from process.env', async () => {
|
||||
const env = await spawnAndGetEnv(undefined, { LANG: undefined })
|
||||
expect(env.LANG).toBe('en_US.UTF-8')
|
||||
|
||||
Reference in New Issue
Block a user