diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 9475f57a0..02fc838c8 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -73,7 +73,7 @@ With `CCSTATUSLINE_DEV_RELOAD=1`, Ctrl+R restarts the interactive process with i If you use a custom Claude config location, set `CLAUDE_CONFIG_DIR` and ccstatusline will read/write that path instead of `~/.claude`. -On macOS, usage credentials for a custom profile come from `Claude Code-credentials-`, then that profile's `.credentials.json`; the lookup does not fall back to another profile's Keychain entry. The hash uses the raw `CLAUDE_CONFIG_DIR` value normalized to NFC, without path resolution. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides that hash input, including an empty value to force the default service lookup. Default lookup tries the plain service, then the same service scoped to `os.userInfo().username` if no OAuth token was found, then discovered suffixed services and the credentials file. If the OS username cannot be resolved, the account-scoped retry is skipped. Both access and refresh tokens are preserved for cache identity checks. Other platforms use the credentials file directly. Each Keychain subprocess has a five-second timeout; a timeout stops further Keychain probes for that lookup (including the username retry) and continues with the current profile’s credentials file, while an ordinary miss continues to the next source. A missing OAuth login triggers a profile-specific 30-second lookup backoff. +On macOS, usage credentials for a custom profile come from `Claude Code-credentials-`, then that profile's `.credentials.json`; the lookup does not fall back to another profile's Keychain entry. The hash uses the raw `CLAUDE_CONFIG_DIR` value normalized to NFC, without path resolution. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides that hash input, including an empty value to force the default service lookup. Default lookup tries the plain service, then the same service scoped to `os.userInfo().username` if no OAuth token was found, then the credentials file; like a custom profile's, it never falls back to another profile's Keychain entry. If the OS username cannot be resolved, the account-scoped retry is skipped. Both access and refresh tokens are preserved for cache identity checks. Other platforms use the credentials file directly. Each Keychain subprocess has a five-second timeout; a timeout stops further Keychain probes for that lookup (including the username retry) and continues with the current profile’s credentials file, while an ordinary miss continues to the next source. A missing OAuth login triggers a profile-specific 30-second lookup backoff. Usage file names use the first 16 hex characters of SHA-256 of `path.resolve(getClaudeConfigDir())`, including for the default profile. This file identity is separate from the raw environment value used for Keychain service selection. All usage cache freshness checks, stale reads, request locks, lock cleanup, and no-credentials backoff files use that profile's names. Profiles sharing one home keep independent data and backoff deadlines, even if they use the same login. diff --git a/docs/USAGE.md b/docs/USAGE.md index 2496063ec..c1dbe5303 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -206,7 +206,7 @@ The Skills widget reads skill activity recorded by Claude Code hooks, which run ## Usage Credentials and Cache -Usage API requests read credentials from the active Claude config directory's `.credentials.json` on Linux and Windows. On macOS, a custom `CLAUDE_CONFIG_DIR` selects its matching Keychain service first, then falls back only to that profile's credentials file. `CLAUDE_SECURESTORAGE_CONFIG_DIR`, when set, overrides the value used to select the Keychain service; an empty value selects the default service lookup. With the default service lookup, ccstatusline tries `Claude Code-credentials` by service name, then retries that service with the OS username if no OAuth token was found, then tries matching suffixed services and the credentials file. A successful service-only lookup still takes precedence; the username retry does not replace a stale but well-formed token. +Usage API requests read credentials from the active Claude config directory's `.credentials.json` on Linux and Windows. On macOS, a custom `CLAUDE_CONFIG_DIR` selects its matching Keychain service first, then falls back only to that profile's credentials file. `CLAUDE_SECURESTORAGE_CONFIG_DIR`, when set, overrides the value used to select the Keychain service; an empty value selects the default service lookup. With the default service lookup, ccstatusline tries `Claude Code-credentials` by service name, then retries that service with the OS username if no OAuth token was found, then the credentials file; suffixed services belong to other profiles and are not read. A successful service-only lookup still takes precedence; the username retry does not replace a stale but well-formed token. Usage caches and backoff locks are stored separately for each effective Claude config directory, so profiles sharing a home do not replace each other's data or block each other's requests. File names use a hash of the resolved config directory, including for the default profile. The old shared `usage.json`, `usage.lock`, and `usage-credentials.lock` files are ignored and left untouched; after upgrading, each profile fills a new cache on its next lookup instead of migrating shared data or backoff deadlines. diff --git a/src/utils/__tests__/usage-fetch.test.ts b/src/utils/__tests__/usage-fetch.test.ts index ae6ed24d4..c816e050a 100644 --- a/src/utils/__tests__/usage-fetch.test.ts +++ b/src/utils/__tests__/usage-fetch.test.ts @@ -64,6 +64,8 @@ interface TokenHome { home: string; } +interface DefaultProfileKeychainHome extends TokenHome { readSecurityCalls: () => string[] } + interface ProbeOptions { claudeConfigDir?: string; claudeSecureStorageConfigDir?: string; @@ -75,6 +77,7 @@ interface ProbeOptions { mode?: 'error' | 'status' | 'success' | 'unexpected'; nowMs: number; pathDir?: string; + platform?: NodeJS.Platform; requiredFields?: string[]; responseBody?: string; responseHeaders?: Record; @@ -208,6 +211,11 @@ https.request = (...args) => { return request; }; +// Lets a test take the macOS keychain path on any host +if (process.env.TEST_PLATFORM) { + Object.defineProperty(process, 'platform', { value: process.env.TEST_PLATFORM }); +} + const { fetchAccountEmail, fetchUsageData, getUsageAccountKey, getUsageFetchedAtMs, isStaleUsageFallback, lookUpUsageAccount } = await import(${JSON.stringify(usageModulePath)}); const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'); @@ -302,6 +310,60 @@ process.stdout.write(JSON.stringify({ }; } + // The default profile (no CLAUDE_CONFIG_DIR, so ~/.claude) on a Mac where + // a second profile, CLAUDE_CONFIG_DIR=/Users/example/.claude-work, is + // logged in. The stubbed keychain holds that profile's login under its + // suffixed service and lists it in a dump. The default profile's plain + // item holds plainItem, or is missing. + function createDefaultProfileKeychainHome(name: string, plainItem?: string): DefaultProfileKeychainHome { + const home = path.join(tempRoot, `home-${name}`); + const bin = path.join(tempRoot, `bin-${name}`); + const claudeConfig = path.join(home, '.claude'); + const plainItemFile = path.join(bin, 'plain-item.json'); + const otherProfileItemFile = path.join(bin, 'other-profile-item.json'); + const dumpFile = path.join(bin, 'keychain-dump.txt'); + const callLog = path.join(bin, 'security-calls.log'); + const otherProfileService = `Claude Code-credentials-${createHash('sha256').update('/Users/example/.claude-work').digest('hex').slice(0, 8)}`; + + fs.mkdirSync(claudeConfig, { recursive: true }); + fs.mkdirSync(bin, { recursive: true }); + + if (plainItem !== undefined) { + fs.writeFileSync(plainItemFile, plainItem); + } + fs.writeFileSync(otherProfileItemFile, JSON.stringify({ claudeAiOauth: { accessToken: 'other-profile-access', refreshToken: 'other-profile-refresh' } })); + fs.writeFileSync(dumpFile, [ + 'keychain: "/Users/example/Library/Keychains/login.keychain-db"', + 'version: 512', + 'class: "genp"', + 'attributes:', + ` "svce"="${otherProfileService}"`, + ' "mdat"="20240301010101Z"', + '' + ].join('\n')); + fs.writeFileSync(path.join(bin, 'security'), [ + '#!/bin/sh', + `echo "$*" >> '${callLog}'`, + 'case "$1:$3" in', + ` 'find-generic-password:Claude Code-credentials') [ -f '${plainItemFile}' ] || exit 44; exec /bin/cat '${plainItemFile}' ;;`, + ` 'find-generic-password:${otherProfileService}') exec /bin/cat '${otherProfileItemFile}' ;;`, + ` dump-keychain:*) exec /bin/cat '${dumpFile}' ;;`, + 'esac', + 'exit 44', + '' + ].join('\n')); + fs.chmodSync(path.join(bin, 'security'), 0o755); + + return { + bin, + claudeConfig, + home, + readSecurityCalls: () => fs.existsSync(callLog) + ? fs.readFileSync(callLog, 'utf8').split('\n').filter(line => line !== '') + : [] + }; + } + function createTimedOutSecurityHome(name: string): TokenHome { const tokenHome = createTokenHome(name); const securityScript = path.join(tokenHome.bin, 'security'); @@ -364,6 +426,10 @@ process.stdout.write(JSON.stringify({ env.HTTPS_PROXY = options.httpsProxy; } + if (options.platform !== undefined) { + env.TEST_PLATFORM = options.platform; + } + if (options.lockWrittenDuringRequest !== undefined) { env.TEST_LOCK_DURING_REQUEST = options.lockWrittenDuringRequest; } @@ -396,6 +462,7 @@ process.stdout.write(JSON.stringify({ return { cleanup, + createDefaultProfileKeychainHome, createEmptyHome, createTimedOutSecurityHome, createTokenHome, @@ -1376,9 +1443,9 @@ describe('fetchUsageData error handling', () => { expect(renderAt(nowMs).first).toEqual({ error: 'no-credentials' }); // An API-key user has no OAuth login to find, and on macOS each - // lookup spawns `security` twice, a full keychain dump included. - // Later renders inside the window skip the lookup entirely, so a - // login made meanwhile is only picked up once it ends. + // lookup spawns `security`. Later renders inside the window skip + // the lookup entirely, so a login made meanwhile is only picked up + // once it ends. fs.writeFileSync(credentialsFile, JSON.stringify({ claudeAiOauth: { accessToken: 'test-token' } })); const backedOff = renderAt(nowMs + 10000); expect(backedOff.first).toEqual({ error: 'no-credentials' }); @@ -1397,6 +1464,64 @@ describe('fetchUsageData error handling', () => { } }); + it('uses the default profile\'s own login on macOS, not another profile\'s keychain item, when its plain item is missing', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createDefaultProfileKeychainHome('default-profile-file-login'); + writeUsageCredentials(home.claudeConfig, { accessToken: 'default-access', refreshToken: 'default-refresh' }); + + const result = harness.runProbe({ + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + platform: 'darwin', + responseBody: successResponseBody + }); + + expect(result.first).toMatchObject({ sessionUsage: 42, weeklyUsage: 17 }); + expect(result.requestCount).toBe(1); + expect(result.requestAuthorization).toBe('Bearer default-access'); + expect(home.readSecurityCalls()).toEqual([ + 'find-generic-password -s Claude Code-credentials -w', + `find-generic-password -s Claude Code-credentials -a ${os.userInfo().username} -w` + ]); + } finally { + harness.cleanup(); + } + }); + + it('reports no credentials on macOS, not another profile\'s usage, when the default profile has no login', () => { + const harness = createProbeHarness(); + + try { + // A plain item holding only an MCP server's OAuth tokens (#521) + const home = harness.createDefaultProfileKeychainHome( + 'default-profile-no-login', + JSON.stringify({ mcpOAuth: { 'example-server': { accessToken: 'mcp-access' } } }) + ); + + const result = harness.runProbe({ + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + platform: 'darwin', + responseBody: successResponseBody + }); + + expect(result.first).toEqual({ error: 'no-credentials' }); + expect(result.requestCount).toBe(0); + expect(home.readSecurityCalls()).toEqual([ + 'find-generic-password -s Claude Code-credentials -w', + `find-generic-password -s Claude Code-credentials -a ${os.userInfo().username} -w` + ]); + } finally { + harness.cleanup(); + } + }); + it.skipIf(process.platform !== 'darwin')('stops default Keychain probes after a real fake-security timeout and still uses the credentials file', { timeout: 15_000 }, () => { const harness = createProbeHarness(); diff --git a/src/utils/__tests__/usage-token-buffer.test.ts b/src/utils/__tests__/usage-token-buffer.test.ts deleted file mode 100644 index a64027819..000000000 --- a/src/utils/__tests__/usage-token-buffer.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import * as childProcess from 'node:child_process'; -import { createRequire } from 'node:module'; -import type { Mock } from 'vitest'; -import { - afterEach, - beforeEach, - describe, - expect, - it, - vi -} from 'vitest'; - -import { getUsageToken } from '../usage-fetch'; - -vi.mock('node:child_process', () => ({ - execSync: vi.fn(), - execFileSync: vi.fn(), - spawnSync: vi.fn() -})); - -const require = createRequire(import.meta.url); -const { execFileSync: realExecFileSync } = require('node:child_process') as { execFileSync: typeof childProcess.execFileSync }; -const mockedExecFileSync = childProcess.execFileSync as Mock; - -const ORIGINAL_CLAUDE_CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR; -const ORIGINAL_SECURESTORAGE_CONFIG_DIR = process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR; - -describe('getUsageToken dump-keychain behavior', () => { - beforeEach(() => { - // The candidate scan under test only runs for the default profile, so - // shed any config-dir variables leaking in from the environment. - delete process.env.CLAUDE_CONFIG_DIR; - delete process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR; - mockedExecFileSync.mockReset(); - mockedExecFileSync.mockImplementation(realExecFileSync); - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); - }); - - afterEach(() => { - delete process.env.CLAUDE_CONFIG_DIR; - delete process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR; - if (ORIGINAL_CLAUDE_CONFIG_DIR !== undefined) { - process.env.CLAUDE_CONFIG_DIR = ORIGINAL_CLAUDE_CONFIG_DIR; - } - if (ORIGINAL_SECURESTORAGE_CONFIG_DIR !== undefined) { - process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR = ORIGINAL_SECURESTORAGE_CONFIG_DIR; - } - vi.restoreAllMocks(); - mockedExecFileSync.mockReset(); - mockedExecFileSync.mockImplementation(realExecFileSync); - }); - - it('uses an expanded maxBuffer when dumping keychains for hashed fallbacks', () => { - let dumpMaxBuffer: number | undefined; - - mockedExecFileSync.mockImplementation((command: string, args?: string[], options?: { maxBuffer?: number }) => { - if (command !== 'security') { - return realExecFileSync(command, args, options); - } - - if (!args) { - throw new Error('Expected security arguments'); - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { - throw new Error('missing exact credential'); - } - - if (args[0] === 'dump-keychain') { - dumpMaxBuffer = options?.maxBuffer; - return [ - 'keychain: "/Users/example/Library/Keychains/login.keychain-db"', - 'version: 512', - 'class: "genp"', - 'attributes:', - ' "svce"="Claude Code-credentials-hashed"', - ' "mdat"="20240301010101Z"' - ].join('\n'); - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials-hashed') { - return JSON.stringify({ claudeAiOauth: { accessToken: 'hashed-token' } }); - } - - throw new Error(`Unexpected security args: ${args.join(' ')}`); - }); - - expect(getUsageToken()).toBe('hashed-token'); - expect(dumpMaxBuffer).toBe(8 * 1024 * 1024); - }); -}); diff --git a/src/utils/__tests__/usage-token.test.ts b/src/utils/__tests__/usage-token.test.ts index 31e261d48..bb3324d67 100644 --- a/src/utils/__tests__/usage-token.test.ts +++ b/src/utils/__tests__/usage-token.test.ts @@ -18,8 +18,7 @@ import { getMacKeychainConfigDirService, getUsageCredentials, getUsageLoginFingerprint, - getUsageToken, - parseMacKeychainCredentialCandidates + getUsageToken } from '../usage-fetch'; vi.mock('node:child_process', () => ({ @@ -63,28 +62,15 @@ function makeExecFileTimeoutError(): Error & { code: string } { return Object.assign(new Error('child process failed'), { code: 'ETIMEDOUT' }); } -function encodeAsciiAsHex(value: string): string { - return Buffer.from(value, 'utf8').toString('hex'); -} - -function makeKeychainBlock(service: string, modifiedAt?: { raw?: string; quoted?: string }): string { - const lines = [ +function makeKeychainBlock(service: string): string { + return [ 'keychain: "/Users/example/Library/Keychains/login.keychain-db"', 'version: 512', 'class: "genp"', 'attributes:', - ` "svce"="${service}"` - ]; - - if (modifiedAt?.raw && modifiedAt.quoted) { - lines.push(` "mdat"=0x${modifiedAt.raw} "${modifiedAt.quoted}"`); - } else if (modifiedAt?.raw) { - lines.push(` "mdat"=0x${modifiedAt.raw}`); - } else if (modifiedAt?.quoted) { - lines.push(` "mdat"="${modifiedAt.quoted}"`); - } - - return lines.join('\n'); + ` "svce"="${service}"`, + ' "mdat"="20240301010101Z"' + ].join('\n'); } function getSecurityCallLog(): string[] { @@ -96,6 +82,37 @@ function getSecurityCallLog(): string[] { }); } +// A second profile, CLAUDE_CONFIG_DIR=/fake/claude-work, is logged in: the +// keychain holds its login under that profile's suffixed service and lists it +// in a dump. The default profile's plain item holds plainItem, or is missing. +function mockKeychainWithOtherProfileLogin(plainItem?: string): void { + const otherProfileService = makeConfigDirService('/fake/claude-work'); + + mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { + if (command !== 'security' || !args) { + throw new Error(`Unexpected security args: ${args?.join(' ')}`); + } + + if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { + if (plainItem === undefined) { + throw new Error('missing exact credential'); + } + + return plainItem; + } + + if (args[0] === 'dump-keychain') { + return makeKeychainBlock(otherProfileService); + } + + if (args[0] === 'find-generic-password' && args[2] === otherProfileService) { + return makeTokenPayload('other-profile-token', 'other-profile-refresh-token'); + } + + throw new Error(`Unexpected security args: ${args.join(' ')}`); + }); +} + function mockCredentialsFile(payload?: string): void { vi.spyOn(fs, 'readFileSync').mockImplementation((filePath, options) => { if (filePath === CREDENTIALS_FILE) { @@ -111,35 +128,6 @@ function mockCredentialsFile(payload?: string): void { }); } -describe('parseMacKeychainCredentialCandidates', () => { - it('returns hashed macOS credential candidates sorted newest-first and excludes the exact service', () => { - const dump = [ - makeKeychainBlock('Claude Code-credentials', { quoted: '20240101010101Z' }), - makeKeychainBlock('Claude Code-credentials-old', { quoted: '20240201010101Z' }), - makeKeychainBlock('Claude Code-credentials-new', { quoted: '20240301010101Z' }) - ].join('\n'); - - expect(parseMacKeychainCredentialCandidates(dump)).toEqual([ - 'Claude Code-credentials-new', - 'Claude Code-credentials-old' - ]); - }); - - it('uses discovered order when modified times are unavailable and parses hex-only timestamps when present', () => { - const dump = [ - makeKeychainBlock('Claude Code-credentials-first'), - makeKeychainBlock('Claude Code-credentials-second', { raw: encodeAsciiAsHex('20240401010101Z\0') }), - makeKeychainBlock('Claude Code-credentials-third') - ].join('\n'); - - expect(parseMacKeychainCredentialCandidates(dump)).toEqual([ - 'Claude Code-credentials-second', - 'Claude Code-credentials-first', - 'Claude Code-credentials-third' - ]); - }); -}); - describe('getUsageToken', () => { beforeEach(() => { vi.restoreAllMocks(); @@ -153,9 +141,9 @@ describe('getUsageToken', () => { mockedExecFileSync.mockReset(); }); - it('prefers the exact macOS keychain service over hashed fallbacks and files', () => { + it('prefers the exact macOS keychain service over the credentials file', () => { vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); - mockCredentialsFile(); + mockCredentialsFile(makeTokenPayload('file-token')); mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { if (command === 'security' && args?.[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { return makeTokenPayload('exact-token'); @@ -219,85 +207,54 @@ describe('getUsageToken', () => { throw new Error('missing exact credential'); } - if (args[0] === 'dump-keychain') { - return ''; - } - throw new Error(`Unexpected security args: ${args.join(' ')}`); }); expect(getUsageToken()).toBe('file-token'); expect(getSecurityCallLog()).toEqual([ - 'find-generic-password -s Claude Code-credentials -w', - 'dump-keychain' + 'find-generic-password -s Claude Code-credentials -w' ]); }); - it('tries the newest hashed macOS keychain candidate after an exact miss', () => { - const dump = [ - makeKeychainBlock('Claude Code-credentials-old', { quoted: '20240201010101Z' }), - makeKeychainBlock('Claude Code-credentials-new', { quoted: '20240301010101Z' }) - ].join('\n'); - + it('uses the default profile\'s credentials file after an exact miss, not another profile\'s keychain item', () => { vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); - mockCredentialsFile(); - mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { - if (command !== 'security' || !args) { - throw new Error(`Unexpected security args: ${args?.join(' ')}`); - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { - throw new Error('missing exact credential'); - } - - if (args[0] === 'dump-keychain') { - return dump; - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials-new') { - return makeTokenPayload('hashed-token'); - } + mockCredentialsFile(makeTokenPayload('file-token', 'file-refresh-token')); + mockKeychainWithOtherProfileLogin(); - throw new Error(`Unexpected security args: ${args.join(' ')}`); + expect(getUsageToken()).toBe('file-token'); + expect(getUsageCredentials()).toEqual({ + accessToken: 'file-token', + refreshToken: 'file-refresh-token' }); - - expect(getUsageToken()).toBe('hashed-token'); - expect(getUsageToken()).toBe('hashed-token'); expect(getSecurityCallLog()).toEqual([ 'find-generic-password -s Claude Code-credentials -w', 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-new -w', 'find-generic-password -s Claude Code-credentials -w', - 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-new -w' + 'find-generic-password -s Claude Code-credentials -a testuser -w' ]); }); - it('falls back to ~/.claude/.credentials.json on macOS when keychain lookups miss or parse invalid data', () => { - const dump = makeKeychainBlock('Claude Code-credentials-hashed', { quoted: '20240301010101Z' }); + it('finds no login rather than another profile\'s when the exact item holds only MCP tokens', () => { + vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); + mockCredentialsFile(); + mockKeychainWithOtherProfileLogin(JSON.stringify({ mcpOAuth: { 'example-server': { accessToken: 'mcp-token' } } })); + + expect(getUsageCredentials()).toBeNull(); + expect(getSecurityCallLog()).toEqual([ + 'find-generic-password -s Claude Code-credentials -w', + 'find-generic-password -s Claude Code-credentials -a testuser -w' + ]); + }); + it('falls back to ~/.claude/.credentials.json on macOS when the keychain item holds invalid data', () => { vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); mockCredentialsFile(makeTokenPayload('file-token')); mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { - if (command !== 'security' || !args) { - throw new Error(`Unexpected security args: ${args?.join(' ')}`); - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { - throw new Error('missing exact credential'); - } - - if (args[0] === 'dump-keychain') { - return dump; - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials-hashed') { + if (command === 'security' && args?.[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { return 'not-json'; } - throw new Error(`Unexpected security args: ${args.join(' ')}`); + throw new Error(`Unexpected security args: ${args?.join(' ')}`); }); expect(getUsageToken()).toBe('file-token'); @@ -305,34 +262,22 @@ describe('getUsageToken', () => { expect(getSecurityCallLog()).toEqual([ 'find-generic-password -s Claude Code-credentials -w', 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-hashed -w', 'find-generic-password -s Claude Code-credentials -w', - 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-hashed -w' + 'find-generic-password -s Claude Code-credentials -a testuser -w' ]); }); it('bounds every macOS keychain read with a timeout', () => { - const dump = makeKeychainBlock('Claude Code-credentials-hashed', { quoted: '20240301010101Z' }); - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); mockCredentialsFile(); - mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { - if (command === 'security' && args?.[0] === 'dump-keychain') { - return dump; - } - + mockedExecFileSync.mockImplementation(() => { throw new Error('security timed out'); }); expect(getUsageToken()).toBeNull(); expect(getSecurityCallLog()).toEqual([ 'find-generic-password -s Claude Code-credentials -w', - 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-hashed -w' + 'find-generic-password -s Claude Code-credentials -a testuser -w' ]); // A blocked `security` (e.g. waiting on a keychain unlock prompt) // must not hold the status line until someone answers it. @@ -367,43 +312,6 @@ describe('getUsageToken', () => { ]); }); - it('stops trying macOS keychain candidates after one times out', () => { - const dump = [ - makeKeychainBlock('Claude Code-credentials-new', { quoted: '20240301010101Z' }), - makeKeychainBlock('Claude Code-credentials-old', { quoted: '20240201010101Z' }) - ].join('\n'); - - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin'); - mockCredentialsFile(makeTokenPayload('file-token')); - mockedExecFileSync.mockImplementation((command: string, args?: string[]) => { - if (command !== 'security' || !args) { - throw new Error(`Unexpected security args: ${args?.join(' ')}`); - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials') { - throw new Error('missing exact credential'); - } - - if (args[0] === 'dump-keychain') { - return dump; - } - - if (args[0] === 'find-generic-password' && args[2] === 'Claude Code-credentials-new') { - throw makeExecFileTimeoutError(); - } - - throw new Error(`Unexpected security args: ${args.join(' ')}`); - }); - - expect(getUsageToken()).toBe('file-token'); - expect(getSecurityCallLog()).toEqual([ - 'find-generic-password -s Claude Code-credentials -w', - 'find-generic-password -s Claude Code-credentials -a testuser -w', - 'dump-keychain', - 'find-generic-password -s Claude Code-credentials-new -w' - ]); - }); - it.each(['linux', 'win32'] as const)('uses the credentials file on %s', (platform) => { vi.spyOn(process, 'platform', 'get').mockReturnValue(platform); mockCredentialsFile(makeTokenPayload('file-token')); diff --git a/src/utils/usage-fetch.ts b/src/utils/usage-fetch.ts index f917bf417..ef26b6f04 100644 --- a/src/utils/usage-fetch.ts +++ b/src/utils/usage-fetch.ts @@ -50,7 +50,6 @@ const DEFAULT_RATE_LIMIT_BACKOFF = 300; // seconds // stuck on [Timeout] and no code path able to recover. const MAX_LOCK_HORIZON = 24 * 60 * 60; // seconds const MACOS_USAGE_CREDENTIALS_SERVICE = 'Claude Code-credentials'; -const MACOS_SECURITY_DUMP_MAX_BUFFER = 8 * 1024 * 1024; // Keychain reads normally take milliseconds. A `security` call blocked on an // unlock prompt must not hold the status line until someone answers it. const MACOS_SECURITY_TIMEOUT_MS = 5000; @@ -385,11 +384,6 @@ export function isStaleUsageFallback(data: UsageData): boolean { type UsageLockError = z.infer; type UsageApiFetchResult = { kind: 'success'; body: string } | { kind: 'rate-limited'; retryAfterSeconds: number } | { kind: 'error' }; -interface MacKeychainCredentialCandidate { - modifiedAt: string | null; - order: number; - service: string; -} type MacKeychainSecretResult = { kind: 'found'; secret: string } | { kind: 'miss' } @@ -482,95 +476,6 @@ function getStaleUsageOrError( return setCachedUsageError(error, now, errorCacheMaxAge); } -function normalizeSecurityTimedateValue(rawValue: string): string | null { - const cleaned = rawValue.replace(/\\000/g, '').replace(/\0/g, '').trim(); - return /^\d{14}Z$/.test(cleaned) ? cleaned : null; -} - -function decodeHexAscii(rawHex: string): string | null { - if (rawHex.length === 0 || rawHex.length % 2 !== 0) { - return null; - } - - let decoded = ''; - - for (let i = 0; i < rawHex.length; i += 2) { - const byte = Number.parseInt(rawHex.slice(i, i + 2), 16); - if (Number.isNaN(byte)) { - return null; - } - - decoded += String.fromCharCode(byte); - } - - return decoded; -} - -function parseModifiedTimeFromKeychainBlock(block: string): string | null { - const quotedMatch = /"mdat"=(?:0x[0-9A-Fa-f]+\s+)?"([^"]+)"/.exec(block); - if (quotedMatch?.[1]) { - const parsed = normalizeSecurityTimedateValue(quotedMatch[1]); - if (parsed !== null) { - return parsed; - } - } - - const hexMatch = /"mdat"=0x([0-9A-Fa-f]+)/.exec(block); - if (!hexMatch?.[1]) { - return null; - } - - const decoded = decodeHexAscii(hexMatch[1]); - return decoded ? normalizeSecurityTimedateValue(decoded) : null; -} - -function sortMacKeychainCredentialCandidates(a: MacKeychainCredentialCandidate, b: MacKeychainCredentialCandidate): number { - if (a.modifiedAt !== null && b.modifiedAt !== null && a.modifiedAt !== b.modifiedAt) { - return b.modifiedAt.localeCompare(a.modifiedAt); - } - - if (a.modifiedAt !== null && b.modifiedAt === null) { - return -1; - } - - if (a.modifiedAt === null && b.modifiedAt !== null) { - return 1; - } - - return a.order - b.order; -} - -export function parseMacKeychainCredentialCandidates(rawDump: string, servicePrefix = MACOS_USAGE_CREDENTIALS_SERVICE): string[] { - const blocks = rawDump.split(/(?=^keychain:\s)/m).filter(block => block.trim().length > 0); - const dedupedCandidates = new Map(); - let order = 0; - - for (const block of blocks) { - const serviceMatch = /"svce"="([^"]+)"/.exec(block); - const service = serviceMatch?.[1]; - - if (!service || !service.startsWith(servicePrefix) || service === MACOS_USAGE_CREDENTIALS_SERVICE) { - continue; - } - - const candidate: MacKeychainCredentialCandidate = { - modifiedAt: parseModifiedTimeFromKeychainBlock(block), - order, - service - }; - order += 1; - - const existing = dedupedCandidates.get(service); - if (!existing || sortMacKeychainCredentialCandidates(candidate, existing) < 0) { - dedupedCandidates.set(service, candidate); - } - } - - return [...dedupedCandidates.values()] - .sort(sortMacKeychainCredentialCandidates) - .map(candidate => candidate.service); -} - function isExecFileTimeoutError(error: unknown): boolean { return typeof error === 'object' && error !== null @@ -621,42 +526,6 @@ function readUsageCredentialsFromMacKeychainUserAccount(service: string): MacKey return osUsername ? readUsageCredentialsFromMacKeychainService(service, osUsername) : { kind: 'miss' }; } -function listMacKeychainCredentialCandidates(): string[] | { kind: 'miss' | 'timeout' } { - try { - const rawDump = execFileSync( - 'security', - ['dump-keychain'], - { - encoding: 'utf8', - maxBuffer: MACOS_SECURITY_DUMP_MAX_BUFFER, - stdio: ['pipe', 'pipe', 'ignore'], - timeout: MACOS_SECURITY_TIMEOUT_MS, - windowsHide: true - } - ); - - return parseMacKeychainCredentialCandidates(rawDump); - } catch (error) { - return { kind: isExecFileTimeoutError(error) ? 'timeout' : 'miss' }; - } -} - -function readUsageCredentialsFromMacKeychainCandidates(): MacKeychainCredentialResult { - const candidates = listMacKeychainCredentialCandidates(); - if (!Array.isArray(candidates)) { - return candidates; - } - - for (const service of candidates) { - const result = readUsageCredentialsFromMacKeychainService(service); - if (result.kind !== 'miss') { - return result; - } - } - - return { kind: 'miss' }; -} - function readUsageCredentialsFromCredentialsFile(): UsageCredentials | null { try { const credFile = path.join(getClaudeConfigDir(), '.credentials.json'); @@ -690,39 +559,28 @@ export function getUsageCredentials(): UsageCredentials | null { return readUsageCredentialsFromCredentialsFile(); } + // Every profile, the default one included, owns exactly one keychain + // service name, the only one Claude Code reads for it. On a miss, the + // remaining "Claude Code-credentials" items belong to other profiles (or + // hold only MCP tokens), so fall through only to the profile's own + // .credentials.json, Claude Code's fallback store, rather than surface + // another account's usage. const configDirService = getMacKeychainConfigDirService(); - if (configDirService !== null) { - // A non-default profile owns exactly one keychain service name. On a - // miss, the plain service and the other suffixed items all belong to - // other profiles (or MCP servers), so fall through only to the - // profile's own .credentials.json rather than surface another - // account's usage. - const result = readUsageCredentialsFromMacKeychainService(configDirService); - return result.kind === 'found' ? result.credentials : readUsageCredentialsFromCredentialsFile(); - } - - const defaultResult = readUsageCredentialsFromMacKeychainService(MACOS_USAGE_CREDENTIALS_SERVICE); - if (defaultResult.kind === 'found') { - return defaultResult.credentials; - } - - if (defaultResult.kind === 'timeout') { - return readUsageCredentialsFromCredentialsFile(); + const result = readUsageCredentialsFromMacKeychainService(configDirService ?? MACOS_USAGE_CREDENTIALS_SERVICE); + if (result.kind === 'found') { + return result.credentials; } - const accountResult = readUsageCredentialsFromMacKeychainUserAccount(MACOS_USAGE_CREDENTIALS_SERVICE); - if (accountResult.kind === 'found') { - return accountResult.credentials; - } - - if (accountResult.kind === 'timeout') { - return readUsageCredentialsFromCredentialsFile(); + // The default service can hold several items that differ only by account, + // and Claude Code's own is under the OS username. A timeout skips the retry. + if (configDirService === null && result.kind === 'miss') { + const accountResult = readUsageCredentialsFromMacKeychainUserAccount(MACOS_USAGE_CREDENTIALS_SERVICE); + if (accountResult.kind === 'found') { + return accountResult.credentials; + } } - const candidateResult = readUsageCredentialsFromMacKeychainCandidates(); - return candidateResult.kind === 'found' - ? candidateResult.credentials - : readUsageCredentialsFromCredentialsFile(); + return readUsageCredentialsFromCredentialsFile(); } export function getUsageToken(): string | null { @@ -731,9 +589,9 @@ export function getUsageToken(): string | null { // A lookup that finds no OAuth login (an API-key user, a logged-out profile) // stands for LOCK_MAX_AGE across renders, as it already does within one -// process: on macOS the default profile's lookup can run `security` multiple -// times, including a full keychain dump. The record names the credential stores it -// covers, so one profile's miss never suppresses another profile's lookup. +// process: on macOS every lookup spawns `security`, the default profile's up +// to twice. The record names the credential stores it covers, so one +// profile's miss never suppresses another profile's lookup. const NoCredentialsLockSchema = z.object({ blockedUntil: z.number(), source: z.string()