Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<sha256(configDir)[:8]>`, 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-<sha256(configDir)[:8]>`, 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.

Expand Down
2 changes: 1 addition & 1 deletion docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
131 changes: 128 additions & 3 deletions src/utils/__tests__/usage-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ interface TokenHome {
home: string;
}

interface DefaultProfileKeychainHome extends TokenHome { readSecurityCalls: () => string[] }

interface ProbeOptions {
claudeConfigDir?: string;
claudeSecureStorageConfigDir?: string;
Expand All @@ -75,6 +77,7 @@ interface ProbeOptions {
mode?: 'error' | 'status' | 'success' | 'unexpected';
nowMs: number;
pathDir?: string;
platform?: NodeJS.Platform;
requiredFields?: string[];
responseBody?: string;
responseHeaders?: Record<string, string>;
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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"<blob>="${otherProfileService}"`,
' "mdat"<timedate>="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');
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -396,6 +462,7 @@ process.stdout.write(JSON.stringify({

return {
cleanup,
createDefaultProfileKeychainHome,
createEmptyHome,
createTimedOutSecurityHome,
createTokenHome,
Expand Down Expand Up @@ -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' });
Expand All @@ -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();

Expand Down
91 changes: 0 additions & 91 deletions src/utils/__tests__/usage-token-buffer.test.ts

This file was deleted.

Loading
Loading