@scrylog/cli 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +46 -7
  2. package/package.json +13 -10
  3. package/src/api/docs/sessions.ts +3 -2
  4. package/src/api/docs/system.ts +3 -0
  5. package/src/api/docs/usage.ts +2 -2
  6. package/src/api/routes/sessions.ts +6 -2
  7. package/src/api/routes/system.ts +4 -1
  8. package/src/api/routes/webhooks/claude.ts +9 -21
  9. package/src/api/routes/webhooks/opencode.ts +6 -1
  10. package/src/api/routes.ts +1 -1
  11. package/src/api/schemas/common.ts +8 -0
  12. package/src/api/schemas/sessions.ts +15 -1
  13. package/src/api/schemas/usage.ts +1 -0
  14. package/src/cli/commands.ts +170 -26
  15. package/src/cli/index.ts +18 -0
  16. package/src/cli/program.ts +175 -0
  17. package/src/daemon/collectors/claude/collector.ts +11 -1
  18. package/src/daemon/collectors/claude/discovery.ts +2 -23
  19. package/src/daemon/collectors/codex/collector.ts +3 -3
  20. package/src/daemon/collectors/git.ts +60 -2
  21. package/src/daemon/collectors/herdr/collector.ts +128 -0
  22. package/src/daemon/collectors/herdr/index.ts +2 -0
  23. package/src/daemon/collectors/herdr/normalization.ts +111 -0
  24. package/src/daemon/collectors/opencode/collector.ts +4 -2
  25. package/src/daemon/collectors/opencode-db.ts +17 -5
  26. package/src/daemon/collectors/tmux/collector.ts +21 -1
  27. package/src/daemon/collectors/tmux/enrichment.ts +1 -0
  28. package/src/daemon/collectors/usage.ts +115 -49
  29. package/src/daemon/index.ts +2 -0
  30. package/src/daemon/store.ts +109 -14
  31. package/src/postinstall.cjs +11 -0
  32. package/src/shared/config.ts +33 -0
  33. package/src/shared/session-exclusions.ts +5 -0
  34. package/src/shared/session-view.ts +67 -6
  35. package/src/shared/terminal-capabilities.ts +130 -0
  36. package/src/shared/types.ts +33 -2
  37. package/src/shared/version.ts +44 -0
  38. package/src/tui/App.tsx +240 -0
  39. package/src/tui/assets/providers/SOURCES.md +21 -0
  40. package/src/tui/assets/providers/claude-terminal.png +0 -0
  41. package/src/tui/assets/providers/claude-terminal.svg +62 -0
  42. package/src/tui/assets/providers/claude.png +0 -0
  43. package/src/tui/assets/providers/copilot.png +0 -0
  44. package/src/tui/assets/providers/copilot.svg +44 -0
  45. package/src/tui/assets/providers/openai-terminal.png +0 -0
  46. package/src/tui/assets/providers/openai-terminal.svg +62 -0
  47. package/src/tui/assets/providers/openai.png +0 -0
  48. package/src/tui/assets/providers/opencode-terminal.png +0 -0
  49. package/src/tui/assets/providers/opencode-terminal.svg +62 -0
  50. package/src/tui/assets/providers/opencode.png +0 -0
  51. package/src/tui/assets/providers/shell.png +0 -0
  52. package/src/tui/assets/providers/shell.svg +23 -0
  53. package/src/tui/assets/providers/unknown.png +0 -0
  54. package/src/tui/assets/providers/unknown.svg +23 -0
  55. package/src/tui/client.ts +22 -8
  56. package/src/tui/components/BindingsModal.tsx +82 -0
  57. package/src/tui/components/DashboardHeader.tsx +256 -0
  58. package/src/tui/components/KeyBar.tsx +67 -0
  59. package/src/tui/components/SessionDetailModal.tsx +169 -0
  60. package/src/tui/components/SessionsView.tsx +184 -0
  61. package/src/tui/components/TabBar.tsx +40 -0
  62. package/src/tui/components/UsageSummaryPane.tsx +272 -0
  63. package/src/tui/components/UsageView.tsx +242 -0
  64. package/src/tui/components/tool-icons.ts +24 -0
  65. package/src/tui/index.tsx +106 -0
  66. package/src/tui/keybindings.ts +49 -0
  67. package/src/tui/model.ts +295 -0
  68. package/src/tui/state.ts +77 -0
  69. package/src/tui/theme.ts +110 -0
  70. package/src/usage/README.md +3 -3
  71. package/src/usage/clients/anthropic-oauth-usage.ts +100 -20
  72. package/src/usage/clients/anthropic-web-usage.ts +133 -49
  73. package/src/usage/clients/claude-cli-probe.ts +458 -132
  74. package/src/usage/clients/codex-app-server.ts +354 -0
  75. package/src/usage/clients/codex-oauth-usage.ts +143 -16
  76. package/src/usage/clients/opencode-go-api.ts +100 -0
  77. package/src/usage/clients/opencode-go-usage.ts +163 -27
  78. package/src/usage/errors.ts +33 -0
  79. package/src/usage/index.ts +2 -1
  80. package/src/usage/local/opencode-go-local.ts +194 -0
  81. package/src/usage/mappers.ts +24 -15
  82. package/src/usage/planner.ts +89 -25
  83. package/src/usage/providers/claude.ts +203 -83
  84. package/src/usage/providers/codex.ts +92 -11
  85. package/src/usage/providers/opencode-go.ts +94 -16
  86. package/src/usage/resolvers/browser-cookies.ts +679 -69
  87. package/src/usage/resolvers/claude-auth.ts +150 -41
  88. package/src/usage/resolvers/claude-desktop-auth.ts +170 -0
  89. package/src/usage/resolvers/claude-web.ts +72 -6
  90. package/src/usage/resolvers/codex-auth.ts +74 -17
  91. package/src/usage/resolvers/keychain-coordinator.ts +397 -0
  92. package/src/usage/resolvers/opencode-go-web.ts +47 -6
  93. package/src/usage/types.ts +37 -2
  94. package/src/usage/web-session-cache.ts +37 -0
  95. package/src/neo-blessed.d.ts +0 -4
  96. package/src/tui/app.ts +0 -920
  97. package/src/tui/index.ts +0 -193
@@ -1,12 +1,37 @@
1
- import { execSync } from "node:child_process";
2
- import { existsSync, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
3
2
  import { homedir } from "node:os";
4
3
  import { join } from "node:path";
5
4
  import type { TokenResolver } from "../resolver";
6
5
  import type { ClaudeOAuthCredentials } from "../types";
7
6
  import { IS_MAC } from "../../shared/platform";
7
+ import { keychainCoordinator, CLAUDE_SAFE_STORAGE_ITEMS } from "./keychain-coordinator";
8
+ import { ClaudeDesktopAuthResolver } from "./claude-desktop-auth";
9
+
10
+ export const CLAUDE_KEYCHAIN_TOKEN_SERVICES = ["claude-api-oauth", "Claude Code-credentials"] as const;
11
+
12
+ const DEFAULT_STALE_RESCAN_INTERVAL_MS = 10 * 60 * 1_000;
13
+
14
+ export interface ClaudeAuthResolverOptions {
15
+ candidatesSource?: () => Promise<ClaudeOAuthCredentials[]>;
16
+ staleRescanIntervalMs?: number;
17
+ now?: () => number;
18
+ }
8
19
 
9
20
  export class ClaudeAuthResolver implements TokenResolver<ClaudeOAuthCredentials> {
21
+ private cached?: ClaudeOAuthCredentials;
22
+ private nextScanAt = 0;
23
+ private readonly staleRescanIntervalMs: number;
24
+ private readonly now: () => number;
25
+ /** Last blocking keychain description seen while resolving candidates. */
26
+ private lastKeychainFailure: string | null = null;
27
+
28
+ constructor(
29
+ private readonly options: ClaudeAuthResolverOptions = {},
30
+ ) {
31
+ this.staleRescanIntervalMs = options.staleRescanIntervalMs ?? DEFAULT_STALE_RESCAN_INTERVAL_MS;
32
+ this.now = options.now ?? Date.now;
33
+ }
34
+
10
35
  private readonly debug = (message: string, meta?: Record<string, unknown>) => {
11
36
  // Avoid coupling to logger; stderr debug line is acceptable for resolver diagnostics.
12
37
  if (process.env.SCRYLOG_DEBUG_AUTH) {
@@ -15,42 +40,94 @@ export class ClaudeAuthResolver implements TokenResolver<ClaudeOAuthCredentials>
15
40
  };
16
41
 
17
42
  async resolve(): Promise<ClaudeOAuthCredentials | null> {
43
+ const cached = this.cached;
44
+ if (cached && !cached.isStale) return cached;
45
+ // Debounce full candidate scans (which include keychain reads) while a
46
+ // cached-but-stale credential exists, so polls never scan every cycle.
47
+ if (cached && this.now() < this.nextScanAt) return cached;
48
+ const selected = selectClaudeCredentials(await this.resolveCandidates());
49
+ this.cached = selected ?? undefined;
50
+ this.nextScanAt = this.now() + this.staleRescanIntervalMs;
51
+ this.lastKeychainFailure = selected
52
+ ? null
53
+ : keychainCoordinator.describeBlockingFailure([
54
+ { service: CLAUDE_KEYCHAIN_TOKEN_SERVICES[0]! },
55
+ { service: CLAUDE_KEYCHAIN_TOKEN_SERVICES[1]! },
56
+ ...CLAUDE_SAFE_STORAGE_ITEMS,
57
+ ]);
58
+ return this.cached ?? null;
59
+ }
60
+
61
+ /**
62
+ * Actionable keychain diagnostic for the latest resolution attempt, or null
63
+ * when the last attempt's failure was not keychain-related (missing items,
64
+ * absent caches are not surfaced).
65
+ */
66
+ describeKeychainFailure(): string | null {
67
+ return this.lastKeychainFailure;
68
+ }
69
+
70
+ /** Invalidates the daemon-lifetime credential cache (e.g. after a 401). */
71
+ invalidate(): void {
72
+ this.cached = undefined;
73
+ this.nextScanAt = 0;
74
+ for (const service of CLAUDE_KEYCHAIN_TOKEN_SERVICES) {
75
+ keychainCoordinator.clearMemo(service);
76
+ }
77
+ }
78
+
79
+ async resolveCandidates(): Promise<ClaudeOAuthCredentials[]> {
80
+ if (this.options.candidatesSource) return this.options.candidatesSource();
81
+ return this.resolveCandidatesUncached();
82
+ }
83
+
84
+ private async resolveCandidatesUncached(): Promise<ClaudeOAuthCredentials[]> {
85
+ const candidates: ClaudeOAuthCredentials[] = [];
86
+
18
87
  // 1. macOS Keychain is the primary store on macOS.
19
88
  if (IS_MAC) {
20
- const services = ["claude-api-oauth", "Claude Code-credentials"];
21
- for (const service of services) {
22
- const creds = this.tryService(service);
23
- if (creds) return creds;
89
+ for (const service of CLAUDE_KEYCHAIN_TOKEN_SERVICES) {
90
+ const creds = await this.tryService(service);
91
+ if (creds) candidates.push(creds);
24
92
  }
25
93
  } else {
26
94
  this.debug("Keychain not available on this platform", { platform: process.platform });
27
95
  }
28
96
 
29
- // 2. Linux/WSL/Windows: Claude Code stores credentials in ~/.claude/.credentials.json
97
+ // 2. Claude Desktop app local token cache (macOS / Windows only).
98
+ // Reads the Electron safeStorage-encrypted `oauth:tokenCache` from
99
+ // ~/Library/Application Support/Claude/config.json (macOS) or
100
+ // %APPDATA%/Anthropic/Claude/config.json (Windows). This covers the
101
+ // common case where the user has Claude Desktop but not Claude Code CLI.
102
+ const desktopCreds = await new ClaudeDesktopAuthResolver().resolve();
103
+ if (desktopCreds) candidates.push(desktopCreds);
104
+
105
+ // 3. Linux/WSL/Windows: Claude Code stores credentials in ~/.claude/.credentials.json
30
106
  const fileCreds = this.tryCredentialsFile();
31
- if (fileCreds) return fileCreds;
107
+ if (fileCreds) candidates.push(fileCreds);
32
108
 
33
- // 3. Universal env-var fallback
109
+ // 4. Universal env-var fallback
34
110
  const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN;
35
111
  if (envToken) {
36
- return { accessToken: envToken };
112
+ candidates.push({
113
+ accessToken: envToken,
114
+ owner: "environment",
115
+ credentialSource: "environment",
116
+ });
37
117
  }
38
118
 
39
- return null;
119
+ return candidates;
40
120
  }
41
121
 
42
122
  async isAvailable(): Promise<boolean> {
43
123
  return (await this.resolve()) !== null;
44
124
  }
45
125
 
46
- private tryService(service: string): ClaudeOAuthCredentials | null {
126
+ private async tryService(service: string): Promise<ClaudeOAuthCredentials | null> {
47
127
  try {
48
- const output = execSync(
49
- `security find-generic-password -s "${service}" -w`,
50
- { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }
51
- ).trim();
128
+ const output = await keychainCoordinator.read(service);
52
129
  if (!output) return null;
53
- return this.parseCredentialsJson(output);
130
+ return parseClaudeCredentialsJson(output, "keychain");
54
131
  } catch (error) {
55
132
  this.debug("Keychain lookup failed", { service, error: error instanceof Error ? error.message : String(error) });
56
133
  return null;
@@ -63,37 +140,69 @@ export class ClaudeAuthResolver implements TokenResolver<ClaudeOAuthCredentials>
63
140
 
64
141
  const claudeDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
65
142
  const path = join(claudeDir, ".credentials.json");
66
- if (!existsSync(path)) return null;
67
-
68
143
  try {
69
144
  const raw = readFileSync(path, "utf8");
70
- return this.parseCredentialsJson(raw);
145
+ return parseClaudeCredentialsJson(raw, "credentials-file");
71
146
  } catch (error) {
72
147
  this.debug("Failed to read credentials file", { path, error: error instanceof Error ? error.message : String(error) });
73
148
  return null;
74
149
  }
75
150
  }
76
151
 
77
- private parseCredentialsJson(input: string): ClaudeOAuthCredentials | null {
78
- try {
79
- const parsed = JSON.parse(input) as Record<string, unknown>;
80
- // Handle nested structure: { claudeAiOauth: { accessToken, ... } }
81
- const inner = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object"
82
- ? parsed.claudeAiOauth as Record<string, unknown>
83
- : parsed;
84
- const accessToken = inner.accessToken ?? inner.access_token;
85
- if (!accessToken) return null;
86
- return {
87
- accessToken: String(accessToken),
88
- refreshToken: inner.refreshToken ? String(inner.refreshToken) : undefined,
89
- expiresAt: inner.expiresAt ? String(inner.expiresAt) : undefined,
90
- scopes: Array.isArray(inner.scopes) ? inner.scopes.map(String) : undefined,
91
- rateLimitTier: inner.rateLimitTier ? String(inner.rateLimitTier) : undefined,
92
- subscriptionType: inner.subscriptionType ? String(inner.subscriptionType) : undefined,
93
- };
94
- } catch {
95
- // Not JSON — treat the raw string as an access token.
96
- return { accessToken: input.trim() };
97
- }
152
+ }
153
+
154
+ const EXPIRY_SKEW_MS = 60_000;
155
+
156
+ function parseExpiry(value: unknown): number | undefined | null {
157
+ if (value === undefined || value === null || value === "") return undefined;
158
+ const millis = typeof value === "number"
159
+ ? value
160
+ : typeof value === "string" && /^\d+$/.test(value.trim())
161
+ ? Number(value)
162
+ : typeof value === "string"
163
+ ? Date.parse(value)
164
+ : Number.NaN;
165
+ return Number.isFinite(millis) && millis > 0 ? millis : null;
166
+ }
167
+
168
+ export function parseClaudeCredentialsJson(
169
+ input: string,
170
+ credentialSource: "keychain" | "credentials-file",
171
+ now = Date.now(),
172
+ ): ClaudeOAuthCredentials | null {
173
+ let parsed: unknown;
174
+ try {
175
+ parsed = JSON.parse(input);
176
+ } catch {
177
+ return null;
98
178
  }
179
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
180
+ const outer = parsed as Record<string, unknown>;
181
+ const inner = outer.claudeAiOauth && typeof outer.claudeAiOauth === "object" && !Array.isArray(outer.claudeAiOauth)
182
+ ? outer.claudeAiOauth as Record<string, unknown>
183
+ : outer;
184
+ const token = inner.accessToken ?? inner.access_token;
185
+ if (typeof token !== "string" || !token.trim()) return null;
186
+
187
+ const expiryMillis = parseExpiry(inner.expiresAt ?? inner.expires_at);
188
+ if (expiryMillis === null) return null;
189
+ return {
190
+ accessToken: token.trim(),
191
+ refreshToken: typeof (inner.refreshToken ?? inner.refresh_token) === "string"
192
+ ? inner.refreshToken as string ?? inner.refresh_token as string
193
+ : undefined,
194
+ expiresAt: expiryMillis === undefined ? undefined : new Date(expiryMillis).toISOString(),
195
+ owner: "claude",
196
+ credentialSource,
197
+ isStale: expiryMillis === undefined || expiryMillis <= now + EXPIRY_SKEW_MS,
198
+ scopes: Array.isArray(inner.scopes) && inner.scopes.every((scope) => typeof scope === "string")
199
+ ? inner.scopes
200
+ : undefined,
201
+ rateLimitTier: typeof inner.rateLimitTier === "string" ? inner.rateLimitTier : undefined,
202
+ subscriptionType: typeof inner.subscriptionType === "string" ? inner.subscriptionType : undefined,
203
+ };
204
+ }
205
+
206
+ export function selectClaudeCredentials(candidates: ClaudeOAuthCredentials[]): ClaudeOAuthCredentials | null {
207
+ return candidates.find((candidate) => !candidate.isStale) ?? candidates[0] ?? null;
99
208
  }
@@ -0,0 +1,170 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { TokenResolver } from "../resolver";
5
+ import type { ClaudeOAuthCredentials } from "../types";
6
+ import { IS_MAC, IS_WINDOWS } from "../../shared/platform";
7
+ import { getChromiumSafeStorageKey, decryptSafeStorageBlob } from "./browser-cookies";
8
+ import { keychainCoordinator, CLAUDE_SAFE_STORAGE_ITEMS } from "./keychain-coordinator";
9
+
10
+ /**
11
+ * Shape of a single entry in the `oauth:tokenCache` field of Claude Desktop's
12
+ * `config.json`. The key in the outer Record is a colon-separated composite:
13
+ * `<accountId>:<orgId>:<audience>:<space-separated scopes>`
14
+ */
15
+ interface TokenCacheEntry {
16
+ token: string;
17
+ refreshToken?: string;
18
+ /** Milliseconds since Unix epoch */
19
+ expiresAt?: number;
20
+ subscriptionType?: string;
21
+ rateLimitTier?: string;
22
+ }
23
+
24
+ /**
25
+ * Reads the Claude Desktop app's local OAuth token cache and surfaces it as a
26
+ * `ClaudeOAuthCredentials` so the OAuth usage route works without Claude Code CLI.
27
+ *
28
+ * Data source:
29
+ * macOS: ~/Library/Application Support/Claude/config.json → oauth:tokenCache
30
+ * Windows: %APPDATA%/Anthropic/Claude/config.json → oauth:tokenCache
31
+ * Linux: Claude Desktop is unavailable; resolver always returns null.
32
+ *
33
+ * The `oauth:tokenCache` value is an Electron safeStorage blob (base64, v10/v11
34
+ * AES-128-CBC) decrypted with the Keychain key from "Claude Safe Storage".
35
+ */
36
+ export class ClaudeDesktopAuthResolver implements TokenResolver<ClaudeOAuthCredentials> {
37
+ private readonly debug = (message: string, meta?: Record<string, unknown>) => {
38
+ if (process.env.SCRYLOG_DEBUG_AUTH) {
39
+ process.stderr.write(
40
+ `[scrylog:claude-desktop-auth] ${message}${meta ? ` ${JSON.stringify(meta)}` : ""}\n`
41
+ );
42
+ }
43
+ };
44
+
45
+ async resolve(): Promise<ClaudeOAuthCredentials | null> {
46
+ const configPath = this.getConfigPath();
47
+ if (!configPath) {
48
+ this.debug("Claude Desktop not supported on this platform", { platform: process.platform });
49
+ return null;
50
+ }
51
+ if (!existsSync(configPath)) {
52
+ this.debug("Claude Desktop config.json not found", { path: configPath });
53
+ return null;
54
+ }
55
+
56
+ try {
57
+ const raw = readFileSync(configPath, "utf8");
58
+ const cfg = JSON.parse(raw) as Record<string, unknown>;
59
+ const blobB64 = cfg["oauth:tokenCache"];
60
+ if (typeof blobB64 !== "string" || !blobB64) {
61
+ this.debug("oauth:tokenCache missing or not a string in config.json");
62
+ return null;
63
+ }
64
+
65
+ const buf = Buffer.from(blobB64, "base64");
66
+ const key = await getChromiumSafeStorageKey("Claude Safe Storage", "Claude");
67
+ if (!key) {
68
+ this.debug("Failed to retrieve Claude Safe Storage key from Keychain");
69
+ return null;
70
+ }
71
+
72
+ const plaintext = decryptSafeStorageBlob(buf, key);
73
+ if (!plaintext) {
74
+ this.debug("Failed to decrypt oauth:tokenCache blob");
75
+ return null;
76
+ }
77
+
78
+ const cache = JSON.parse(plaintext) as Record<string, TokenCacheEntry>;
79
+ const creds = this.selectBestEntry(cache);
80
+ if (creds) {
81
+ this.debug("Resolved Claude Desktop OAuth credentials");
82
+ } else {
83
+ this.debug("No usable entry found in oauth:tokenCache");
84
+ }
85
+ return creds;
86
+ } catch (err) {
87
+ this.debug("Error reading Claude Desktop config", {
88
+ error: err instanceof Error ? err.message : String(err),
89
+ });
90
+ return null;
91
+ }
92
+ }
93
+
94
+ async isAvailable(): Promise<boolean> {
95
+ return (await this.resolve()) !== null;
96
+ }
97
+
98
+ /** Actionable keychain diagnostic for the latest resolution attempt. */
99
+ describeKeychainFailure(): string | null {
100
+ return keychainCoordinator.describeBlockingFailure(CLAUDE_SAFE_STORAGE_ITEMS);
101
+ }
102
+
103
+ private getConfigPath(): string | null {
104
+ const home = homedir();
105
+ if (IS_MAC) {
106
+ return join(home, "Library", "Application Support", "Claude", "config.json");
107
+ }
108
+ if (IS_WINDOWS) {
109
+ const appData = process.env.APPDATA ?? join(home, "AppData", "Roaming");
110
+ return join(appData, "Anthropic", "Claude", "config.json");
111
+ }
112
+ // Linux: Claude Desktop is not available
113
+ return null;
114
+ }
115
+
116
+ /**
117
+ * Pick the best (longest-lived, has user:profile scope) non-expired token entry.
118
+ *
119
+ * The cache key format is:
120
+ * `<accountId>:<orgId>:<audience>:<space-separated scopes>`
121
+ * e.g.
122
+ * `uuid1:uuid2:https://api.anthropic.com:user:inference user:file_upload user:profile ...`
123
+ *
124
+ * AnthropicOAuthUsageClient requires the `user:profile` scope, so entries that
125
+ * lack it are skipped.
126
+ */
127
+ private selectBestEntry(
128
+ cache: Record<string, TokenCacheEntry>
129
+ ): ClaudeOAuthCredentials | null {
130
+ const now = Date.now();
131
+ let bestCreds: ClaudeOAuthCredentials | null = null;
132
+ let bestExpiresAt = -Infinity;
133
+ let bestIsStale = true;
134
+
135
+ for (const [scopeKey, entry] of Object.entries(cache)) {
136
+ if (!entry.token) continue;
137
+ // Require user:profile scope for the OAuth usage endpoint
138
+ if (!scopeKey.includes("user:profile")) continue;
139
+
140
+ const isStale = entry.expiresAt === undefined || entry.expiresAt <= now + 60_000;
141
+ const expiresAt = entry.expiresAt ?? -Infinity;
142
+ if ((!isStale && bestIsStale) || (isStale === bestIsStale && expiresAt > bestExpiresAt)) {
143
+ bestExpiresAt = expiresAt;
144
+ bestIsStale = isStale;
145
+
146
+ // Parse space-separated scopes from the composite key.
147
+ // Key format after the audience URL: "...:<audience>:<scopes>"
148
+ const audienceMatch = scopeKey.match(/:[^:]+:\/\/[^:]+:(.+)$/);
149
+ const scopes = audienceMatch ? audienceMatch[1].split(" ") : undefined;
150
+
151
+ bestCreds = {
152
+ accessToken: entry.token,
153
+ refreshToken: entry.refreshToken,
154
+ expiresAt:
155
+ entry.expiresAt !== undefined
156
+ ? new Date(entry.expiresAt).toISOString()
157
+ : undefined,
158
+ owner: "claude",
159
+ credentialSource: "claude-desktop",
160
+ isStale,
161
+ scopes,
162
+ subscriptionType: entry.subscriptionType,
163
+ rateLimitTier: entry.rateLimitTier,
164
+ };
165
+ }
166
+ }
167
+
168
+ return bestCreds;
169
+ }
170
+ }
@@ -1,16 +1,82 @@
1
1
  import type { TokenResolver } from "../resolver";
2
2
  import type { ClaudeWebSession } from "../types";
3
- import { extractCookies, buildCookieHeader } from "./browser-cookies";
3
+ import { usageWebSessionCache } from "../web-session-cache";
4
+ import { BrowserCookieSourceCursor, buildCookieHeader, hasBrowserCookieSources } from "./browser-cookies";
5
+ import { keychainCoordinator, CLAUDE_SAFE_STORAGE_ITEMS } from "./keychain-coordinator";
6
+
7
+ export const CLAUDE_WEB_CACHE_KEY = "claude-web";
4
8
 
5
9
  export class ClaudeWebResolver implements TokenResolver<ClaudeWebSession> {
6
- async resolve(): Promise<ClaudeWebSession | null> {
7
- const cookies = extractCookies("claude.ai");
8
- const sessionKey = cookies.find((c) => c.name === "sessionKey");
9
- if (!sessionKey) return null;
10
- return { cookieHeader: buildCookieHeader(cookies) };
10
+ constructor(
11
+ private readonly cursorFactory: () => BrowserCookieSourceCursor = () =>
12
+ new BrowserCookieSourceCursor("claude.ai", ["sessionKey"], { preferredBrowserId: "claude-desktop" }),
13
+ ) {}
14
+
15
+ resolve(): Promise<ClaudeWebSession | null> {
16
+ return Promise.resolve().then(() => this.buildSession());
17
+ }
18
+
19
+ /**
20
+ * Cache-only resolution for planning and Web extras. Never reads a browser
21
+ * cookie store and never requests a Safe Storage key.
22
+ */
23
+ async resolveCached(): Promise<ClaudeWebSession | null> {
24
+ const observed = usageWebSessionCache.observe(CLAUDE_WEB_CACHE_KEY);
25
+ if (!observed.value) return null;
26
+ return {
27
+ cookieHeader: observed.value,
28
+ cookieCandidates: [observed.value],
29
+ cacheRevision: observed.revision,
30
+ };
31
+ }
32
+
33
+ /**
34
+ * True when an import could yield candidates: a cached value exists or some
35
+ * browser import source is present. Cheap existence checks only — no SQLite
36
+ * reads and no Keychain requests.
37
+ */
38
+ async hasImportSources(): Promise<boolean> {
39
+ if (usageWebSessionCache.observe(CLAUDE_WEB_CACHE_KEY).value) return true;
40
+ return hasBrowserCookieSources();
41
+ }
42
+
43
+ private async buildSession(): Promise<ClaudeWebSession | null> {
44
+ const observed = usageWebSessionCache.observe(CLAUDE_WEB_CACHE_KEY);
45
+ if (observed.value) {
46
+ return {
47
+ cookieHeader: observed.value,
48
+ cookieCandidates: [observed.value],
49
+ cacheRevision: observed.revision,
50
+ };
51
+ }
52
+
53
+ // Cache miss: import the first source. Later sources are only inspected
54
+ // when the client advances the cursor after a classified auth rejection.
55
+ const cursor = this.cursorFactory();
56
+ const candidate = await cursor.next();
57
+ if (!candidate) return null;
58
+ const header = buildCookieHeader(candidate.cookies);
59
+ if (!header) return null;
60
+ return {
61
+ cookieHeader: header,
62
+ cookieCandidates: [header],
63
+ cacheRevision: observed.revision,
64
+ importNext: async () => {
65
+ const next = await cursor.next();
66
+ return next ? buildCookieHeader(next.cookies) : null;
67
+ },
68
+ };
11
69
  }
12
70
 
13
71
  async isAvailable(): Promise<boolean> {
14
72
  return (await this.resolve()) !== null;
15
73
  }
74
+
75
+ /**
76
+ * Actionable keychain diagnostic for the latest import attempt (e.g. the
77
+ * Safe Storage read failed), or null when the miss was not keychain-related.
78
+ */
79
+ describeKeychainFailure(): string | null {
80
+ return keychainCoordinator.describeBlockingFailure(CLAUDE_SAFE_STORAGE_ITEMS);
81
+ }
16
82
  }
@@ -1,8 +1,22 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { TokenResolver } from "../resolver";
5
5
  import type { CodexOAuthCredentials } from "../types";
6
+ import { UsageError } from "../errors";
7
+
8
+ const NATIVE_EXPIRY_MARGIN_MS = 5 * 60 * 1_000;
9
+ const NATIVE_REFRESH_MAX_AGE_MS = 8 * 24 * 60 * 60 * 1_000;
10
+
11
+ export class CodexCredentialSourceError extends UsageError {
12
+ constructor(
13
+ public readonly reason: "malformed" | "unreadable",
14
+ message: string,
15
+ ) {
16
+ super(reason === "malformed" ? "invalid-response" : "transient", message);
17
+ this.name = "CodexCredentialSourceError";
18
+ }
19
+ }
6
20
 
7
21
  function getCodexDir(): string {
8
22
  if (process.env.CODEX_HOME) return process.env.CODEX_HOME;
@@ -11,7 +25,6 @@ function getCodexDir(): string {
11
25
 
12
26
  function readConfigToml(codexDir: string): string | undefined {
13
27
  const path = join(codexDir, "config.toml");
14
- if (!existsSync(path)) return undefined;
15
28
  try {
16
29
  const content = readFileSync(path, "utf8");
17
30
  for (const line of content.split(/\r?\n/)) {
@@ -39,6 +52,38 @@ function decodeJwtClaims(token: string): { email?: string; sub?: string; org_id?
39
52
  }
40
53
  }
41
54
 
55
+ function decodeJwtExpiry(token: string): number | undefined {
56
+ try {
57
+ const payload = token.split(".")[1];
58
+ if (!payload) return undefined;
59
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Record<string, unknown>;
60
+ return typeof claims["exp"] === "number" && Number.isFinite(claims["exp"])
61
+ ? claims["exp"] * 1_000
62
+ : undefined;
63
+ } catch {
64
+ return undefined;
65
+ }
66
+ }
67
+
68
+ function parseTimestamp(value: unknown): number | undefined {
69
+ if (typeof value !== "string") return undefined;
70
+ const timestamp = Date.parse(value);
71
+ return Number.isNaN(timestamp) ? undefined : timestamp;
72
+ }
73
+
74
+ export function isCodexCredentialFresh(
75
+ credentials: CodexOAuthCredentials,
76
+ now = Date.now(),
77
+ ): boolean {
78
+ if (credentials.tokenExpiresAt !== undefined) {
79
+ return credentials.tokenExpiresAt > now + NATIVE_EXPIRY_MARGIN_MS;
80
+ }
81
+ if (credentials.lastRefreshAt !== undefined) {
82
+ return now - credentials.lastRefreshAt < NATIVE_REFRESH_MAX_AGE_MS;
83
+ }
84
+ return false;
85
+ }
86
+
42
87
  /**
43
88
  * Extract access_token and related fields from Codex auth.json.
44
89
  * Codex CLI writes credentials in a nested "tokens" object, e.g.:
@@ -56,10 +101,10 @@ function extractTokens(raw: Record<string, unknown>): {
56
101
  : undefined;
57
102
 
58
103
  const accessToken =
59
- typeof raw["access_token"] === "string"
60
- ? raw["access_token"]
61
- : typeof tokens?.["access_token"] === "string"
62
- ? tokens["access_token"]
104
+ typeof tokens?.["access_token"] === "string"
105
+ ? tokens["access_token"]
106
+ : typeof raw["access_token"] === "string"
107
+ ? raw["access_token"]
63
108
  : undefined;
64
109
 
65
110
  const accountId =
@@ -76,40 +121,52 @@ function extractTokens(raw: Record<string, unknown>): {
76
121
  }
77
122
 
78
123
  export class CodexAuthResolver implements TokenResolver<CodexOAuthCredentials> {
124
+ constructor(private readonly configuredBaseUrl?: string) {}
125
+
79
126
  async resolve(): Promise<CodexOAuthCredentials | null> {
80
127
  const codexDir = getCodexDir();
81
128
  const authPath = join(codexDir, "auth.json");
82
- if (!existsSync(authPath)) return null;
129
+ let content: string;
130
+ try {
131
+ content = readFileSync(authPath, "utf8");
132
+ } catch (error) {
133
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
134
+ throw new CodexCredentialSourceError("unreadable", "Codex auth.json could not be read");
135
+ }
83
136
 
84
137
  try {
85
- const raw = JSON.parse(readFileSync(authPath, "utf8")) as Record<string, unknown>;
138
+ const parsed = JSON.parse(content) as unknown;
139
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
140
+ throw new Error("expected a JSON object");
141
+ }
142
+ const raw = parsed as Record<string, unknown>;
86
143
  const tokens = extractTokens(raw);
87
144
  if (!tokens.accessToken) return null;
88
145
 
89
146
  const claims = decodeJwtClaims(tokens.accessToken);
90
- const chatgptBaseUrl = readConfigToml(codexDir);
147
+ const tokenExpiresAt = decodeJwtExpiry(tokens.accessToken) ?? parseTimestamp(raw["expires_at"]);
148
+ const lastRefreshAt = parseTimestamp(raw["last_refresh"]);
149
+ const chatgptBaseUrl = this.configuredBaseUrl ?? readConfigToml(codexDir);
91
150
 
92
151
  return {
93
152
  accessToken: tokens.accessToken,
94
153
  refreshToken: tokens.refreshToken,
95
154
  expiresAt: typeof raw["expires_at"] === "string" ? raw["expires_at"] : undefined,
155
+ ...(tokenExpiresAt !== undefined ? { tokenExpiresAt } : {}),
156
+ ...(lastRefreshAt !== undefined ? { lastRefreshAt } : {}),
96
157
  accountEmail: claims.email ?? null,
97
158
  accountId: tokens.accountId ?? claims.sub ?? claims.org_id ?? null,
98
159
  ...(chatgptBaseUrl ? { chatgptBaseUrl } : {}),
99
160
  };
100
- } catch {
101
- return null;
161
+ } catch (error) {
162
+ if (error instanceof CodexCredentialSourceError) throw error;
163
+ throw new CodexCredentialSourceError("malformed", "Codex auth.json is malformed");
102
164
  }
103
165
  }
104
166
 
105
167
  async isAvailable(): Promise<boolean> {
106
- const codexDir = getCodexDir();
107
- const authPath = join(codexDir, "auth.json");
108
- if (!existsSync(authPath)) return false;
109
168
  try {
110
- const raw = JSON.parse(readFileSync(authPath, "utf8")) as Record<string, unknown>;
111
- const { accessToken } = extractTokens(raw);
112
- return typeof accessToken === "string" && accessToken.length > 0;
169
+ return (await this.resolve()) !== null;
113
170
  } catch {
114
171
  return false;
115
172
  }