diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index ebc22c099..838b9e612 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -63,6 +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`, `.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 `_` @@ -100,13 +101,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). `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. - **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 8cc4c8c7b..502f5714a 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. - **Fast Mode** - Show whether Claude Code's fast mode is on, from the status line's `fast_mode` field. It can render as icon plus text (`⚡ on` / `⚡ off`, the default), an icon with a state dot, plain text, or `fast on/off`, with optional Nerd Font lightning icons. It can hide while fast mode is off, and shows nothing on Claude Code versions that don't report fast mode. @@ -199,9 +199,11 @@ 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 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 -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 6cf0a6e9f..16194022a 100644 --- a/src/ccstatusline.ts +++ b/src/ccstatusline.ts @@ -42,6 +42,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'; @@ -104,6 +105,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(); @@ -126,10 +128,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(undefined) ]); const sessionForecast = computeSessionForecastIfNeeded(lines, usageData, getDefaultSessionUsageHistoryDeps(data)); @@ -156,6 +159,7 @@ async function renderMultipleLines(data: StatusJSON) { usageData, sessionForecast, claudeStatusData, + accountEmail, sessionDuration, transcriptSessionName: hasSessionNameWidget ? (transcriptAnalysis?.sessionName ?? null) diff --git a/src/types/AccountEmail.ts b/src/types/AccountEmail.ts new file mode 100644 index 000000000..44f097ccd --- /dev/null +++ b/src/types/AccountEmail.ts @@ -0,0 +1,3 @@ +export type AccountEmailResult = { status: 'available'; email: string } + | { status: 'no-credentials' } + | { status: 'unavailable' }; diff --git a/src/types/RenderContext.ts b/src/types/RenderContext.ts index bf58df0fe..de0e6c987 100644 --- a/src/types/RenderContext.ts +++ b/src/types/RenderContext.ts @@ -3,6 +3,7 @@ import type { SkillsMetrics } from '../types'; +import type { AccountEmailResult } from './AccountEmail'; import type { SessionForecast } from './SessionForecast'; import type { SpeedMetrics } from './SpeedMetrics'; import type { StatusJSON } from './StatusJSON'; @@ -55,6 +56,7 @@ export interface RenderContext { usageData?: RenderUsageData | null; sessionForecast?: SessionForecast | null; claudeStatusData?: ClaudeStatusRenderData | null; + accountEmail?: AccountEmailResult; // 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__/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 33c608e9d..0f0e466db 100644 --- a/src/utils/__tests__/usage-fetch.test.ts +++ b/src/utils/__tests__/usage-fetch.test.ts @@ -28,6 +28,7 @@ const require = createRequire(import.meta.url); const { execFileSync: realExecFileSync } = require('node:child_process') as { execFileSync: typeof childProcess.execFileSync }; interface UsageProbeResult { + renderedEmail: string | null; first: Record; second: Record; staleFallback: [boolean, boolean]; @@ -36,6 +37,8 @@ interface UsageProbeResult { requestCount: number; proxyAgentConfigured: boolean; requestHost: string | null; + requestPath: string | null; + requestAuthorization: string | null; homedir: string; lockContents: string | null; securityCalls: string[]; @@ -63,6 +66,9 @@ interface ProbeOptions { responseBody?: string; responseHeaders?: Record; statusCode?: number; + // What each of the probe's two calls runs: fetchUsageData (the default) + // or fetchAccountEmail, whose status also drives the real email widget. + target?: 'account-email' | 'usage'; } function createProbeHarness() { @@ -86,6 +92,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; @@ -93,6 +101,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(); @@ -160,7 +170,7 @@ https.request = (...args) => { return request; }; -const { fetchUsageData, getUsageFetchedAtMs, isStaleUsageFallback } = await import(${JSON.stringify(usageModulePath)}); +const { fetchAccountEmail, fetchUsageData, getUsageFetchedAtMs, isStaleUsageFallback } = await import(${JSON.stringify(usageModulePath)}); const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'); const configHash = createHash('sha256').update(path.resolve(configDir)).digest('hex').slice(0, 16); @@ -171,9 +181,23 @@ 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' + ? () => fetchAccountEmail() + : () => fetchUsageData({ requiredFields }); +const first = await fetchOnce(); +const second = await fetchOnce(); +let renderedEmail = null; +if (process.env.TEST_PROBE_TARGET === 'account-email') { + const { ClaudeAccountEmailWidget } = await import(${JSON.stringify(fileURLToPath(new URL('../../widgets/ClaudeAccountEmail.ts', import.meta.url)))}); + const { DEFAULT_SETTINGS } = await import(${JSON.stringify(fileURLToPath(new URL('../../types/Settings.ts', import.meta.url)))}); + renderedEmail = new ClaudeAccountEmailWidget().render( + { id: 'email', type: 'claude-account-email' }, + { accountEmail: first }, + DEFAULT_SETTINGS + ); +} process.stdout.write(JSON.stringify({ + renderedEmail, first, second, staleFallback: [isStaleUsageFallback(first), isStaleUsageFallback(second)], @@ -182,6 +206,8 @@ process.stdout.write(JSON.stringify({ requestCount, proxyAgentConfigured, requestHost, + requestPath, + requestAuthorization, homedir: os.homedir(), lockContents: fs.existsSync(lockFile) ? fs.readFileSync(lockFile, 'utf8') : null, securityCalls: fs.existsSync(securityCallsFile) @@ -268,7 +294,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) { @@ -659,6 +686,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(); } @@ -2296,6 +2324,391 @@ 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: string): 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: string, 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({ status: 'available', email: 'current@example.com' }); + expect(result.second).toEqual({ status: 'available', 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-${fingerprint('current-refresh-token')}.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-${fingerprint('test-token')}.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({ status: 'available', 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({ 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('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: { status: 'available', email: '' } }) } + ])('returns unavailable 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({ status: 'unavailable' }); + expect(result.second).toEqual({ status: 'unavailable' }); + expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, `account-email-${fingerprint('test-token')}.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({ status: 'unavailable' }); + expect(heldOff.requestCount).toBe(0); + + const otherLogin = lookUpAt(nowMs + 10000, otherProfile.claudeConfig, 'other@example.com'); + expect(otherLogin.first).toEqual({ status: 'available', email: 'other@example.com' }); + expect(otherLogin.requestCount).toBe(1); + + const retried = lookUpAt(nowMs + 31000, home.claudeConfig, 'current@example.com'); + expect(retried.first).toEqual({ status: 'available', email: 'current@example.com' }); + expect(retried.requestCount).toBe(1); + } finally { + harness.cleanup(); + } + }); + + it.each(['error', 'status'] as const)('hides the previous account after a login switch followed by a lookup %s', (mode) => { + const harness = createProbeHarness(); + try { + const home = harness.createTokenHome('account-switch-failure'); + const render = (requestMode: ProbeOptions['mode'], time = nowMs) => harness.runProbe({ + home: home.home, + claudeConfigDir: home.claudeConfig, + pathDir: home.bin, + mode: requestMode, + nowMs: time, + statusCode: requestMode === 'status' ? 429 : 200, + responseHeaders: { 'retry-after': '120' }, + responseBody: profileResponseBody('previous@example.com'), + target: 'account-email' + }); + writeUsageCredentials(home.claudeConfig, { accessToken: 'previous-access', refreshToken: 'previous-refresh' }); + fs.writeFileSync(path.join(home.claudeConfig, '.claude.json'), JSON.stringify({ oauthAccount: { emailAddress: 'previous@example.com' } })); + expect(render('success').renderedEmail).toBe('Account: previous@example.com'); + + writeUsageCredentials(home.claudeConfig, { accessToken: 'current-access', refreshToken: 'current-refresh' }); + const failed = render(mode); + expect(failed.first).toEqual({ status: 'unavailable' }); + expect(failed.renderedEmail).toBeNull(); + expect(failed.requestCount).toBe(1); + expect(failed.requestAuthorization).toBe('Bearer current-access'); + const blocked = render('unexpected', nowMs + 10000); + expect(blocked.first).toEqual({ status: 'unavailable' }); + expect(blocked.renderedEmail).toBeNull(); + expect(blocked.requestCount).toBe(0); + // The old email may remain cached, but only its own login may use it. + writeUsageCredentials(home.claudeConfig, { accessToken: 'refreshed-previous-access', refreshToken: 'previous-refresh' }); + const previous = render('unexpected'); + expect(previous.renderedEmail).toBe('Account: previous@example.com'); + expect(previous.requestCount).toBe(0); + } finally { + harness.cleanup(); + } + }); + + it.each([false, true])('keeps alternating failure deadlines independent across two logins (first rate limited: %s)', (firstRateLimited) => { + const harness = createProbeHarness(); + try { + const first = harness.createTokenHome('alternating-first'); + const second = { ...harness.createTokenHome('alternating-second'), home: first.home }; + writeUsageCredentials(first.claudeConfig, { accessToken: 'access-a', refreshToken: 'refresh-a' }); + writeUsageCredentials(second.claudeConfig, { accessToken: 'access-b', refreshToken: 'refresh-b' }); + const render = (profile: TokenHome, mode: ProbeOptions['mode'], time: number) => harness.runProbe({ + home: profile.home, + claudeConfigDir: profile.claudeConfig, + pathDir: profile.bin, + mode, + nowMs: time, + statusCode: mode === 'status' ? 429 : 200, + responseHeaders: { 'retry-after': '120' }, + responseBody: profileResponseBody('recovered@example.com'), + target: 'account-email' + }); + expect(render(first, firstRateLimited ? 'status' : 'error', nowMs).requestCount).toBe(1); + expect(render(second, firstRateLimited ? 'error' : 'status', nowMs).requestCount).toBe(1); + expect(readCacheFile(first.home, `account-email-${fingerprint('refresh-a')}.lock`)).toEqual({ + tokenHash: fingerprint('refresh-a'), + blockedUntil: nowSeconds + (firstRateLimited ? 120 : 30) + }); + expect(readCacheFile(first.home, `account-email-${fingerprint('refresh-b')}.lock`)).toEqual({ + tokenHash: fingerprint('refresh-b'), + blockedUntil: nowSeconds + (firstRateLimited ? 30 : 120) + }); + // Access-token rotation must not bypass the login's backoff. + writeUsageCredentials(first.claudeConfig, { accessToken: 'rotated-access-a', refreshToken: 'refresh-a' }); + for (const profile of [first, second]) { + const blocked = render(profile, 'unexpected', nowMs + 10000); + expect(blocked.first).toEqual({ status: 'unavailable' }); + expect(blocked.requestCount).toBe(0); + } + const shortBackoff = firstRateLimited ? second : first; + const longBackoff = firstRateLimited ? first : second; + expect(render(shortBackoff, 'error', nowMs + 31000).requestCount).toBe(1); + expect(render(longBackoff, 'unexpected', nowMs + 31000).requestCount).toBe(0); + const recovered = render(longBackoff, 'success', nowMs + 121000); + expect(recovered.first).toEqual({ status: 'available', email: 'recovered@example.com' }); + expect(recovered.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({ status: 'unavailable' }); + expect(result.requestCount).toBe(1); + expect(readCacheFile(home.home, `account-email-${fingerprint('test-token')}.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-${fingerprint('test-token')}.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({ status: 'available', 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'); + fs.writeFileSync(path.join(home.home, '.claude.json'), JSON.stringify({ oauthAccount: { emailAddress: 'snapshot@example.com' } })); + + const result = harness.runProbe({ + home: home.home, + mode: 'unexpected', + nowMs, + target: 'account-email' + }); + + expect(result.first).toEqual({ status: 'no-credentials' }); + expect(result.second).toEqual({ status: 'no-credentials' }); + expect(result.requestCount).toBe(0); + expect(result.renderedEmail).toBe('Account: snapshot@example.com'); + } 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 467db511e..a4137729b 100644 --- a/src/utils/usage-fetch.ts +++ b/src/utils/usage-fetch.ts @@ -1,11 +1,16 @@ 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'; import * as path from 'node:path'; import { z } from 'zod'; +import type { AccountEmailResult } from '../types/AccountEmail'; + import { getClaudeConfigDir } from './claude-settings'; import { isExcludedFromProxy } from './no-proxy'; import { @@ -885,6 +890,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 { @@ -896,7 +902,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 { @@ -904,7 +910,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}`, @@ -920,8 +926,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' }; } @@ -1087,3 +1093,187 @@ 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. +// 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}`); +} + +const ProfileApiResponseSchema = z.looseObject({ account: z.looseObject({ email: z.string().min(1).nullable().optional() }).nullable().optional() }); +const CachedAccountEmailSchema = z.object({ + tokenHash: z.string(), + email: z.string().min(1) +}); +const AccountEmailLockSchema = z.object({ + blockedUntil: z.number(), + tokenHash: z.string() +}); + +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 writeCachedAccountEmail(tokenHash: string, email: string, owner: string): void { + const cachePath = getAccountEmailPath(tokenHash, 'json'); + const tempPath = `${cachePath}.${owner}.tmp`; + try { + fs.writeFileSync(tempPath, JSON.stringify({ tokenHash, email }), { mode: 0o600, flag: 'wx' }); + fs.renameSync(tempPath, cachePath); + } catch { + // Ignore cache write errors. + } finally { + try { + fs.unlinkSync(tempPath); + } catch { + // Already renamed or never created. + } + } +} + +// 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(); + 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 { + // 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 readAccountEmailBackoff(tokenHash: string, now: number): number { + try { + 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 0; + } +} + +function writeAccountEmailLock(tokenHash: string, blockedUntil: number): void { + try { + ensureCacheDirExists(); + 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 + } +} + +/** + * Distinguish no OAuth login from a failed lookup for an existing login so + * the widget never substitutes an unverified account snapshot after failure. + * Successful answers are cached per login across access-token refreshes. + */ +export async function fetchAccountEmail(): Promise { + const now = Math.floor(Date.now() / 1000); + const credentials = getUsageCredentialsWithBackoff(now); + if (!credentials) { + return { status: 'no-credentials' }; + } + + // 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 cached = readCachedAccountEmail(tokenHash); + if (cached !== null) { + return { status: 'available', email: cached }; + } + + if (readAccountEmailBackoff(tokenHash, now)) { + return { status: 'unavailable' }; + } + const owner = acquireAccountEmailLease(tokenHash, now); + if (owner === null) { + return { status: 'unavailable' }; + } + + 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); + } +} diff --git a/src/utils/usage.ts b/src/utils/usage.ts index f165705a9..aadea828c 100644 --- a/src/utils/usage.ts +++ b/src/utils/usage.ts @@ -1,4 +1,5 @@ export { + fetchAccountEmail, fetchUsageData, getUsageFetchedAtMs, getUsageLoginFingerprint, diff --git a/src/widgets/ClaudeAccountEmail.ts b/src/widgets/ClaudeAccountEmail.ts index 00afad82e..b8988e12b 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,20 @@ 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). A failed + // lookup for an existing login must not fall back to that snapshot. + if (context.accountEmail?.status === 'unavailable') { + return null; + } + const email = context.accountEmail?.status === 'available' + ? context.accountEmail.email + : 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..85a22b71e 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?: RenderContext['accountEmail']; } = {}): 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,51 @@ 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: { status: 'available', email: 'current@example.com' } })).toBe('Account: current@example.com'); + expect(render({ accountEmail: { status: 'available', email: 'current@example.com' }, rawValue: true })).toBe('current@example.com'); + }); + + it('falls back to .claude.json when there are no OAuth credentials', () => { + 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: { status: 'no-credentials' } })).toBe('Account: user@example.com'); + }); + + it('hides an unverified previous account when the current login lookup fails', () => { + process.env.CLAUDE_CONFIG_DIR = tempHomeDir; + fs.writeFileSync( + path.join(tempHomeDir, '.claude.json'), + JSON.stringify({ oauthAccount: { emailAddress: 'previous@example.com' } }) + ); + + expect(render({ accountEmail: { status: 'unavailable' } })).toBeNull(); + expect(render({ accountEmail: { status: 'unavailable' }, rawValue: true })).toBeNull(); + }); + + 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: { status: 'available', email: '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);