From 461872429a8d0c072a5096a3b871baaf8fb67fbd Mon Sep 17 00:00:00 2001 From: Artem Efimov <41889057+efim0v@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:50:40 +0500 Subject: [PATCH 1/2] fix(account-email): show the account the live credentials belong to The Claude Account Email widget read oauthAccount.emailAddress from .claude.json. Claude Code writes that record at login and does not rewrite it when the credentials change underneath, so after an account switch the widget could keep naming the previous account, next to usage widgets that read the live credentials and report on the new one. The email now comes from GET /api/oauth/profile, requested with the usage credentials and the usage request's headers, proxy rules and deadline. Answers are cached in ~/.cache/ccstatusline/account-email.json (owner-only) under the usage cache's login fingerprint, so an access-token refresh reuses them and only a login change triggers another request. Up to ten logins are kept, so profiles used side by side do not evict each other. A failed lookup backs off for that login only: 30 seconds, or after a 429 the server's Retry-After. Without an OAuth login, or until a lookup succeeds, the widget falls back to .claude.json as before. Fixes #538 --- docs/DEVELOPMENT.md | 4 +- docs/USAGE.md | 6 +- src/ccstatusline.ts | 8 +- src/types/RenderContext.ts | 1 + src/utils/__tests__/usage-fetch.test.ts | 317 +++++++++++++++++- src/utils/usage-fetch.ts | 110 +++++- src/utils/usage.ts | 5 +- src/widgets/ClaudeAccountEmail.ts | 30 +- .../__tests__/ClaudeAccountEmail.test.ts | 40 ++- 9 files changed, 494 insertions(+), 27 deletions(-) diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5579cf476..3f29c4814 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -57,6 +57,7 @@ bun run docs - `~/.cache/ccstatusline/terminal-width.json` - per-session no-width probe results; detected numeric widths are not persisted by the renderer - `~/.cache/ccstatusline/usage.json` and `~/.cache/ccstatusline/usage.lock` - usage API data cache and fetch backoff lock - `~/.cache/ccstatusline/usage-credentials.lock` - 30-second backoff after a usage credential lookup finds no OAuth login, tagged with the profile it applies to +- `~/.cache/ccstatusline/account-email.json` and `~/.cache/ccstatusline/account-email.lock` - Claude Account Email lookups keyed by login fingerprint (owner-only), and the backoff after a failed lookup, tagged with the login it applies to - `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock - `~/.cache/ccstatusline/skills/skills-.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_` @@ -90,13 +91,14 @@ After a complete successful usage fetch, the process clears the lock only if its - **JJ widgets** invoke `runJjArgs()` with a five-second timeout and use their normal missing-data behavior when the command fails or times out. - **Git PR and Git CI Status** render from the versioned disk cache under `~/.cache/ccstatusline/git-review`. Missing or stale entries are refreshed in a detached helper so network-bound `gh` or `glab` calls do not block rendering. Git CI Status adds GitHub's `statusCheckRollup`; if the authenticated `gh` token cannot read checks, the refresh retries with PR metadata only so Git PR still works. - **Usage widgets** merge Claude Code's stdin `rate_limits` with `/api/oauth/usage` only for fields required by the active widgets. Session and aggregate weekly fields prefer the flat API buckets and fall back to `limits[]`; per-model weekly fields prefer `weekly_scoped` entries. A model-scoped entry reporting 0% without `resets_at` is valid zero usage, while unscoped empty placeholders remain filtered out. `WEEKLY_MODEL_USAGE_BUCKETS` in `src/utils/usage-types.ts` is the shared registry for Sonnet, Opus, and Fable widget wiring, field requirements, reset fields, and scoped-limit matching. Session and weekly percentage widgets delegate rendering and editor behavior to `src/widgets/shared/usage-percent-widget.ts`; the Fable label is `Weekly Fable:`. Spend Limit Usage and Spend Limit Amount read `rate_limits.spend_limit` from stdin only (no `USAGE_WIDGET_REQUIREMENTS` entry, so they never trigger an API fetch); the percentage widget goes through the same shared renderer with `ignoreApiError` set and no time cursor. +- **Claude Account Email** asks `/api/oauth/profile` which account the usage credentials belong to. Answers are cached under the usage cache's login fingerprint, so an access-token refresh reuses them and only a login change triggers another request. A failed lookup backs off for that login only: 30 seconds, or after a 429 the server's `Retry-After` (five minutes without one). Without an OAuth login, or until a lookup for the current one succeeds, the widget falls back to `oauthAccount.emailAddress` in `.claude.json`, which Claude Code writes at login and does not update when the credentials change. - **Custom Command** delegates to `src/utils/custom-command.ts`. `customCommandCacheTtlSeconds` defaults to `0` (disabled), with a maximum of 60 seconds. Both successes and failures are cached, with TTL measured from command completion; without a session ID, entries stay in process memory. Other stdin fields are deliberately excluded from the key. A helper in the current runtime captures stdout in memory, limits it to 1 MiB, and retains at most 16,384 characters; it enforces command deadlines and closes inherited pipes, terminating the process group on POSIX or the shell on Windows when a command times out. Cached raw output is formatted separately by each widget, and previews never execute commands. - **Terminal width** is memoized once per render, including a `null` probe result. Linux first probes ancestor terminal devices through `/proc` and `tty.WriteStream`; portable fallbacks use `execFileSync` for `ps` and `stty`. `CCSTATUSLINE_WIDTH` takes precedence, including on Windows where probing is disabled. Only no-width results are persisted per session, for `terminalWidthCacheTtlSeconds` (default 5, range 0–300); `0` disables cross-process reuse. Numeric widths are re-probed on the next render. - **Context length transcript fallback** treats the latest `compact_boundary` as the start of the current context. It uses the first main-chain usage entry after that boundary, then `compactMetadata.postTokens`, then zero, while session token totals remain cumulative. - **Sandbox Status** reads `sandbox.enabled` from Claude Code's layered project-local, project, user-local, and user settings on every refresh. This reflects `/sandbox` file updates but remains a best-effort indicator when managed or CLI settings take precedence. - **Skills** reads only logs for session IDs accepted by `getSkillsFilePath()`. Rejected IDs return no metrics, and the hook handler exits before creating directories or writing a log. -Both usage and service-status requests honor uppercase `HTTPS_PROXY` and share `isExcludedFromProxy()` for the `NO_PROXY`/`no_proxy` rules described in [Usage](USAGE.md#proxy-settings). Each request has a total five-second deadline in addition to its socket timeout. On expiry, `createProxyAgent().close()` aborts the pending proxy connection when `AbortController` is available; on older runtimes without it, that connection can remain open. The proxy integration tests require permission to listen on a local socket. +Usage, account profile, and service-status requests honor uppercase `HTTPS_PROXY` and share `isExcludedFromProxy()` for the `NO_PROXY`/`no_proxy` rules described in [Usage](USAGE.md#proxy-settings). Each request has a total five-second deadline in addition to its socket timeout. On expiry, `createProxyAgent().close()` aborts the pending proxy connection when `AbortController` is available; on older runtimes without it, that connection can remain open. The proxy integration tests require permission to listen on a local socket. ## Widget Implementation diff --git a/docs/USAGE.md b/docs/USAGE.md index a60352bee..6fcea33b6 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -28,7 +28,7 @@ ccstatusline --version ### Claude & Session - **Model** / **Output Style** / **Version** - Show the active Claude model, output style, and Claude Code CLI version. Model names omit trailing context suffixes like `(1M context)`; use **Context Window** when you want the total window size shown. -- **Claude Session ID** / **Session Name** / **Claude Account Email** - Show session identifiers plus the currently signed-in Claude account email. +- **Claude Session ID** / **Session Name** / **Claude Account Email** - Show session identifiers plus the currently signed-in Claude account email. Claude Account Email names the account the usage credentials belong to, looked up from `api.anthropic.com` once per login; see [Usage Credentials and Cache](#usage-credentials-and-cache). - **Claude Status** - Show the current Claude/Anthropic service status from `status.claude.com` (`ok` when the indicator is `none`, otherwise the indicator word such as `minor`, `major`, `critical`, or `maintenance`). Press `h` in the editor to add a 48-hour incident-history strip of eight six-hour blocks (oldest to newest), each colored by the worst incident overlapping that block: green (none), yellow (minor), orange (major), red (critical). Responses are cached for about five minutes; on network failure the widget shows stale data when available or degrades to `?`. With the history strip enabled the widget colors itself by severity, so per-widget foreground colors and theme foregrounds are skipped, like Custom Command's preserve-colors mode. Press `l` to make the widget a link to the status page (`https://status.claude.com`), in terminals that support OSC 8 hyperlinks. - **Voice Status** - Show whether Claude Code voice input is enabled. It can render as an icon, icon plus text, plain text, or `voice on/off`, with optional Nerd Font microphone icons. - **Sandbox Status** - Show the effective `sandbox.enabled` value from Claude Code's layered project and user settings. It can render as a glyph, `SB: ON/OFF`, or `Sandbox: ON/OFF`, with optional Nerd Font lock icons. The value is refreshed after `/sandbox` changes, but is best effort when managed or CLI settings override files or sandbox initialization fails. @@ -191,9 +191,11 @@ The usage cache uses a fingerprint of the refresh token when available, falling Each macOS Keychain command has a five-second timeout. When no OAuth credentials are found, the lookup backs off for 30 seconds for that profile, so a newly signed-in account may take up to 30 seconds to appear. Usage cache files dated more than 180 seconds into the future are treated as stale. +Claude Account Email uses the same credentials to look up the account's email from `/api/oauth/profile`. The answer is cached per login fingerprint, so an access-token refresh does not repeat the request. A failed lookup is retried after 30 seconds, or after the `Retry-After` of a 429 response (five minutes without one). Until a lookup succeeds, or without an OAuth login, the widget shows `oauthAccount.emailAddress` from `.claude.json`, which Claude Code writes at login and does not update when the credentials change. + ### Proxy Settings -Usage requests to `api.anthropic.com` and Claude Status requests to `status.claude.com` honor uppercase `HTTPS_PROXY`. Both `NO_PROXY` and `no_proxy` supply exclusions; matching either variable sends the request directly. +Usage and Claude Account Email requests to `api.anthropic.com` and Claude Status requests to `status.claude.com` honor uppercase `HTTPS_PROXY`. Both `NO_PROXY` and `no_proxy` supply exclusions; matching either variable sends the request directly. Exclusions are separated by commas or whitespace and matched without regard to case. Use `*` for all hosts, a hostname such as `api.anthropic.com`, or a domain such as `anthropic.com`, `.anthropic.com`, or `*.anthropic.com` to match that domain and its subdomains. An optional `:443` suffix is supported; entries for other ports do not match these HTTPS requests. diff --git a/src/ccstatusline.ts b/src/ccstatusline.ts index d16d0bb58..692ff9cc9 100644 --- a/src/ccstatusline.ts +++ b/src/ccstatusline.ts @@ -40,6 +40,7 @@ import { getTerminalWidth } from './utils/terminal'; import { sanitizeTerminalText } from './utils/terminal-sanitize'; +import { fetchAccountEmail } from './utils/usage'; import { prefetchUsageDataIfNeeded } from './utils/usage-prefetch'; import { ensureWindowsUtf8CodePage } from './utils/windows-code-page'; @@ -98,6 +99,7 @@ async function renderMultipleLines(data: StatusJSON) { const hasCompactionWidget = lines.some(line => line.some(item => item.type === 'compaction-counter')); const hasThinkingEffortWidget = lines.some(line => line.some(item => item.type === 'thinking-effort')); const hasSessionNameWidget = lines.some(line => line.some(item => item.type === 'session-name')); + const hasAccountEmailWidget = lines.some(line => line.some(item => item.type === 'claude-account-email')); const needsTranscriptThinkingEffort = hasThinkingEffortWidget && (!data.effort || !('level' in data.effort)); const requestedSpeedWindows = new Set(); @@ -120,10 +122,11 @@ async function renderMultipleLines(data: StatusJSON) { includeSessionName: hasSessionNameWidget }) : Promise.resolve(null); - const [transcriptAnalysis, usageData, claudeStatusData] = await Promise.all([ + const [transcriptAnalysis, usageData, claudeStatusData, accountEmail] = await Promise.all([ transcriptAnalysisPromise, prefetchUsageDataIfNeeded(lines, data), - prefetchClaudeStatusIfNeeded(lines) + prefetchClaudeStatusIfNeeded(lines), + hasAccountEmailWidget ? fetchAccountEmail() : Promise.resolve(null) ]); const tokenMetrics = transcriptAnalysis?.tokenMetrics ?? null; @@ -148,6 +151,7 @@ async function renderMultipleLines(data: StatusJSON) { windowedSpeedMetrics, usageData, claudeStatusData, + accountEmail, sessionDuration, transcriptSessionName: hasSessionNameWidget ? (transcriptAnalysis?.sessionName ?? null) diff --git a/src/types/RenderContext.ts b/src/types/RenderContext.ts index 77a10392b..eb200a7e9 100644 --- a/src/types/RenderContext.ts +++ b/src/types/RenderContext.ts @@ -52,6 +52,7 @@ export interface RenderContext { windowedSpeedMetrics?: Record | null; usageData?: RenderUsageData | null; claudeStatusData?: ClaudeStatusRenderData | null; + accountEmail?: string | null; // Email of the account the live OAuth credentials belong to sessionDuration?: string | null; transcriptSessionName?: string | null; transcriptThinkingEffort?: { value: string; known: boolean } | null; diff --git a/src/utils/__tests__/usage-fetch.test.ts b/src/utils/__tests__/usage-fetch.test.ts index 5cb7b3cea..36f2b5cba 100644 --- a/src/utils/__tests__/usage-fetch.test.ts +++ b/src/utils/__tests__/usage-fetch.test.ts @@ -35,6 +35,8 @@ interface UsageProbeResult { requestCount: number; proxyAgentConfigured: boolean; requestHost: string | null; + requestPath: string | null; + requestAuthorization: string | null; homedir: string; lockContents: string | null; } @@ -59,6 +61,9 @@ interface ProbeOptions { responseBody?: string; responseHeaders?: Record; statusCode?: number; + // What each of the probe's two calls runs: fetchUsageData (the default) + // or fetchAccountEmail, whose result is reported as { email }. + target?: 'account-email' | 'usage'; } function createProbeHarness() { @@ -81,6 +86,8 @@ const statusCode = Number(process.env.TEST_STATUS_CODE || (mode === 'success' ? let requestCount = 0; let proxyAgentConfigured = false; let requestHost = null; +let requestPath = null; +let requestAuthorization = null; https.request = (...args) => { requestCount += 1; @@ -88,6 +95,8 @@ https.request = (...args) => { const options = args.find(value => value && typeof value === 'object' && !Buffer.isBuffer(value)); proxyAgentConfigured = Boolean(options?.agent); requestHost = options?.hostname ?? null; + requestPath = options?.path ?? null; + requestAuthorization = options?.headers?.Authorization ?? null; const requestHandlers = new Map(); const responseHandlers = new Map(); @@ -155,7 +164,7 @@ https.request = (...args) => { return request; }; -const { fetchUsageData } = await import(${JSON.stringify(usageModulePath)}); +const { fetchAccountEmail, fetchUsageData } = await import(${JSON.stringify(usageModulePath)}); const lockFile = path.join(os.homedir(), '.cache', 'ccstatusline', 'usage.lock'); const cacheFile = path.join(os.homedir(), '.cache', 'ccstatusline', 'usage.json'); @@ -163,8 +172,11 @@ const nowMs = Number(process.env.TEST_NOW_MS || Date.now()); const requiredFields = JSON.parse(process.env.TEST_REQUIRED_FIELDS_JSON || '[]'); Date.now = () => nowMs; -const first = await fetchUsageData({ requiredFields }); -const second = await fetchUsageData({ requiredFields }); +const fetchOnce = process.env.TEST_PROBE_TARGET === 'account-email' + ? async () => ({ email: await fetchAccountEmail() }) + : () => fetchUsageData({ requiredFields }); +const first = await fetchOnce(); +const second = await fetchOnce(); process.stdout.write(JSON.stringify({ first, second, @@ -173,6 +185,8 @@ process.stdout.write(JSON.stringify({ requestCount, proxyAgentConfigured, requestHost, + requestPath, + requestAuthorization, homedir: os.homedir(), lockContents: fs.existsSync(lockFile) ? fs.readFileSync(lockFile, 'utf8') : null })); @@ -231,7 +245,8 @@ process.stdout.write(JSON.stringify({ TEST_REQUEST_MODE: options.mode ?? 'success', TEST_RESPONSE_BODY: options.responseBody ?? '', TEST_RESPONSE_HEADERS_JSON: JSON.stringify(options.responseHeaders ?? {}), - TEST_STATUS_CODE: String(options.statusCode ?? (options.mode === 'success' ? 200 : 500)) + TEST_STATUS_CODE: String(options.statusCode ?? (options.mode === 'success' ? 200 : 500)), + TEST_PROBE_TARGET: options.target ?? 'usage' }); if (options.claudeConfigDir !== undefined) { @@ -466,6 +481,7 @@ describe('fetchUsageData error handling', () => { expect(result.requestCount).toBe(1); expect(result.proxyAgentConfigured).toBe(false); expect(result.requestHost).toBe('api.anthropic.com'); + expect(result.requestPath).toBe('/api/oauth/usage'); } finally { harness.cleanup(); } @@ -1888,6 +1904,299 @@ describe('fetchUsageData error handling', () => { }); }); +describe('fetchAccountEmail', () => { + const nowMs = 2200000000000; + const nowSeconds = Math.floor(nowMs / 1000); + + function profileResponseBody(email: string): string { + return JSON.stringify({ + account: { uuid: 'account-uuid', email, full_name: 'Example User' }, + organization: { name: 'Example Org', organization_type: 'claude_max' } + }); + } + + function fingerprint(token: string): string { + return createHash('sha256').update(token).digest('hex').slice(0, 16); + } + + function readCacheFile(home: string, fileName: 'account-email.json' | 'account-email.lock'): unknown { + const filePath = path.join(home, '.cache', 'ccstatusline', fileName); + return fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown : null; + } + + function writeCacheFile(home: string, fileName: 'account-email.json' | 'account-email.lock', contents: unknown): void { + const cacheDir = path.join(home, '.cache', 'ccstatusline'); + fs.mkdirSync(cacheDir, { recursive: true }); + fs.writeFileSync(path.join(cacheDir, fileName), JSON.stringify(contents)); + } + + it('looks up the email of the account the live credentials belong to', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email'); + writeUsageCredentials(home.claudeConfig, { + accessToken: 'current-access-token', + refreshToken: 'current-refresh-token' + }); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + responseBody: profileResponseBody('current@example.com'), + target: 'account-email' + }); + + expect(result.first).toEqual({ email: 'current@example.com' }); + expect(result.second).toEqual({ email: 'current@example.com' }); + // The second call is answered from the cache + expect(result.requestCount).toBe(1); + expect(result.requestHost).toBe('api.anthropic.com'); + expect(result.requestPath).toBe('/api/oauth/profile'); + expect(result.requestAuthorization).toBe('Bearer current-access-token'); + expect(readCacheFile(home.home, 'account-email.json')).toEqual([ + { tokenHash: fingerprint('current-refresh-token'), email: 'current@example.com' } + ]); + } finally { + harness.cleanup(); + } + }); + + it.skipIf(process.platform === 'win32')('writes the email cache owner-only', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-private'); + + harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + responseBody: profileResponseBody('current@example.com'), + target: 'account-email' + }); + + const cacheFile = path.join(home.home, '.cache', 'ccstatusline', 'account-email.json'); + expect(fs.statSync(cacheFile).mode & 0o777).toBe(0o600); + } finally { + harness.cleanup(); + } + }); + + it('keeps the cached email when the access token is refreshed for the same login', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-refreshed'); + writeUsageCredentials(home.claudeConfig, { + accessToken: 'reissued-access-token', + refreshToken: 'stable-refresh-token' + }); + writeCacheFile(home.home, 'account-email.json', [ + { tokenHash: fingerprint('stable-refresh-token'), email: 'current@example.com' } + ]); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'unexpected', + nowMs, + pathDir: home.bin, + target: 'account-email' + }); + + expect(result.first).toEqual({ email: 'current@example.com' }); + expect(result.requestCount).toBe(0); + } finally { + harness.cleanup(); + } + }); + + it('looks the email up again after a login change and keeps the other login cached', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-switched'); + writeUsageCredentials(home.claudeConfig, { + accessToken: 'current-access-token', + refreshToken: 'current-refresh-token' + }); + writeCacheFile(home.home, 'account-email.json', [ + { tokenHash: fingerprint('previous-refresh-token'), email: 'previous@example.com' } + ]); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + responseBody: profileResponseBody('current@example.com'), + target: 'account-email' + }); + + expect(result.first).toEqual({ email: 'current@example.com' }); + expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, 'account-email.json')).toEqual([ + { tokenHash: fingerprint('current-refresh-token'), email: 'current@example.com' }, + { tokenHash: fingerprint('previous-refresh-token'), email: 'previous@example.com' } + ]); + } finally { + harness.cleanup(); + } + }); + + it.each([ + { name: 'the request fails', mode: 'error' as const }, + { name: 'the endpoint rejects the token', mode: 'status' as const, statusCode: 401 }, + { name: 'the response names no email', mode: 'success' as const, responseBody: JSON.stringify({ account: { email: '' } }) } + ])('returns null and holds off for 30 seconds when $name', ({ mode, responseBody, statusCode }) => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-failed'); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode, + nowMs, + pathDir: home.bin, + responseBody, + statusCode, + target: 'account-email' + }); + + expect(result.first).toEqual({ email: null }); + expect(result.second).toEqual({ email: null }); + expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, 'account-email.lock')).toEqual({ + blockedUntil: nowSeconds + 30, + tokenHash: fingerprint('test-token') + }); + expect(readCacheFile(home.home, 'account-email.json')).toBeNull(); + } finally { + harness.cleanup(); + } + }); + + it('holds off only the login whose lookup failed, and retries it after the backoff', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-backoff'); + const otherProfile = harness.createTokenHome('account-email-backoff-other'); + writeUsageCredentials(otherProfile.claudeConfig, { accessToken: 'other-access-token' }); + const lookUpAt = (probeNowMs: number, claudeConfig: string, email: string | null) => harness.runProbe({ + claudeConfigDir: claudeConfig, + home: home.home, + mode: email === null ? 'error' : 'success', + nowMs: probeNowMs, + pathDir: home.bin, + responseBody: email === null ? '' : profileResponseBody(email), + target: 'account-email' + }); + + expect(lookUpAt(nowMs, home.claudeConfig, null).requestCount).toBe(1); + + const heldOff = lookUpAt(nowMs + 10000, home.claudeConfig, 'current@example.com'); + expect(heldOff.first).toEqual({ email: null }); + expect(heldOff.requestCount).toBe(0); + + const otherLogin = lookUpAt(nowMs + 10000, otherProfile.claudeConfig, 'other@example.com'); + expect(otherLogin.first).toEqual({ email: 'other@example.com' }); + expect(otherLogin.requestCount).toBe(1); + + const retried = lookUpAt(nowMs + 31000, home.claudeConfig, 'current@example.com'); + expect(retried.first).toEqual({ email: 'current@example.com' }); + expect(retried.requestCount).toBe(1); + } finally { + harness.cleanup(); + } + }); + + it('holds off for the Retry-After of a rate-limited lookup', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-rate-limited'); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'status', + nowMs, + pathDir: home.bin, + responseHeaders: { 'retry-after': '120' }, + statusCode: 429, + target: 'account-email' + }); + + expect(result.first).toEqual({ email: null }); + expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, 'account-email.lock')).toEqual({ + blockedUntil: nowSeconds + 120, + tokenHash: fingerprint('test-token') + }); + } finally { + harness.cleanup(); + } + }); + + it('ignores a backoff whose deadline is implausibly far in the future', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createTokenHome('account-email-poisoned-lock'); + writeCacheFile(home.home, 'account-email.lock', { + blockedUntil: nowSeconds + 2 * 24 * 60 * 60, + tokenHash: fingerprint('test-token') + }); + + const result = harness.runProbe({ + claudeConfigDir: home.claudeConfig, + home: home.home, + mode: 'success', + nowMs, + pathDir: home.bin, + responseBody: profileResponseBody('current@example.com'), + target: 'account-email' + }); + + expect(result.first).toEqual({ email: 'current@example.com' }); + expect(result.requestCount).toBe(1); + } finally { + harness.cleanup(); + } + }); + + it('does not call the profile endpoint without an OAuth login', () => { + const harness = createProbeHarness(); + + try { + const home = harness.createEmptyHome('account-email-no-login'); + + const result = harness.runProbe({ + home: home.home, + mode: 'unexpected', + nowMs, + target: 'account-email' + }); + + expect(result.first).toEqual({ email: null }); + expect(result.second).toEqual({ email: null }); + expect(result.requestCount).toBe(0); + } finally { + harness.cleanup(); + } + }); +}); + // Guards the exact failure mode described in the code review that motivated // WEEKLY_MODEL_USAGE_BUCKETS (usage-types.ts): CachedUsageDataSchema and // UsageApiResponseSchema are hand-declared (see the comments on them in diff --git a/src/utils/usage-fetch.ts b/src/utils/usage-fetch.ts index 5aae11a0b..5bd340b81 100644 --- a/src/utils/usage-fetch.ts +++ b/src/utils/usage-fetch.ts @@ -766,6 +766,7 @@ function parseRetryAfterSeconds(headerValue: string | string[] | undefined, nowM const USAGE_API_HOST = 'api.anthropic.com'; const USAGE_API_PATH = '/api/oauth/usage'; +const PROFILE_API_PATH = '/api/oauth/profile'; const USAGE_API_TIMEOUT_MS = 5000; function getUsageApiProxyUrl(): string | null { @@ -777,7 +778,7 @@ function getUsageApiProxyUrl(): string | null { return proxyUrl ?? null; } -function getUsageApiRequest(token: string): { options: https.RequestOptions; proxy: ClosableProxyAgent | null } | null { +function getUsageApiRequest(token: string, apiPath: string): { options: https.RequestOptions; proxy: ClosableProxyAgent | null } | null { const proxyUrl = getUsageApiProxyUrl(); try { @@ -785,7 +786,7 @@ function getUsageApiRequest(token: string): { options: https.RequestOptions; pro return { options: { hostname: USAGE_API_HOST, - path: USAGE_API_PATH, + path: apiPath, method: 'GET', headers: { 'Authorization': `Bearer ${token}`, @@ -801,8 +802,8 @@ function getUsageApiRequest(token: string): { options: https.RequestOptions; pro } } -async function fetchFromUsageApi(token: string, deadlineMs = USAGE_API_TIMEOUT_MS): Promise { - const usageRequest = getUsageApiRequest(token); +async function fetchFromUsageApi(token: string, deadlineMs = USAGE_API_TIMEOUT_MS, apiPath = USAGE_API_PATH): Promise { + const usageRequest = getUsageApiRequest(token, apiPath); if (!usageRequest) { return { kind: 'error' }; } @@ -968,3 +969,104 @@ export async function fetchUsageData(options: FetchUsageDataOptions = {}): Promi return getStaleUsageOrError('parse-error', now, cacheIdentity, LOCK_MAX_AGE, requiredFields); } } + +// Claude Code records the signed-in account in .claude.json (oauthAccount) +// at login and does not rewrite it when the credentials change underneath, so +// that record can name a different account than the one the credentials, and +// the usage above, belong to (#538). The profile endpoint answers for the +// credentials themselves. +const ACCOUNT_EMAIL_CACHE_FILE = path.join(CACHE_DIR, 'account-email.json'); +const ACCOUNT_EMAIL_LOCK_FILE = path.join(CACHE_DIR, 'account-email.lock'); +// Logins used side by side (one per CLAUDE_CONFIG_DIR profile) each keep an +// entry instead of evicting each other on every render. +const MAX_CACHED_ACCOUNT_EMAILS = 10; + +const ProfileApiResponseSchema = z.looseObject({ account: z.looseObject({ email: z.string().min(1).nullable().optional() }).nullable().optional() }); +const CachedAccountEmailsSchema = z.array(z.object({ + tokenHash: z.string(), + email: z.string().min(1) +})); +const AccountEmailLockSchema = z.object({ + blockedUntil: z.number(), + tokenHash: z.string() +}); + +type CachedAccountEmails = z.infer; + +function readCachedAccountEmails(): CachedAccountEmails { + try { + return parseJsonWithSchema(fs.readFileSync(ACCOUNT_EMAIL_CACHE_FILE, 'utf8'), CachedAccountEmailsSchema) ?? []; + } catch { + return []; + } +} + +function writeCachedAccountEmails(entries: CachedAccountEmails): void { + try { + ensureCacheDirExists(); + // Email addresses, so readable by this user only + fs.writeFileSync(ACCOUNT_EMAIL_CACHE_FILE, JSON.stringify(entries), { mode: 0o600 }); + } catch { + // Ignore cache write errors + } +} + +// A failed lookup holds off only the login it failed for. The deadline is +// bounded like the usage lock's, so one written under a wrong clock cannot +// stop lookups for good. +function isAccountEmailLookupBlocked(tokenHash: string, now: number): boolean { + try { + const lock = parseJsonWithSchema(fs.readFileSync(ACCOUNT_EMAIL_LOCK_FILE, 'utf8'), AccountEmailLockSchema); + return lock?.tokenHash === tokenHash && lock.blockedUntil > now && lock.blockedUntil <= now + MAX_LOCK_HORIZON; + } catch { + return false; + } +} + +function writeAccountEmailLock(tokenHash: string, blockedUntil: number): void { + try { + ensureCacheDirExists(); + fs.writeFileSync(ACCOUNT_EMAIL_LOCK_FILE, JSON.stringify({ blockedUntil, tokenHash })); + } catch { + // Ignore lock file errors + } +} + +/** + * The email of the account the usage credentials belong to, or null when there + * is no OAuth login or the lookup failed. Cached per login, so the profile + * endpoint is called again only when the login changes. + */ +export async function fetchAccountEmail(): Promise { + const now = Math.floor(Date.now() / 1000); + const credentials = getUsageCredentialsWithBackoff(now); + if (!credentials) { + return null; + } + + // Keyed like the usage cache: a refreshed access token keeps the entry, + // and a different login is looked up again. + const tokenHash = getUsageCacheIdentity(credentials).preferredHash; + const cachedEmails = readCachedAccountEmails(); + const cached = cachedEmails.find(entry => entry.tokenHash === tokenHash); + if (cached) { + return cached.email; + } + + if (isAccountEmailLookupBlocked(tokenHash, now)) { + return null; + } + + const response = await fetchFromUsageApi(credentials.accessToken, USAGE_API_TIMEOUT_MS, PROFILE_API_PATH) + .catch((): UsageApiFetchResult => ({ kind: 'error' })); + const email = response.kind === 'success' + ? parseJsonWithSchema(response.body, ProfileApiResponseSchema)?.account?.email ?? null + : null; + if (email === null) { + writeAccountEmailLock(tokenHash, now + (response.kind === 'rate-limited' ? response.retryAfterSeconds : LOCK_MAX_AGE)); + return null; + } + + writeCachedAccountEmails([{ tokenHash, email }, ...cachedEmails].slice(0, MAX_CACHED_ACCOUNT_EMAILS)); + return email; +} diff --git a/src/utils/usage.ts b/src/utils/usage.ts index 0532b7819..db5ef7cfe 100644 --- a/src/utils/usage.ts +++ b/src/utils/usage.ts @@ -1,4 +1,7 @@ -export { fetchUsageData } from './usage-fetch'; +export { + fetchAccountEmail, + fetchUsageData +} from './usage-fetch'; export { formatUsageDuration, formatUsageResetAt, diff --git a/src/widgets/ClaudeAccountEmail.ts b/src/widgets/ClaudeAccountEmail.ts index 00afad82e..7cccdb601 100644 --- a/src/widgets/ClaudeAccountEmail.ts +++ b/src/widgets/ClaudeAccountEmail.ts @@ -15,6 +15,18 @@ const LABEL = 'Account: '; interface ClaudeJson { oauthAccount?: { emailAddress?: string } } +function readClaudeJsonAccountEmail(): string | null { + try { + const content = fs.readFileSync(getClaudeJsonPath(), 'utf-8'); + const data = JSON.parse(content) as ClaudeJson; + const email = data.oauthAccount?.emailAddress; + + return typeof email === 'string' && email.length > 0 ? email : null; + } catch { + return null; + } +} + export class ClaudeAccountEmailWidget implements Widget { getDefaultColor(): string { return 'blue'; } getDescription(): string { return 'Displays the email of the currently logged-in Claude account'; } @@ -30,19 +42,15 @@ export class ClaudeAccountEmailWidget implements Widget { return formatRawOrLabeledValue(item, this.getLabelPrefix(), 'you@example.com'); } - try { - const content = fs.readFileSync(getClaudeJsonPath(), 'utf-8'); - const data = JSON.parse(content) as ClaudeJson; - const email = data.oauthAccount?.emailAddress; - - if (typeof email !== 'string' || email.length === 0) { - return null; - } - - return formatRawOrLabeledValue(item, this.getLabelPrefix(), email); - } catch { + // .claude.json's oauthAccount is written at login and can still name a + // previous account after the credentials change (#538), so it only + // stands in when the live login's email could not be looked up. + const email = context.accountEmail ?? readClaudeJsonAccountEmail(); + if (email === null) { return null; } + + return formatRawOrLabeledValue(item, this.getLabelPrefix(), email); } supportsRawValue(): boolean { return true; } diff --git a/src/widgets/__tests__/ClaudeAccountEmail.test.ts b/src/widgets/__tests__/ClaudeAccountEmail.test.ts index 7a7439685..a4446abd6 100644 --- a/src/widgets/__tests__/ClaudeAccountEmail.test.ts +++ b/src/widgets/__tests__/ClaudeAccountEmail.test.ts @@ -25,14 +25,16 @@ let tempHomeDir: string; function render(options: { rawValue?: boolean; isPreview?: boolean; + accountEmail?: string | null; } = {}): string | null { const { rawValue = false, - isPreview = false + isPreview = false, + accountEmail } = options; const widget = new ClaudeAccountEmailWidget(); - const context: RenderContext = { isPreview }; + const context: RenderContext = { isPreview, accountEmail }; const item: WidgetItem = { id: 'claude-account-email', type: 'claude-account-email', @@ -137,6 +139,40 @@ describe('ClaudeAccountEmailWidget', () => { expect(render()).toBeNull(); }); + it('prefers the email of the live login over the .claude.json snapshot', () => { + // Claude Code writes oauthAccount at login and does not rewrite it when + // the credentials change, so after an account switch it can still name + // the previous account (#538). + delete process.env.CLAUDE_CONFIG_DIR; + vi.spyOn(os, 'homedir').mockReturnValue(tempHomeDir); + fs.writeFileSync( + path.join(tempHomeDir, '.claude.json'), + JSON.stringify({ oauthAccount: { emailAddress: 'previous@example.com' } }), + 'utf-8' + ); + + expect(render({ accountEmail: 'current@example.com' })).toBe('Account: current@example.com'); + expect(render({ accountEmail: 'current@example.com', rawValue: true })).toBe('current@example.com'); + }); + + it('falls back to .claude.json when the live login has no known email', () => { + delete process.env.CLAUDE_CONFIG_DIR; + vi.spyOn(os, 'homedir').mockReturnValue(tempHomeDir); + fs.writeFileSync( + path.join(tempHomeDir, '.claude.json'), + JSON.stringify({ oauthAccount: { emailAddress: 'user@example.com' } }), + 'utf-8' + ); + + expect(render({ accountEmail: null })).toBe('Account: user@example.com'); + }); + + it('shows the email of the live login when .claude.json has none', () => { + process.env.CLAUDE_CONFIG_DIR = path.join(tempHomeDir, '.claude'); + + expect(render({ accountEmail: 'current@example.com' })).toBe('Account: current@example.com'); + }); + it('returns null when emailAddress is not a string', () => { delete process.env.CLAUDE_CONFIG_DIR; vi.spyOn(os, 'homedir').mockReturnValue(tempHomeDir); From d158f23ae6f2ba561bb1a2f0671123e62b3ef0cc Mon Sep 17 00:00:00 2001 From: Matthew Breedlove Date: Thu, 29 Oct 2026 13:23:06 -0400 Subject: [PATCH 2/2] Fix concurrent account-email lookups and cache updates --- docs/DEVELOPMENT.md | 4 +- docs/USAGE.md | 2 +- .../account-email-concurrency.test.ts | 233 ++++++++++++++++++ src/utils/__tests__/usage-fetch.test.ts | 14 +- src/utils/usage-fetch.ts | 158 +++++++++--- 5 files changed, 366 insertions(+), 45 deletions(-) create mode 100644 src/utils/__tests__/account-email-concurrency.test.ts diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index ab81ae09b..838b9e612 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -63,7 +63,7 @@ bun run docs - `~/.cache/ccstatusline/usage-.json` and `~/.cache/ccstatusline/usage-.lock` - per-profile usage API data cache and fetch backoff lock - `~/.cache/ccstatusline/usage-.credentials.lock` - per-profile 30-second backoff after a usage credential lookup finds no OAuth login, also tagged with its credential source - `~/.cache/ccstatusline/session-usage-history.json` and `~/.cache/ccstatusline/session-usage-history.json.lock` - 5-hour usage readings for Block Forecast and Block Limit Timer, per Claude config directory and login, and the lock a render holds while writing them -- `~/.cache/ccstatusline/account-email.json` and `~/.cache/ccstatusline/account-email-.lock` - Claude Account Email lookups keyed by login fingerprint (owner-only cache), and independent backoff files for failed logins +- `~/.cache/ccstatusline/account-email-.json`, `.lock`, and `.inflight` - owner-only Claude Account Email caches, independent failure backoffs, and exclusive in-flight leases per login - `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock - `~/.cache/ccstatusline/skills/skills-.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_` @@ -101,7 +101,7 @@ After a complete successful usage fetch, the process clears the lock only if its - **JJ widgets** invoke `runJjArgs()` with a five-second timeout and use their normal missing-data behavior when the command fails or times out. - **Git PR and Git CI Status** render from the versioned disk cache under `~/.cache/ccstatusline/git-review`. Missing or stale entries are refreshed in a detached helper so network-bound `gh` or `glab` calls do not block rendering. Git CI Status adds GitHub's `statusCheckRollup`; if the authenticated `gh` token cannot read checks, the refresh retries with PR metadata only so Git PR still works. - **Usage widgets** merge Claude Code's stdin `rate_limits` with `/api/oauth/usage` only for fields required by the active widgets. Session and aggregate weekly fields prefer the flat API buckets and fall back to `limits[]`; per-model weekly fields prefer `weekly_scoped` entries. A model-scoped entry reporting 0% without `resets_at` is valid zero usage, while unscoped empty placeholders remain filtered out. `WEEKLY_MODEL_USAGE_BUCKETS` in `src/utils/usage-types.ts` is the shared registry for Sonnet, Opus, and Fable widget wiring, field requirements, reset fields, and scoped-limit matching. Session and weekly percentage widgets delegate rendering and editor behavior to `src/widgets/shared/usage-percent-widget.ts`; the Fable label is `Weekly Fable:`. Spend Limit Usage and Spend Limit Amount read `rate_limits.spend_limit` from stdin only (no `USAGE_WIDGET_REQUIREMENTS` entry, so they never trigger an API fetch); the percentage widget goes through the same shared renderer with `ignoreApiError` set and no time cursor. -- **Claude Account Email** asks `/api/oauth/profile` which account the usage credentials belong to. Answers are cached under the usage cache's login fingerprint, so an access-token refresh reuses them and only a login change triggers another request. A failed lookup backs off for that login only: 30 seconds, or after a 429 the server's `Retry-After` (five minutes without one). `fetchAccountEmail()` distinguishes an available email, no OAuth credentials, and an unavailable email for an existing login. Only the no-credentials case falls back to `oauthAccount.emailAddress` in `.claude.json`; a failed or backed-off lookup for an existing login hides the widget. Independent lock files retain each login’s deadline across alternating failures and access-token refreshes. +- **Claude Account Email** asks `/api/oauth/profile` which account the usage credentials belong to. Answers are cached under the usage cache's login fingerprint, so an access-token refresh reuses them and only a login change triggers another request. A failed lookup backs off for that login only: 30 seconds, or after a 429 the server's `Retry-After` (five minutes without one). `fetchAccountEmail()` distinguishes an available email, no OAuth credentials, and an unavailable email for an existing login. Only the no-credentials case falls back to `oauthAccount.emailAddress` in `.claude.json`; a failed or backed-off lookup for an existing login hides the widget. Independent lock files retain each login’s deadline across alternating failures and access-token refreshes. An exclusive 30-second lease coordinates requests and writes for each login; the request itself still has a five-second deadline. Expired owners cannot write results, and a failure never shortens an existing valid backoff. Cache entries are written atomically to separate owner-only files, so concurrent logins cannot discard each other’s answers. Matching entries in the old shared `account-email.json` remain readable; the shared file is never rewritten. - **Custom Command** delegates to `src/utils/custom-command.ts`. `customCommandCacheTtlSeconds` defaults to `0` (disabled), with a maximum of 60 seconds. Both successes and failures are cached, with TTL measured from command completion; without a session ID, entries stay in process memory. Other stdin fields are deliberately excluded from the key. A helper in the current runtime captures stdout in memory, limits it to 1 MiB, and retains at most 16,384 characters; it enforces command deadlines and closes inherited pipes, terminating the process group on POSIX or the shell on Windows when a command times out. Cached raw output is formatted separately by each widget, and previews never execute commands. - **Terminal width** is memoized once per render, including a `null` probe result. Linux first probes ancestor terminal devices through `/proc` and `tty.WriteStream`; portable fallbacks use `execFileSync` for `ps` and `stty`. `CCSTATUSLINE_WIDTH` takes precedence, including on Windows where probing is disabled. Only no-width results are persisted per session, for `terminalWidthCacheTtlSeconds` (default 5, range 0–300); `0` disables cross-process reuse. Numeric widths are re-probed on the next render. - **Context length transcript fallback** treats the latest `compact_boundary` as the start of the current context. It uses the first main-chain usage entry after that boundary, then `compactMetadata.postTokens`, then zero, while session token totals remain cumulative. diff --git a/docs/USAGE.md b/docs/USAGE.md index b8c57dcc6..502f5714a 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -199,7 +199,7 @@ The usage cache uses a fingerprint of the refresh token when available, falling Each macOS Keychain command has a five-second timeout. If a command times out, ccstatusline skips all remaining Keychain probes for that lookup and tries the current profile’s credentials file. When no OAuth credentials are found, the lookup backs off for 30 seconds for that profile, so a newly signed-in account may take up to 30 seconds to appear. Usage cache files dated more than 180 seconds into the future are treated as stale. -Claude Account Email uses the same credentials to look up the account's email from `/api/oauth/profile`. The answer is cached per login fingerprint, so an access-token refresh does not repeat the request. A failed lookup is retried after 30 seconds, or after the `Retry-After` of a 429 response (five minutes without one). Each login has its own backoff file, so alternating failures cannot overwrite another login’s deadline. If credentials exist but their email lookup fails or is backed off, the widget is hidden instead of showing an unverified previous account. Without OAuth credentials, it can still show `oauthAccount.emailAddress` from `.claude.json`. Cached email is used only for the current login fingerprint. +Claude Account Email uses the same credentials to look up the account's email from `/api/oauth/profile`. The answer is cached per login fingerprint, so an access-token refresh does not repeat the request. A failed lookup is retried after 30 seconds, or after the `Retry-After` of a 429 response (five minutes without one). Each login has its own cache and backoff files. Concurrent lookups for the same login are coordinated, and a failure does not shorten an existing backoff deadline. Concurrent lookups for different logins retain both cached emails. Existing matching entries in the old shared email cache remain usable. If credentials exist but their email lookup fails or is backed off, the widget is hidden instead of showing an unverified previous account. Without OAuth credentials, it can still show `oauthAccount.emailAddress` from `.claude.json`. Cached email is used only for the current login fingerprint. ### Proxy Settings diff --git a/src/utils/__tests__/account-email-concurrency.test.ts b/src/utils/__tests__/account-email-concurrency.test.ts new file mode 100644 index 000000000..e333a6fb9 --- /dev/null +++ b/src/utils/__tests__/account-email-concurrency.test.ts @@ -0,0 +1,233 @@ +import type * as childProcess from 'node:child_process'; +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; +import { createRequire } from 'node:module'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + afterEach, + beforeEach, + describe, + expect, + it +} from 'vitest'; + +import type { AccountEmailResult } from '../../types/AccountEmail'; + +const require = createRequire(import.meta.url); +const { spawn: realSpawn } = require('node:child_process') as typeof childProcess; +const NOW = 2200000000000; +const modulePath = fileURLToPath(new URL('../usage-fetch.ts', import.meta.url)); + +interface ProbeResult { + result: AccountEmailResult; + requests: number; +} + +interface Probe { + ready: string; + release: () => void; + done: Promise; +} + +let root: string; +let home: string; +let sequence: number; +let children: childProcess.ChildProcess[]; +let completions: Promise[]; + +function accountPath(token: string, extension: string): string { + const hash = createHash('sha256').update(token).digest('hex').slice(0, 16); + return path.join(home, '.cache', 'ccstatusline', `account-email-${hash}.${extension}`); +} + +function startProbe(token: string, outcome: 'success' | 'error' | 'rate-limited', now = NOW): Probe { + const id = String(sequence++); + const configDir = path.join(root, `profile-${token}`); + fs.mkdirSync(configDir, { recursive: true }); + fs.writeFileSync(path.join(configDir, '.credentials.json'), JSON.stringify({ claudeAiOauth: { accessToken: token } })); + const ready = path.join(root, `${id}.ready`); + const gate = path.join(root, `${id}.gate`); + const env = { ...process.env }; + delete env.CLAUDE_SECURESTORAGE_CONFIG_DIR; + delete env.HTTPS_PROXY; + delete env.NO_PROXY; + delete env.no_proxy; + const child = realSpawn(process.execPath, [path.join(root, 'probe.mjs')], { + env: { + ...env, + HOME: home, + USERPROFILE: home, + CLAUDE_CONFIG_DIR: configDir, + PATH: path.join(root, 'bin'), + PROBE_READY: ready, + PROBE_GATE: gate, + PROBE_OUTCOME: outcome, + PROBE_NOW: String(now) + }, + stdio: ['ignore', 'pipe', 'pipe'] + }); + children.push(child); + const done = new Promise((resolve, reject) => { + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (data) => { stdout += String(data); }); + child.stderr.on('data', (data) => { stderr += String(data); }); + child.on('error', reject); + child.on('close', (code) => { + if (code !== 0) { + reject(new Error(`Probe exited ${code}: ${stderr}`)); + return; + } + try { + resolve(JSON.parse(stdout) as ProbeResult); + } catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + } + }); + }); + // Teardown awaits every child, including those interrupted by a failed test. + void done.catch(() => undefined); + completions.push(done); + return { ready, done, release: () => { fs.writeFileSync(gate, ''); } }; +} + +async function waitForRequest(probe: Probe): Promise { + const deadline = Date.now() + 4000; + while (!fs.existsSync(probe.ready)) { + if (Date.now() >= deadline) { + throw new Error('Probe did not start its mocked request'); + } + await new Promise(resolve => setTimeout(resolve, 10)); + } +} + +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'ccstatusline-email-concurrency-')); + home = path.join(root, 'home'); + sequence = 0; + children = []; + completions = []; + fs.mkdirSync(home); + fs.mkdirSync(path.join(root, 'bin')); + // Keep every macOS credential lookup inside the temporary fixture. + fs.writeFileSync(path.join(root, 'bin', 'security'), '#!/bin/sh\n/bin/cat "$CLAUDE_CONFIG_DIR/.credentials.json"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(root, 'probe.mjs'), ` +import * as fs from 'node:fs'; +import { EventEmitter } from 'node:events'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const https = require('node:https'); +Date.now = () => Number(process.env.PROBE_NOW); +let requests = 0; +https.request = (options, callback) => { + requests++; + const request = new EventEmitter(); + let timer; + request.destroy = () => clearInterval(timer); + request.end = () => { + fs.writeFileSync(process.env.PROBE_READY, ''); + timer = setInterval(() => { + if (!fs.existsSync(process.env.PROBE_GATE)) return; + clearInterval(timer); + if (process.env.PROBE_OUTCOME === 'error') { + request.emit('error', new Error('mock request failure')); + return; + } + const response = new EventEmitter(); + response.headers = { 'retry-after': '120' }; + response.statusCode = process.env.PROBE_OUTCOME === 'rate-limited' ? 429 : 200; + response.setEncoding = () => {}; + callback(response); + const token = options.headers.Authorization.slice('Bearer '.length); + response.emit('data', JSON.stringify({ account: { email: token + '@example.com' } })); + response.emit('end'); + }, 10); + }; + return request; +}; +const { fetchAccountEmail } = await import(${JSON.stringify(modulePath)}); +const result = await fetchAccountEmail(); +process.stdout.write(JSON.stringify({ result, requests })); +`); +}); + +afterEach(async () => { + for (const child of children) { + if (child.exitCode === null) { + child.kill(); + } + } + await Promise.allSettled(completions); + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('account-email cross-process coordination', () => { + it('allows only one request for an uncached login and retains its 429 deadline', async () => { + const owner = startProbe('shared', 'rate-limited'); + await waitForRequest(owner); + const competing = startProbe('shared', 'error'); + expect(await competing.done).toEqual({ result: { status: 'unavailable' }, requests: 0 }); + expect(fs.existsSync(competing.ready)).toBe(false); + owner.release(); + expect((await owner.done).requests).toBe(1); + const lock = JSON.parse(fs.readFileSync(accountPath('shared', 'lock'), 'utf8')) as { blockedUntil: number }; + expect(lock.blockedUntil).toBe(NOW / 1000 + 120); + expect(fs.existsSync(accountPath('shared', 'inflight'))).toBe(false); + expect(await startProbe('shared', 'error', NOW + 31000).done).toEqual({ result: { status: 'unavailable' }, requests: 0 }); + }); + + it('does not shorten a longer deadline written while its request was in flight', async () => { + const probe = startProbe('long-backoff', 'error'); + await waitForRequest(probe); + const tokenHash = createHash('sha256').update('long-backoff').digest('hex').slice(0, 16); + fs.writeFileSync(accountPath('long-backoff', 'lock'), JSON.stringify({ tokenHash, blockedUntil: NOW / 1000 + 120 })); + probe.release(); + expect((await probe.done).result).toEqual({ status: 'unavailable' }); + const lock = JSON.parse(fs.readFileSync(accountPath('long-backoff', 'lock'), 'utf8')) as { blockedUntil: number }; + expect(lock.blockedUntil).toBe(NOW / 1000 + 120); + expect((await startProbe('long-backoff', 'error', NOW + 31000).done).requests).toBe(0); + }); + + it.each([false, true])('keeps both concurrent successful logins cached (reverse response order: %s)', async (reverse) => { + const first = startProbe('first', 'success'); + const second = startProbe('second', 'success'); + await Promise.all([waitForRequest(first), waitForRequest(second)]); + for (const probe of reverse ? [second, first] : [first, second]) { + probe.release(); + expect((await probe.done).requests).toBe(1); + } + for (const token of ['first', 'second']) { + expect(await startProbe(token, 'error').done).toEqual({ + result: { status: 'available', email: `${token}@example.com` }, + requests: 0 + }); + } + }); + + it('recovers a stale incomplete lease left by a crashed writer', async () => { + const leasePath = accountPath('incomplete', 'inflight'); + fs.mkdirSync(path.dirname(leasePath), { recursive: true }); + fs.writeFileSync(leasePath, '{'); + fs.utimesSync(leasePath, NOW / 1000 - 60, NOW / 1000 - 60); + const probe = startProbe('incomplete', 'success'); + await waitForRequest(probe); + probe.release(); + expect((await probe.done).result).toEqual({ status: 'available', email: 'incomplete@example.com' }); + expect(fs.existsSync(leasePath)).toBe(false); + }); + + it('recovers an abandoned lease and rejects the expired owner response', async () => { + const abandoned = startProbe('expired', 'error'); + await waitForRequest(abandoned); + const replacement = startProbe('expired', 'rate-limited', NOW + 31000); + await waitForRequest(replacement); + replacement.release(); + await replacement.done; + const lockBefore = fs.readFileSync(accountPath('expired', 'lock'), 'utf8'); + abandoned.release(); + await abandoned.done; + expect(fs.readFileSync(accountPath('expired', 'lock'), 'utf8')).toBe(lockBefore); + }); +}); diff --git a/src/utils/__tests__/usage-fetch.test.ts b/src/utils/__tests__/usage-fetch.test.ts index 488dfca46..0f0e466db 100644 --- a/src/utils/__tests__/usage-fetch.test.ts +++ b/src/utils/__tests__/usage-fetch.test.ts @@ -2377,9 +2377,10 @@ describe('fetchAccountEmail', () => { expect(result.requestHost).toBe('api.anthropic.com'); expect(result.requestPath).toBe('/api/oauth/profile'); expect(result.requestAuthorization).toBe('Bearer current-access-token'); - expect(readCacheFile(home.home, 'account-email.json')).toEqual([ - { tokenHash: fingerprint('current-refresh-token'), email: 'current@example.com' } - ]); + expect(readCacheFile(home.home, `account-email-${fingerprint('current-refresh-token')}.json`)).toEqual({ + tokenHash: fingerprint('current-refresh-token'), + email: 'current@example.com' + }); } finally { harness.cleanup(); } @@ -2401,7 +2402,7 @@ describe('fetchAccountEmail', () => { target: 'account-email' }); - const cacheFile = path.join(home.home, '.cache', 'ccstatusline', 'account-email.json'); + const cacheFile = path.join(home.home, '.cache', 'ccstatusline', `account-email-${fingerprint('test-token')}.json`); expect(fs.statSync(cacheFile).mode & 0o777).toBe(0o600); } finally { harness.cleanup(); @@ -2462,8 +2463,11 @@ describe('fetchAccountEmail', () => { expect(result.first).toEqual({ status: 'available', email: 'current@example.com' }); expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, `account-email-${fingerprint('current-refresh-token')}.json`)).toEqual({ + tokenHash: fingerprint('current-refresh-token'), + email: 'current@example.com' + }); expect(readCacheFile(home.home, 'account-email.json')).toEqual([ - { tokenHash: fingerprint('current-refresh-token'), email: 'current@example.com' }, { tokenHash: fingerprint('previous-refresh-token'), email: 'previous@example.com' } ]); } finally { diff --git a/src/utils/usage-fetch.ts b/src/utils/usage-fetch.ts index e94d7fe15..a4137729b 100644 --- a/src/utils/usage-fetch.ts +++ b/src/utils/usage-fetch.ts @@ -1,5 +1,8 @@ import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; +import { + createHash, + randomBytes +} from 'node:crypto'; import * as fs from 'node:fs'; import * as https from 'node:https'; import * as os from 'node:os'; @@ -1096,60 +1099,122 @@ export async function fetchUsageData(options: FetchUsageDataOptions = {}): Promi // that record can name a different account than the one the credentials, and // the usage above, belong to (#538). The profile endpoint answers for the // credentials themselves. -const ACCOUNT_EMAIL_CACHE_FILE = path.join(CACHE_DIR, 'account-email.json'); -function getAccountEmailLockPath(tokenHash: string): string { - return path.join(CACHE_DIR, `account-email-${tokenHash}.lock`); +// Read the old shared cache for existing entries, but never modify it. +const LEGACY_ACCOUNT_EMAIL_CACHE_FILE = path.join(CACHE_DIR, 'account-email.json'); +function getAccountEmailPath(tokenHash: string, suffix: 'json' | 'lock' | 'inflight'): string { + return path.join(CACHE_DIR, `account-email-${tokenHash}.${suffix}`); } -// Logins used side by side (one per CLAUDE_CONFIG_DIR profile) each keep an -// entry instead of evicting each other on every render. -const MAX_CACHED_ACCOUNT_EMAILS = 10; const ProfileApiResponseSchema = z.looseObject({ account: z.looseObject({ email: z.string().min(1).nullable().optional() }).nullable().optional() }); -const CachedAccountEmailsSchema = z.array(z.object({ +const CachedAccountEmailSchema = z.object({ tokenHash: z.string(), email: z.string().min(1) -})); +}); const AccountEmailLockSchema = z.object({ blockedUntil: z.number(), tokenHash: z.string() }); -type CachedAccountEmails = z.infer; +function readCachedAccountEmail(tokenHash: string): string | null { + try { + const entry = parseJsonWithSchema(fs.readFileSync(getAccountEmailPath(tokenHash, 'json'), 'utf8'), CachedAccountEmailSchema); + if (entry?.tokenHash === tokenHash) { + return entry.email; + } + } catch { + // Try a matching entry from the previous shared cache. + } + try { + const entries = parseJsonWithSchema(fs.readFileSync(LEGACY_ACCOUNT_EMAIL_CACHE_FILE, 'utf8'), z.array(CachedAccountEmailSchema)); + return entries?.find(entry => entry.tokenHash === tokenHash)?.email ?? null; + } catch { + return null; + } +} -function readCachedAccountEmails(): CachedAccountEmails { +function writeCachedAccountEmail(tokenHash: string, email: string, owner: string): void { + const cachePath = getAccountEmailPath(tokenHash, 'json'); + const tempPath = `${cachePath}.${owner}.tmp`; try { - return parseJsonWithSchema(fs.readFileSync(ACCOUNT_EMAIL_CACHE_FILE, 'utf8'), CachedAccountEmailsSchema) ?? []; + fs.writeFileSync(tempPath, JSON.stringify({ tokenHash, email }), { mode: 0o600, flag: 'wx' }); + fs.renameSync(tempPath, cachePath); } catch { - return []; + // Ignore cache write errors. + } finally { + try { + fs.unlinkSync(tempPath); + } catch { + // Already renamed or never created. + } } } -function writeCachedAccountEmails(entries: CachedAccountEmails): void { +// Hold an exclusive lease across the request and its cache/backoff writes. +// A crashed render cannot block future lookups indefinitely. The lease is +// longer than the five-second request deadline; an expired owner cannot write. +const AccountEmailLeaseSchema = z.object({ owner: z.string(), expiresAt: z.number() }); +function acquireAccountEmailLease(tokenHash: string, now: number): string | null { + const leasePath = getAccountEmailPath(tokenHash, 'inflight'); + const owner = randomBytes(16).toString('hex'); try { ensureCacheDirExists(); - // Email addresses, so readable by this user only - fs.writeFileSync(ACCOUNT_EMAIL_CACHE_FILE, JSON.stringify(entries), { mode: 0o600 }); + try { + const existing = fs.readFileSync(leasePath, 'utf8'); + const lease = parseJsonWithSchema(existing, AccountEmailLeaseSchema); + const stale = lease + ? lease.expiresAt <= now || lease.expiresAt > now + LOCK_MAX_AGE + : Math.abs(now - fs.statSync(leasePath).mtimeMs / 1000) > LOCK_MAX_AGE; + if (stale) { + fs.unlinkSync(leasePath); + } + } catch { + // Missing lease: exclusive creation below arbitrates contenders. + } + fs.writeFileSync(leasePath, JSON.stringify({ owner, expiresAt: now + LOCK_MAX_AGE }), { flag: 'wx', mode: 0o600 }); + return owner; + } catch { + return null; + } +} + +function ownsAccountEmailLease(tokenHash: string, owner: string): boolean { + try { + const lease = parseJsonWithSchema(fs.readFileSync(getAccountEmailPath(tokenHash, 'inflight'), 'utf8'), AccountEmailLeaseSchema); + return lease?.owner === owner && lease.expiresAt > Math.floor(Date.now() / 1000); + } catch { + return false; + } +} + +function releaseAccountEmailLease(tokenHash: string, owner: string): void { + try { + if (ownsAccountEmailLease(tokenHash, owner)) { + fs.unlinkSync(getAccountEmailPath(tokenHash, 'inflight')); + } } catch { - // Ignore cache write errors + // Best-effort cleanup; an abandoned lease expires. } } // A failed lookup holds off only the login it failed for. The deadline is // bounded like the usage lock's, so one written under a wrong clock cannot // stop lookups for good. -function isAccountEmailLookupBlocked(tokenHash: string, now: number): boolean { +function readAccountEmailBackoff(tokenHash: string, now: number): number { try { - const lock = parseJsonWithSchema(fs.readFileSync(getAccountEmailLockPath(tokenHash), 'utf8'), AccountEmailLockSchema); - return lock?.tokenHash === tokenHash && lock.blockedUntil > now && lock.blockedUntil <= now + MAX_LOCK_HORIZON; + const lock = parseJsonWithSchema(fs.readFileSync(getAccountEmailPath(tokenHash, 'lock'), 'utf8'), AccountEmailLockSchema); + return lock?.tokenHash === tokenHash && lock.blockedUntil > now && lock.blockedUntil <= now + MAX_LOCK_HORIZON + ? lock.blockedUntil + : 0; } catch { - return false; + return 0; } } function writeAccountEmailLock(tokenHash: string, blockedUntil: number): void { try { ensureCacheDirExists(); - fs.writeFileSync(getAccountEmailLockPath(tokenHash), JSON.stringify({ blockedUntil, tokenHash })); + const deadline = Math.max(blockedUntil, readAccountEmailBackoff(tokenHash, Math.floor(Date.now() / 1000))); + fs.writeFileSync(getAccountEmailPath(tokenHash, 'lock'), JSON.stringify({ blockedUntil: deadline, tokenHash })); } catch { // Ignore lock file errors } @@ -1170,26 +1235,45 @@ export async function fetchAccountEmail(): Promise { // Keyed like the usage cache: a refreshed access token keeps the entry, // and a different login is looked up again. const tokenHash = getUsageCacheIdentity(credentials).preferredHash; - const cachedEmails = readCachedAccountEmails(); - const cached = cachedEmails.find(entry => entry.tokenHash === tokenHash); - if (cached) { - return { status: 'available', email: cached.email }; + const cached = readCachedAccountEmail(tokenHash); + if (cached !== null) { + return { status: 'available', email: cached }; } - if (isAccountEmailLookupBlocked(tokenHash, now)) { + if (readAccountEmailBackoff(tokenHash, now)) { return { status: 'unavailable' }; } - - const response = await fetchFromUsageApi(credentials.accessToken, USAGE_API_TIMEOUT_MS, PROFILE_API_PATH) - .catch((): UsageApiFetchResult => ({ kind: 'error' })); - const email = response.kind === 'success' - ? parseJsonWithSchema(response.body, ProfileApiResponseSchema)?.account?.email ?? null - : null; - if (email === null) { - writeAccountEmailLock(tokenHash, now + (response.kind === 'rate-limited' ? response.retryAfterSeconds : LOCK_MAX_AGE)); + const owner = acquireAccountEmailLease(tokenHash, now); + if (owner === null) { return { status: 'unavailable' }; } - writeCachedAccountEmails([{ tokenHash, email }, ...cachedEmails].slice(0, MAX_CACHED_ACCOUNT_EMAILS)); - return { status: 'available', email }; + try { + // Another render may have finished between our first read and lease. + const latest = readCachedAccountEmail(tokenHash); + if (latest !== null) { + return { status: 'available', email: latest }; + } + if (readAccountEmailBackoff(tokenHash, Math.floor(Date.now() / 1000))) { + return { status: 'unavailable' }; + } + const response = await fetchFromUsageApi(credentials.accessToken, USAGE_API_TIMEOUT_MS, PROFILE_API_PATH) + .catch((): UsageApiFetchResult => ({ kind: 'error' })); + if (!ownsAccountEmailLease(tokenHash, owner)) { + return { status: 'unavailable' }; + } + const email = response.kind === 'success' + ? parseJsonWithSchema(response.body, ProfileApiResponseSchema)?.account?.email ?? null + : null; + if (email === null) { + const responseTime = Math.floor(Date.now() / 1000); + writeAccountEmailLock(tokenHash, responseTime + (response.kind === 'rate-limited' ? response.retryAfterSeconds : LOCK_MAX_AGE)); + return { status: 'unavailable' }; + } + + writeCachedAccountEmail(tokenHash, email, owner); + return { status: 'available', email }; + } finally { + releaseAccountEmailLease(tokenHash, owner); + } }