Reject stale cold-start auth read-back
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -112,7 +112,8 @@ function createClaudeAccount(
|
||||
function createClaudeCredentialsJson(
|
||||
email: string,
|
||||
accessToken: string,
|
||||
organizationUuid: string | null = null
|
||||
organizationUuid: string | null = null,
|
||||
expiresAt = Date.now() + 60_000
|
||||
): string {
|
||||
return `${JSON.stringify({
|
||||
claudeAiOauth: {
|
||||
@@ -120,7 +121,7 @@ function createClaudeCredentialsJson(
|
||||
...(organizationUuid ? { organizationUuid } : {}),
|
||||
accessToken,
|
||||
refreshToken: `${accessToken}-refresh`,
|
||||
expiresAt: Date.now() + 60_000
|
||||
expiresAt
|
||||
}
|
||||
})}\n`
|
||||
}
|
||||
@@ -304,8 +305,18 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
|
||||
it('reads back verified same-account credentials on first sync after restart', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original')
|
||||
const refreshedCredentials = createClaudeCredentialsJson('user@example.com', 'refreshed')
|
||||
const originalCredentials = createClaudeCredentialsJson(
|
||||
'user@example.com',
|
||||
'original',
|
||||
null,
|
||||
1_000
|
||||
)
|
||||
const refreshedCredentials = createClaudeCredentialsJson(
|
||||
'user@example.com',
|
||||
'refreshed',
|
||||
null,
|
||||
2_000
|
||||
)
|
||||
writeFileSync(runtimeCredentialsPath, refreshedCredentials, 'utf-8')
|
||||
const managedAuthPath = createManagedClaudeAuth(
|
||||
testState.userDataDir,
|
||||
@@ -326,6 +337,40 @@ describe('ClaudeRuntimeAuthService', () => {
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(refreshedCredentials)
|
||||
})
|
||||
|
||||
it('rejects older same-account Claude credentials on first sync after restart', async () => {
|
||||
const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json')
|
||||
const staleRuntimeCredentials = createClaudeCredentialsJson(
|
||||
'user@example.com',
|
||||
'stale',
|
||||
null,
|
||||
1_000
|
||||
)
|
||||
const managedCredentials = createClaudeCredentialsJson(
|
||||
'user@example.com',
|
||||
'managed-newer',
|
||||
null,
|
||||
2_000
|
||||
)
|
||||
writeFileSync(runtimeCredentialsPath, staleRuntimeCredentials, '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()
|
||||
|
||||
expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(managedCredentials)
|
||||
expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(managedCredentials)
|
||||
})
|
||||
|
||||
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')
|
||||
|
||||
@@ -186,7 +186,9 @@ export class ClaudeRuntimeAuthService {
|
||||
clearLastWrittenCredentialsJson(
|
||||
accountId = this.store.getSettings().activeClaudeManagedAccountId
|
||||
): void {
|
||||
this.lastWrittenCredentialsJson = null
|
||||
if (accountId === this.store.getSettings().activeClaudeManagedAccountId) {
|
||||
this.lastWrittenCredentialsJson = null
|
||||
}
|
||||
this.skipNextReadBackForAccountId = accountId
|
||||
}
|
||||
|
||||
@@ -213,6 +215,15 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
return { status: 'rejected' }
|
||||
}
|
||||
// Why: on cold app start we cannot tell whether matching runtime
|
||||
// credentials are a fresh CLI refresh or stale state unless token
|
||||
// metadata proves runtime is newer than managed storage.
|
||||
if (
|
||||
this.lastWrittenCredentialsJson === null &&
|
||||
!this.runtimeCredentialsAreFresher(runtimeContents, baselineCredentialsJson)
|
||||
) {
|
||||
return { status: 'rejected' }
|
||||
}
|
||||
|
||||
await this.writeManagedCredentials(match.account, runtimeContents)
|
||||
if (options.updateLastWrittenCredentialsJson) {
|
||||
@@ -376,6 +387,33 @@ export class ClaudeRuntimeAuthService {
|
||||
}
|
||||
}
|
||||
|
||||
private runtimeCredentialsAreFresher(
|
||||
runtimeCredentialsJson: string,
|
||||
managedCredentialsJson: string
|
||||
): boolean {
|
||||
const runtimeFreshness = this.readFreshnessFromCredentials(runtimeCredentialsJson)
|
||||
const managedFreshness = this.readFreshnessFromCredentials(managedCredentialsJson)
|
||||
return (
|
||||
runtimeFreshness !== null && managedFreshness !== null && runtimeFreshness > managedFreshness
|
||||
)
|
||||
}
|
||||
|
||||
private readFreshnessFromCredentials(credentialsJson: string): number | 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 (
|
||||
this.readNumber(oauth, 'expiresAt') ??
|
||||
this.readNumber(oauth, 'expires_at') ??
|
||||
this.readNumber(oauth, 'expiry') ??
|
||||
this.readNumber(oauth, 'expires')
|
||||
)
|
||||
}
|
||||
|
||||
private readIdentityFromOauthAccount(oauthAccount: unknown): ClaudeAuthIdentity {
|
||||
const oauth = this.asRecord(oauthAccount)
|
||||
return {
|
||||
@@ -400,6 +438,18 @@ export class ClaudeRuntimeAuthService {
|
||||
return typeof candidate === 'string' ? candidate : null
|
||||
}
|
||||
|
||||
private readNumber(value: Record<string, unknown> | null, key: string): number | null {
|
||||
const candidate = value?.[key]
|
||||
if (typeof candidate === 'number' && Number.isFinite(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
if (typeof candidate === 'string') {
|
||||
const parsed = Number(candidate)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private normalizeField(value: string | null | undefined): string | null {
|
||||
if (!value) {
|
||||
return null
|
||||
|
||||
@@ -137,11 +137,17 @@ function encodeJwtPart(value: Record<string, unknown>): string {
|
||||
return Buffer.from(JSON.stringify(value)).toString('base64url')
|
||||
}
|
||||
|
||||
function createCodexAuthJson(email: string, accountId: string, refreshToken: string): string {
|
||||
function createCodexAuthJson(
|
||||
email: string,
|
||||
accountId: string,
|
||||
refreshToken: string,
|
||||
expiresAt?: number
|
||||
): string {
|
||||
const idToken = [
|
||||
encodeJwtPart({ alg: 'none', typ: 'JWT' }),
|
||||
encodeJwtPart({
|
||||
email,
|
||||
...(expiresAt === undefined ? {} : { exp: expiresAt }),
|
||||
'https://api.openai.com/auth': {
|
||||
chatgpt_account_id: accountId,
|
||||
workspace_account_id: accountId
|
||||
@@ -154,6 +160,7 @@ function createCodexAuthJson(email: string, accountId: string, refreshToken: str
|
||||
tokens: {
|
||||
id_token: idToken,
|
||||
account_id: accountId,
|
||||
...(expiresAt === undefined ? {} : { expires_at: expiresAt }),
|
||||
refresh_token: refreshToken
|
||||
}
|
||||
})}\n`
|
||||
@@ -1083,8 +1090,8 @@ describe('CodexRuntimeHomeService', () => {
|
||||
|
||||
it('reads back verified same-account refreshes on first sync after restart', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
const originalAuth = createCodexAuthJson('user@example.com', 'acct-1', 'original')
|
||||
const refreshedAuth = createCodexAuthJson('user@example.com', 'acct-1', 'refreshed')
|
||||
const originalAuth = createCodexAuthJson('user@example.com', 'acct-1', 'original', 1_000)
|
||||
const refreshedAuth = createCodexAuthJson('user@example.com', 'acct-1', 'refreshed', 2_000)
|
||||
writeFileSync(runtimeAuthPath, refreshedAuth, 'utf-8')
|
||||
const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', originalAuth)
|
||||
const managedAuthPath = join(managedHomePath, 'auth.json')
|
||||
@@ -1114,6 +1121,39 @@ describe('CodexRuntimeHomeService', () => {
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(refreshedAuth)
|
||||
})
|
||||
|
||||
it('rejects older same-account Codex auth on first sync after restart', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
const staleRuntimeAuth = createCodexAuthJson('user@example.com', 'acct-1', 'stale', 1_000)
|
||||
const managedAuth = createCodexAuthJson('user@example.com', 'acct-1', 'managed-newer', 2_000)
|
||||
writeFileSync(runtimeAuthPath, staleRuntimeAuth, 'utf-8')
|
||||
const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', managedAuth)
|
||||
const managedAuthPath = join(managedHomePath, 'auth.json')
|
||||
const store = createStore(
|
||||
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 { CodexRuntimeHomeService } = await import('./runtime-home-service')
|
||||
new CodexRuntimeHomeService(store as never)
|
||||
|
||||
expect(readFileSync(managedAuthPath, 'utf-8')).toBe(managedAuth)
|
||||
expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe(managedAuth)
|
||||
})
|
||||
|
||||
it('does not contaminate the incoming Codex account during account switch', async () => {
|
||||
const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
|
||||
writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
|
||||
|
||||
@@ -31,7 +31,12 @@ type CodexSystemDefaultSnapshot = {
|
||||
|
||||
type CodexReadBackResult = 'unchanged' | 'persisted' | 'rejected'
|
||||
type CodexReadBackMatch =
|
||||
| { kind: 'matched'; account: CodexManagedAccount; managedAuthPath: string }
|
||||
| {
|
||||
kind: 'matched'
|
||||
account: CodexManagedAccount
|
||||
managedAuthPath: string
|
||||
managedAuthContents: string
|
||||
}
|
||||
| { kind: 'none' | 'ambiguous' }
|
||||
|
||||
export class CodexRuntimeHomeService {
|
||||
@@ -150,7 +155,9 @@ export class CodexRuntimeHomeService {
|
||||
// so the read-back must be skipped to avoid overwriting them with stale
|
||||
// runtime tokens.
|
||||
clearLastWrittenAuthJson(accountId = this.store.getSettings().activeCodexManagedAccountId): void {
|
||||
this.lastWrittenAuthJson = null
|
||||
if (accountId === this.store.getSettings().activeCodexManagedAccountId) {
|
||||
this.lastWrittenAuthJson = null
|
||||
}
|
||||
this.skipNextReadBackForAccountId = accountId
|
||||
}
|
||||
|
||||
@@ -175,6 +182,14 @@ export class CodexRuntimeHomeService {
|
||||
}
|
||||
return 'rejected'
|
||||
}
|
||||
// Why: after app restart, Orca has no last-written baseline. Identity
|
||||
// alone cannot prove runtime auth is newer than managed storage.
|
||||
if (
|
||||
this.lastWrittenAuthJson === null &&
|
||||
!this.runtimeAuthIsFresher(runtimeContents, match.managedAuthContents)
|
||||
) {
|
||||
return 'rejected'
|
||||
}
|
||||
|
||||
writeFileAtomically(match.managedAuthPath, runtimeContents, { mode: 0o600 })
|
||||
if (options.updateLastWrittenAuthJson) {
|
||||
@@ -216,20 +231,19 @@ export class CodexRuntimeHomeService {
|
||||
}
|
||||
|
||||
private findManagedAccountForRuntimeAuth(runtimeAuthContents: string): CodexReadBackMatch {
|
||||
const matches: { account: CodexManagedAccount; managedAuthPath: string }[] = []
|
||||
const matches: {
|
||||
account: CodexManagedAccount
|
||||
managedAuthPath: string
|
||||
managedAuthContents: string
|
||||
}[] = []
|
||||
for (const account of this.store.getSettings().codexManagedAccounts) {
|
||||
const managedAuthPath = join(account.managedHomePath, 'auth.json')
|
||||
if (!existsSync(managedAuthPath)) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
this.runtimeAuthMatchesAccount(
|
||||
runtimeAuthContents,
|
||||
account,
|
||||
readFileSync(managedAuthPath, 'utf-8')
|
||||
)
|
||||
) {
|
||||
matches.push({ account, managedAuthPath })
|
||||
const managedAuthContents = readFileSync(managedAuthPath, 'utf-8')
|
||||
if (this.runtimeAuthMatchesAccount(runtimeAuthContents, account, managedAuthContents)) {
|
||||
matches.push({ account, managedAuthPath, managedAuthContents })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +303,14 @@ export class CodexRuntimeHomeService {
|
||||
)
|
||||
}
|
||||
|
||||
private runtimeAuthIsFresher(runtimeAuthContents: string, managedAuthContents: string): boolean {
|
||||
const runtimeFreshness = this.readFreshnessFromAuthContents(runtimeAuthContents)
|
||||
const managedFreshness = this.readFreshnessFromAuthContents(managedAuthContents)
|
||||
return (
|
||||
runtimeFreshness !== null && managedFreshness !== null && runtimeFreshness > managedFreshness
|
||||
)
|
||||
}
|
||||
|
||||
private identityFieldMatches(selectedField: string | null, runtimeField: string | null): boolean {
|
||||
return !selectedField || Boolean(runtimeField && selectedField === runtimeField)
|
||||
}
|
||||
@@ -332,6 +354,29 @@ export class CodexRuntimeHomeService {
|
||||
}
|
||||
}
|
||||
|
||||
private readFreshnessFromAuthContents(contents: string): number | null {
|
||||
let raw: Record<string, unknown>
|
||||
try {
|
||||
raw = JSON.parse(contents) as Record<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
const tokens = this.readRecordClaim(raw, 'tokens')
|
||||
const idToken = this.normalizeField(
|
||||
this.readStringClaim(tokens, 'id_token') ?? this.readStringClaim(tokens, 'idToken')
|
||||
)
|
||||
const payload = idToken ? this.parseJwtPayload(idToken) : null
|
||||
return (
|
||||
this.readNumberClaim(tokens, 'expires_at') ??
|
||||
this.readNumberClaim(tokens, 'expiresAt') ??
|
||||
this.readNumberClaim(tokens, 'expiry') ??
|
||||
this.readNumberClaim(tokens, 'expires') ??
|
||||
this.readNumberClaim(payload, 'exp') ??
|
||||
this.readNumberClaim(payload, 'iat')
|
||||
)
|
||||
}
|
||||
|
||||
private parseJwtPayload(token: string): Record<string, unknown> | null {
|
||||
const parts = token.split('.')
|
||||
if (parts.length < 2) {
|
||||
@@ -367,6 +412,18 @@ export class CodexRuntimeHomeService {
|
||||
return typeof claim === 'string' ? claim : null
|
||||
}
|
||||
|
||||
private readNumberClaim(value: Record<string, unknown> | null, key: string): number | null {
|
||||
const claim = value?.[key]
|
||||
if (typeof claim === 'number' && Number.isFinite(claim)) {
|
||||
return claim
|
||||
}
|
||||
if (typeof claim === 'string') {
|
||||
const parsed = Number(claim)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private normalizeField(value: string | null | undefined): string | null {
|
||||
if (!value) {
|
||||
return null
|
||||
|
||||
Reference in New Issue
Block a user