Guard Claude auth read-back identity
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -101,6 +101,17 @@ function createClaudeAccount(id: string, managedAuthPath: string): ClaudeManaged
|
||||
}
|
||||
}
|
||||
|
||||
function createClaudeCredentialsJson(email: string, accessToken: string): string {
|
||||
return `${JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
email,
|
||||
accessToken,
|
||||
refreshToken: `${accessToken}-refresh`,
|
||||
expiresAt: Date.now() + 60_000
|
||||
}
|
||||
})}\n`
|
||||
}
|
||||
|
||||
describe('ClaudeRuntimeAuthService', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
@@ -178,4 +189,56 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe('{"token":"rotated"}\n')
|
||||
})
|
||||
|
||||
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')
|
||||
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()
|
||||
|
||||
writeFileSync(runtimeCredentialsPath, refreshedCredentials, 'utf-8')
|
||||
await service.syncForCurrentSelection()
|
||||
|
||||
expect(testState.managedKeychainCredentials.get('account-1')).toBe(refreshedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials)
|
||||
})
|
||||
|
||||
it('rejects runtime read-back from a different Claude identity', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const selectedCredentials = createClaudeCredentialsJson('user@example.com', 'selected')
|
||||
const staleCredentials = createClaudeCredentialsJson('other@example.com', 'stale')
|
||||
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(testState.managedKeychainCredentials.get('account-1')).toBe(selectedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(selectedCredentials)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -30,6 +30,10 @@ type ClaudeSystemDefaultSnapshot = {
|
||||
capturedAt: number
|
||||
}
|
||||
|
||||
type ClaudeAuthIdentity = {
|
||||
email: string | null
|
||||
}
|
||||
|
||||
export class ClaudeRuntimeAuthService {
|
||||
private readonly pathResolver = new ClaudeRuntimePathResolver()
|
||||
private mutationQueue: Promise<unknown> = Promise.resolve()
|
||||
@@ -110,7 +114,7 @@ export class ClaudeRuntimeAuthService {
|
||||
|
||||
await this.captureSystemDefaultSnapshotIfNeeded()
|
||||
|
||||
const credentialsJson = await this.readManagedCredentials(activeAccount)
|
||||
let credentialsJson = await this.readManagedCredentials(activeAccount)
|
||||
if (!credentialsJson) {
|
||||
console.warn(
|
||||
'[claude-runtime-auth] Active managed account is missing credentials, restoring system default'
|
||||
@@ -129,6 +133,7 @@ export class ClaudeRuntimeAuthService {
|
||||
// back to managed storage before overwriting runtime with managed state.
|
||||
if (this.lastSyncedAccountId === activeAccount.id) {
|
||||
await this.readBackRefreshedTokens(activeAccount)
|
||||
credentialsJson = (await this.readManagedCredentials(activeAccount)) ?? credentialsJson
|
||||
}
|
||||
|
||||
this.writeRuntimeCredentials(credentialsJson)
|
||||
@@ -163,6 +168,10 @@ export class ClaudeRuntimeAuthService {
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.runtimeCredentialsMatchAccount(runtimeContents, account)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
await writeManagedClaudeKeychainCredentials(account.id, runtimeContents)
|
||||
} else {
|
||||
@@ -198,6 +207,58 @@ export class ClaudeRuntimeAuthService {
|
||||
return accounts.find((account) => account.id === activeAccountId) ?? null
|
||||
}
|
||||
|
||||
private runtimeCredentialsMatchAccount(
|
||||
runtimeCredentialsJson: string,
|
||||
account: ClaudeManagedAccount
|
||||
): boolean {
|
||||
const identity = this.readIdentityFromCredentials(runtimeCredentialsJson)
|
||||
if (!identity) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Why: this mirrors the Codex runtime-home guard. If another Claude login
|
||||
// or missed live process rewrites shared runtime credentials, do not
|
||||
// persist those credentials into the selected managed account.
|
||||
if (account.email && identity.email && this.normalizeField(account.email) !== identity.email) {
|
||||
return false
|
||||
}
|
||||
|
||||
return Boolean(identity.email)
|
||||
}
|
||||
|
||||
private readIdentityFromCredentials(credentialsJson: string): ClaudeAuthIdentity | null {
|
||||
let parsed: Record<string, unknown>
|
||||
try {
|
||||
parsed = JSON.parse(credentialsJson) as Record<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const oauth = this.asRecord(parsed.claudeAiOauth)
|
||||
return {
|
||||
email: this.normalizeField(this.readString(oauth, 'email'))
|
||||
}
|
||||
}
|
||||
|
||||
private asRecord(value: unknown): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return null
|
||||
}
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
private readString(value: Record<string, unknown> | null, key: string): string | null {
|
||||
const candidate = value?.[key]
|
||||
return typeof candidate === 'string' ? candidate : null
|
||||
}
|
||||
|
||||
private normalizeField(value: string | null | undefined): string | null {
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
const trimmed = value.trim()
|
||||
return trimmed === '' ? null : trimmed
|
||||
}
|
||||
|
||||
private async readManagedCredentials(account: ClaudeManagedAccount): Promise<string | null> {
|
||||
if (process.platform === 'darwin') {
|
||||
return readManagedClaudeKeychainCredentials(account.id)
|
||||
@@ -316,7 +377,12 @@ export class ClaudeRuntimeAuthService {
|
||||
mkdirSync(dirname(credentialsPath), { recursive: true })
|
||||
// Why: repeated Claude spawns sync auth, but credentials rarely change.
|
||||
// Skipping unchanged rewrites avoids Windows EPERM contention in #1507.
|
||||
if (this.lastWrittenCredentialsJson === contents && existsSync(credentialsPath)) {
|
||||
// Still verify the file because another Claude process may have rewritten
|
||||
// runtime credentials since Orca last materialized them.
|
||||
if (
|
||||
this.lastWrittenCredentialsJson === contents &&
|
||||
this.fileContentsEqual(credentialsPath, contents)
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (this.fileContentsEqual(credentialsPath, contents)) {
|
||||
|
||||
Reference in New Issue
Block a user