tokenusage-cli 0.1.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 (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,508 @@
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+ const fs = require("node:fs");
4
+ const cp = require("node:child_process");
5
+
6
+ const { readJson } = require("./fs");
7
+ const { resolveTrackerPaths } = require("./tracker-paths");
8
+ const { probeOpenclawSessionPluginState } = require("./openclaw-session-plugin");
9
+
10
+ const OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
11
+ const MACOS_SECURITY_BIN = "/usr/bin/security";
12
+ const CLAUDE_CODE_KEYCHAIN_SERVICES = ["Claude Code-credentials"];
13
+ // On Linux and Windows, Claude Code persists the same OAuth payload as a plain
14
+ // JSON file instead of the macOS Keychain — at ~/.claude/.credentials.json on
15
+ // Linux and %USERPROFILE%\.claude\.credentials.json on Windows (both resolve via
16
+ // os.homedir()). The payload shape is identical:
17
+ // { claudeAiOauth: { accessToken, subscriptionType, ... } }
18
+ const CLAUDE_CODE_CREDENTIALS_FILE = ".credentials.json";
19
+ // Platforms where Claude Code stores credentials in the plain JSON file above
20
+ // rather than the macOS Keychain.
21
+ const CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS = new Set(["linux", "win32"]);
22
+ // Refresh slightly before wall-clock expiry so Limits does not spend a request
23
+ // that Anthropic answers with 429 for a real-but-expired Claude Code token.
24
+ const CLAUDE_TOKEN_EXPIRY_SKEW_MS = 60_000;
25
+
26
+ function usesClaudeCodeCredentialsFile(platform) {
27
+ return CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS.has(platform);
28
+ }
29
+
30
+ function normalizeString(value) {
31
+ if (typeof value !== "string") return null;
32
+ const trimmed = value.trim();
33
+ return trimmed.length > 0 ? trimmed : null;
34
+ }
35
+
36
+ function normalizeScalarToString(value) {
37
+ if (value === null || value === undefined) return null;
38
+ if (typeof value === "string") return normalizeString(value);
39
+ if (typeof value === "number") {
40
+ if (!Number.isFinite(value)) return null;
41
+ return normalizeString(String(value));
42
+ }
43
+ if (typeof value === "boolean") return value ? "true" : "false";
44
+ return null;
45
+ }
46
+
47
+ function base64UrlDecodeToString(value) {
48
+ if (typeof value !== "string" || value.length === 0) return null;
49
+ const padLen = (4 - (value.length % 4)) % 4;
50
+ const padded = value + "=".repeat(padLen);
51
+ const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
52
+ try {
53
+ return Buffer.from(base64, "base64").toString("utf8");
54
+ } catch (_e) {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function decodeJwtPayload(token) {
60
+ const jwt = normalizeString(token);
61
+ if (!jwt) return null;
62
+ const parts = jwt.split(".");
63
+ if (parts.length < 2) return null;
64
+ const decoded = base64UrlDecodeToString(parts[1]);
65
+ if (!decoded) return null;
66
+ try {
67
+ return JSON.parse(decoded);
68
+ } catch (_e) {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ function extractOpenAiAuthNamespace(payload) {
74
+ if (!payload || typeof payload !== "object") return null;
75
+ const ns = payload[OPENAI_AUTH_CLAIM];
76
+ if (!ns || typeof ns !== "object" || Array.isArray(ns)) return null;
77
+ return ns;
78
+ }
79
+
80
+ function extractChatgptSubscriptionFromPayload(payload) {
81
+ const ns = extractOpenAiAuthNamespace(payload);
82
+ if (!ns) return null;
83
+
84
+ const planType = normalizeString(ns.chatgpt_plan_type);
85
+ const activeStart = normalizeString(ns.chatgpt_subscription_active_start);
86
+ const activeUntil = normalizeString(ns.chatgpt_subscription_active_until);
87
+ const lastChecked = normalizeString(ns.chatgpt_subscription_last_checked);
88
+
89
+ if (!planType && !activeStart && !activeUntil && !lastChecked) return null;
90
+ return { planType, activeStart, activeUntil, lastChecked };
91
+ }
92
+
93
+ function mergeSubscription(primary, secondary) {
94
+ if (!primary && !secondary) return null;
95
+ const a = primary || {};
96
+ const b = secondary || {};
97
+ return {
98
+ planType: a.planType || b.planType || null,
99
+ activeStart: a.activeStart || b.activeStart || null,
100
+ activeUntil: a.activeUntil || b.activeUntil || null,
101
+ lastChecked: a.lastChecked || b.lastChecked || null,
102
+ };
103
+ }
104
+
105
+ function isDisplayablePlanType(planType) {
106
+ const normalized = normalizeString(planType);
107
+ if (!normalized) return false;
108
+ const v = normalized.toLowerCase();
109
+ if (v === "free" || v === "none" || v === "unknown") return false;
110
+ return true;
111
+ }
112
+
113
+ function resolveCodexHome({ home, env }) {
114
+ const explicit = normalizeString(env?.CODEX_HOME);
115
+ return explicit ? path.resolve(explicit) : path.join(home, ".codex");
116
+ }
117
+
118
+ function resolveOpencodeDataDir({ home, env }) {
119
+ const explicit = normalizeString(env?.XDG_DATA_HOME);
120
+ const base = explicit ? path.resolve(explicit) : path.join(home, ".local", "share");
121
+ return path.join(base, "opencode");
122
+ }
123
+
124
+ async function detectCodexChatgptSubscription({ home, env }) {
125
+ const codexHome = resolveCodexHome({ home, env });
126
+ const authPath = path.join(codexHome, "auth.json");
127
+ const auth = await readJson(authPath);
128
+ if (!auth || typeof auth !== "object") return null;
129
+
130
+ const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
131
+ const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
132
+
133
+ const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
134
+ const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
135
+ const merged = mergeSubscription(accessInfo, idInfo);
136
+ if (!merged || !isDisplayablePlanType(merged.planType)) return null;
137
+
138
+ return {
139
+ tool: "codex",
140
+ provider: "openai",
141
+ product: "chatgpt",
142
+ planType: merged.planType,
143
+ activeStart: merged.activeStart,
144
+ activeUntil: merged.activeUntil,
145
+ lastChecked: merged.lastChecked,
146
+ };
147
+ }
148
+
149
+ async function detectOpencodeChatgptSubscription({ home, env }) {
150
+ const dataDir = resolveOpencodeDataDir({ home, env });
151
+ const authPath = path.join(dataDir, "auth.json");
152
+ const auth = await readJson(authPath);
153
+ if (!auth || typeof auth !== "object") return null;
154
+
155
+ const accessPayload = decodeJwtPayload(auth?.openai?.access);
156
+ const info = extractChatgptSubscriptionFromPayload(accessPayload);
157
+ if (!info || !isDisplayablePlanType(info.planType)) return null;
158
+
159
+ return {
160
+ tool: "opencode",
161
+ provider: "openai",
162
+ product: "chatgpt",
163
+ planType: info.planType,
164
+ activeStart: info.activeStart,
165
+ activeUntil: info.activeUntil,
166
+ lastChecked: info.lastChecked,
167
+ };
168
+ }
169
+
170
+ // Match Claude Code 2.1.267's account derivation. A service-only lookup may
171
+ // select credentials from an older installation before the current account.
172
+ function resolveClaudeKeychainAccount({ env = process.env, userInfo = os.userInfo } = {}) {
173
+ let account;
174
+ try { account = env.USER || userInfo().username; } catch (_error) { return "claude-code-user"; }
175
+ return typeof account === "string" && /^[a-zA-Z0-9._-]+$/.test(account)
176
+ ? account : "claude-code-user";
177
+ }
178
+
179
+ function probeMacosKeychainGenericPassword({ service, securityRunner, timeoutMs, env } = {}) {
180
+ const svc = normalizeString(service);
181
+ if (!svc) return false;
182
+
183
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
184
+ if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return false;
185
+
186
+ const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env })], {
187
+ stdio: "ignore",
188
+ timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
189
+ });
190
+
191
+ if (!result || result.error) return false;
192
+ return result.status === 0;
193
+ }
194
+
195
+ function readMacosKeychainPassword({ service, securityRunner, timeoutMs, env } = {}) {
196
+ const svc = normalizeString(service);
197
+ if (!svc) return null;
198
+
199
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
200
+ if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return null;
201
+
202
+ const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env }), "-w"], {
203
+ stdio: ["ignore", "pipe", "ignore"],
204
+ timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
205
+ encoding: "utf8",
206
+ });
207
+
208
+ if (!result || result.error) return null;
209
+ if (result.status !== 0) return null;
210
+
211
+ const stdout =
212
+ typeof result.stdout === "string"
213
+ ? result.stdout
214
+ : Buffer.isBuffer(result.stdout)
215
+ ? result.stdout.toString("utf8")
216
+ : "";
217
+ const trimmed = stdout.trim();
218
+ return trimmed.length > 0 ? trimmed : null;
219
+ }
220
+
221
+ function readClaudeCodeCredentialsFile({ home, fsReader } = {}) {
222
+ const homeDir = typeof home === "string" && home ? home : os.homedir();
223
+ const credPath = path.join(homeDir, ".claude", CLAUDE_CODE_CREDENTIALS_FILE);
224
+ const reader = typeof fsReader === "function" ? fsReader : fs.readFileSync;
225
+ try {
226
+ return reader(credPath, "utf8");
227
+ } catch (_e) {
228
+ return null;
229
+ }
230
+ }
231
+
232
+ function detectClaudeCodeCredentialsPresence({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
233
+ if (platform === "darwin") {
234
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
235
+ const present = probeMacosKeychainGenericPassword({
236
+ service,
237
+ securityRunner,
238
+ env,
239
+ });
240
+ if (!present) continue;
241
+
242
+ // Existence-only probe: do not read secrets or infer paid tier.
243
+ return {
244
+ tool: "claude",
245
+ provider: "anthropic",
246
+ product: "credentials",
247
+ planType: "present",
248
+ };
249
+ }
250
+ return null;
251
+ }
252
+
253
+ if (!usesClaudeCodeCredentialsFile(platform)) return null;
254
+
255
+ // Linux/Windows: credentials live in the .credentials.json file (mode 0600 on
256
+ // Linux; user-profile ACLs on Windows). Existence-only: just check that the
257
+ // file is readable and contains the OAuth key.
258
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
259
+ if (!raw) return null;
260
+ try {
261
+ const payload = JSON.parse(raw);
262
+ if (payload?.claudeAiOauth && typeof payload.claudeAiOauth === "object") {
263
+ return {
264
+ tool: "claude",
265
+ provider: "anthropic",
266
+ product: "credentials",
267
+ planType: "present",
268
+ };
269
+ }
270
+ } catch (_e) {
271
+ // fall through
272
+ }
273
+ return null;
274
+ }
275
+
276
+ function parseClaudeOauthExpiryMs(value) {
277
+ if (typeof value === "number") {
278
+ if (!Number.isFinite(value)) return null;
279
+ if (value <= 0) return 0;
280
+ return value < 1e12 ? value * 1000 : value;
281
+ }
282
+ if (typeof value === "string") {
283
+ const trimmed = value.trim();
284
+ if (!trimmed) return null;
285
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) return parseClaudeOauthExpiryMs(Number(trimmed));
286
+ const ms = Date.parse(trimmed);
287
+ return Number.isFinite(ms) ? ms : null;
288
+ }
289
+ return null;
290
+ }
291
+
292
+ function extractClaudeCodeOauth(payload, nowMs = Date.now()) {
293
+ const oauth = payload?.claudeAiOauth;
294
+ const accessToken = normalizeString(oauth?.accessToken);
295
+ if (!accessToken) return null;
296
+ const expiresAtMs = parseClaudeOauthExpiryMs(oauth?.expiresAt);
297
+ if (expiresAtMs != null && expiresAtMs <= nowMs + CLAUDE_TOKEN_EXPIRY_SKEW_MS) return null;
298
+ return { accessToken, expiresAtMs };
299
+ }
300
+
301
+ function extractClaudeKeychainSubscription(payload) {
302
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
303
+
304
+ const oauth = payload.claudeAiOauth;
305
+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return null;
306
+
307
+ const subscriptionType = normalizeScalarToString(oauth.subscriptionType);
308
+ const rateLimitTier = normalizeScalarToString(oauth.rateLimitTier);
309
+
310
+ if (!subscriptionType) return null;
311
+ return { subscriptionType, rateLimitTier };
312
+ }
313
+
314
+ function detectClaudeCodeSubscriptionDetails({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
315
+ const rawPayloads = [];
316
+ if (platform === "darwin") {
317
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
318
+ const raw = readMacosKeychainPassword({ service, securityRunner, env });
319
+ if (raw) rawPayloads.push(raw);
320
+ }
321
+ } else if (usesClaudeCodeCredentialsFile(platform)) {
322
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
323
+ if (raw) rawPayloads.push(raw);
324
+ } else {
325
+ return null;
326
+ }
327
+
328
+ for (const raw of rawPayloads) {
329
+ let payload;
330
+ try {
331
+ payload = JSON.parse(raw);
332
+ } catch (_e) {
333
+ continue;
334
+ }
335
+
336
+ const info = extractClaudeKeychainSubscription(payload);
337
+ if (!info) continue;
338
+
339
+ return {
340
+ tool: "claude",
341
+ provider: "anthropic",
342
+ product: "subscription",
343
+ planType: info.subscriptionType,
344
+ rateLimitTier: info.rateLimitTier,
345
+ };
346
+ }
347
+
348
+ return null;
349
+ }
350
+
351
+ async function collectLocalSubscriptions({
352
+ home = os.homedir(),
353
+ env = process.env,
354
+ platform = process.platform,
355
+ securityRunner,
356
+ probeKeychain = false,
357
+ probeKeychainDetails = false,
358
+ } = {}) {
359
+ const out = [];
360
+
361
+ const codex = await detectCodexChatgptSubscription({ home, env });
362
+ if (codex) out.push(codex);
363
+
364
+ const opencode = await detectOpencodeChatgptSubscription({ home, env });
365
+ if (opencode) out.push(opencode);
366
+
367
+ if (probeKeychainDetails) {
368
+ const claude = detectClaudeCodeSubscriptionDetails({ platform, securityRunner, home, env });
369
+ if (claude) out.push(claude);
370
+ else if (probeKeychain) {
371
+ const present = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
372
+ if (present) out.push(present);
373
+ }
374
+ } else if (probeKeychain) {
375
+ const claude = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
376
+ if (claude) out.push(claude);
377
+ }
378
+
379
+ const openclaw = await detectOpenclawSessionIntegration({ home, env });
380
+ if (openclaw) out.push(openclaw);
381
+
382
+ // Gemini: no stable local subscription/tier signal found yet.
383
+ return out;
384
+ }
385
+
386
+ async function detectOpenclawSessionIntegration({ home, env }) {
387
+ const { trackerDir } = await resolveTrackerPaths({ home });
388
+ let state = null;
389
+ try {
390
+ state = await probeOpenclawSessionPluginState({ home, trackerDir, env });
391
+ } catch (_err) {
392
+ return null;
393
+ }
394
+
395
+ if (!state?.configured) return null;
396
+
397
+ return {
398
+ tool: "openclaw",
399
+ provider: "openclaw",
400
+ product: "session_plugin",
401
+ planType: "enabled",
402
+ };
403
+ }
404
+
405
+ // Returns the live OAuth token plus its expiry stamp. The expiry doubles as a
406
+ // rotation marker for the 429 cool-down: it changes on every refresh and, unlike
407
+ // the token itself, is not a secret, so nothing derived from a credential has to
408
+ // be written to disk.
409
+ function readClaudeCodeOauthToken({
410
+ platform = process.platform,
411
+ securityRunner,
412
+ home,
413
+ fsReader,
414
+ env,
415
+ nowMs = Date.now(),
416
+ } = {}) {
417
+ if (platform === "darwin") {
418
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
419
+ try {
420
+ const raw = readMacosKeychainPassword({ service, securityRunner, env });
421
+ if (!raw) continue;
422
+ const oauth = extractClaudeCodeOauth(JSON.parse(raw), nowMs);
423
+ if (oauth) return oauth;
424
+ } catch (_e) {
425
+ continue;
426
+ }
427
+ }
428
+ return null;
429
+ }
430
+
431
+ if (!usesClaudeCodeCredentialsFile(platform)) return null;
432
+
433
+ // Linux/Windows: Claude Code stores the OAuth payload as a JSON file
434
+ // (mode 0600 on Linux; user-profile ACLs on Windows).
435
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
436
+ if (!raw) return null;
437
+ try {
438
+ return extractClaudeCodeOauth(JSON.parse(raw), nowMs);
439
+ } catch (_e) {
440
+ return null;
441
+ }
442
+ }
443
+
444
+ function readClaudeCodeAccessToken(options = {}) {
445
+ return readClaudeCodeOauthToken(options)?.accessToken ?? null;
446
+ }
447
+
448
+ async function readCodexAccessToken({ home, env } = {}) {
449
+ try {
450
+ const codexHome = resolveCodexHome({ home, env });
451
+ const authPath = path.join(codexHome, "auth.json");
452
+ const auth = await readJson(authPath);
453
+ return normalizeString(auth?.tokens?.access_token);
454
+ } catch (_e) {
455
+ return null;
456
+ }
457
+ }
458
+
459
+ // Returns the access token + ChatGPT account id + plan type + auth.json path so callers can
460
+ // also trigger a refresh if the tokens are stale (issue #52: stale tokens → wham 401 →
461
+ // "Fetch failed" error after ~7-8 days of not running `codex`).
462
+ async function readCodexAuthBundle({ home, env } = {}) {
463
+ try {
464
+ const codexHome = resolveCodexHome({ home, env });
465
+ const authPath = path.join(codexHome, "auth.json");
466
+ const auth = await readJson(authPath);
467
+ if (!auth || typeof auth !== "object") return null;
468
+
469
+ const accessToken = normalizeString(auth?.tokens?.access_token);
470
+ if (!accessToken) return null;
471
+
472
+ const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
473
+ const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
474
+ const accountId =
475
+ normalizeString(auth?.tokens?.account_id) ||
476
+ normalizeString(extractOpenAiAuthNamespace(accessPayload)?.chatgpt_account_id) ||
477
+ normalizeString(extractOpenAiAuthNamespace(idPayload)?.chatgpt_account_id) ||
478
+ null;
479
+
480
+ const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
481
+ const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
482
+ const merged = mergeSubscription(accessInfo, idInfo);
483
+ const planType = merged?.planType ? merged.planType.toLowerCase() : null;
484
+
485
+ return {
486
+ accessToken,
487
+ accountId,
488
+ planType,
489
+ refreshToken: normalizeString(auth?.tokens?.refresh_token) || null,
490
+ lastRefresh: normalizeString(auth?.last_refresh) || null,
491
+ authPath,
492
+ authJson: auth,
493
+ };
494
+ } catch (_e) {
495
+ return null;
496
+ }
497
+ }
498
+
499
+ module.exports = {
500
+ resolveClaudeKeychainAccount,
501
+ collectLocalSubscriptions,
502
+ detectClaudeCodeCredentialsPresence,
503
+ detectClaudeCodeSubscriptionDetails,
504
+ readClaudeCodeAccessToken,
505
+ readClaudeCodeOauthToken,
506
+ readCodexAccessToken,
507
+ readCodexAuthBundle,
508
+ };
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Anonymous daily heartbeat for counting active installs.
5
+ *
6
+ * Privacy contract (documented in README "Privacy" section — keep in sync):
7
+ * the payload carries exactly four fields — a one-way sha256 hash of the
8
+ * machine id, the app version, `process.platform`, and the app shell
9
+ * (cli / macos / windows / linux). No token counts, no model names, no usernames,
10
+ * no paths. Opt out with TOKENUSAGE_NO_TELEMETRY=1, the DO_NOT_TRACK
11
+ * standard, or `"telemetry": false` in config.json.
12
+ */
13
+
14
+ const path = require("node:path");
15
+ const crypto = require("node:crypto");
16
+
17
+ const pkg = require("../../package.json");
18
+ const { readJson, writeJson } = require("./fs");
19
+ const { getOrCreateMachineId } = require("./machine-id");
20
+ const { resolveRuntimeConfig } = require("./runtime-config");
21
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
22
+ const {
23
+ decideAutoUpload,
24
+ recordUploadSuccess,
25
+ recordUploadFailure,
26
+ } = require("./upload-throttle");
27
+
28
+ const HEARTBEAT_FUNCTION_SLUG = "tokenusage-telemetry";
29
+ const HEARTBEAT_STATE_FILE = "telemetry.heartbeat.json";
30
+ const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
+ // The hash namespace is versioned so the anonymous id can be rotated fleet-wide
32
+ // by bumping the string. sha256(namespace + machineId) cannot be joined back to
33
+ // the cloud device rows (those store the machineId itself).
34
+ const MACHINE_HASH_NAMESPACE = "tokenusage-telemetry-v1:";
35
+ // Generous because some networks need 3-4s just for the TLS handshake to the
36
+ // cloud host; sync awaits this at most once per day so the worst-case stall
37
+ // is bounded and rare.
38
+ const DEFAULT_TIMEOUT_MS = 10_000;
39
+ const VALID_SHELLS = new Set(["cli", "macos", "windows", "linux"]);
40
+
41
+ const THROTTLE_CONFIG = {
42
+ intervalMs: HEARTBEAT_INTERVAL_MS,
43
+ jitterMsMax: 60_000,
44
+ backoffInitialMs: 60 * 60_000, // failures retry hourly at most
45
+ backoffMaxMs: HEARTBEAT_INTERVAL_MS,
46
+ };
47
+
48
+ function isTelemetryDisabled({ env = process.env, config = {} } = {}) {
49
+ if (isTruthyFlag(env?.TOKENUSAGE_NO_TELEMETRY)) return true;
50
+ if (isTruthyFlag(env?.DO_NOT_TRACK)) return true;
51
+ if (config && config.telemetry === false) return true;
52
+ return false;
53
+ }
54
+
55
+ function isTruthyFlag(value) {
56
+ if (typeof value !== "string") return false;
57
+ const v = value.trim().toLowerCase();
58
+ return v === "1" || v === "true";
59
+ }
60
+
61
+ function hashMachineId(machineId) {
62
+ return crypto
63
+ .createHash("sha256")
64
+ .update(`${MACHINE_HASH_NAMESPACE}${machineId}`)
65
+ .digest("hex");
66
+ }
67
+
68
+ function resolveShell(env = process.env) {
69
+ const raw = typeof env?.TOKENUSAGE_APP_SHELL === "string"
70
+ ? env.TOKENUSAGE_APP_SHELL.trim().toLowerCase()
71
+ : "";
72
+ return VALID_SHELLS.has(raw) ? raw : "cli";
73
+ }
74
+
75
+ function buildHeartbeatPayload({ machineId, version = pkg.version, platform = process.platform, env = process.env }) {
76
+ return {
77
+ machine_hash: hashMachineId(machineId),
78
+ app_version: String(version || "").slice(0, 32),
79
+ platform: String(platform || "unknown").slice(0, 16),
80
+ shell: resolveShell(env),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Send the daily heartbeat if allowed. Never throws; every failure path is a
86
+ * silent no-op so serve/sync flow is never affected. Returns a small status
87
+ * object for tests and debug logging.
88
+ */
89
+ async function maybeSendHeartbeat({
90
+ trackerDir,
91
+ fetchImpl = fetch,
92
+ nowMs = Date.now(),
93
+ env = process.env,
94
+ timeoutMs = DEFAULT_TIMEOUT_MS,
95
+ version,
96
+ } = {}) {
97
+ try {
98
+ if (!trackerDir) return { sent: false, reason: "no-tracker-dir" };
99
+
100
+ // Never phone home from the node test runner: many tests drive cmdSync /
101
+ // cmdServe directly from sandboxed temp homes, and their fresh throttle
102
+ // state would let a real POST through to production on every run. Tests
103
+ // that exercise this module inject their own env without this marker.
104
+ if (env?.NODE_TEST_CONTEXT !== undefined) {
105
+ return { sent: false, reason: "test-env" };
106
+ }
107
+
108
+ const configPath = path.join(trackerDir, "config.json");
109
+ const config = (await readJson(configPath)) || {};
110
+ if (isTelemetryDisabled({ env, config })) {
111
+ return { sent: false, reason: "opt-out" };
112
+ }
113
+
114
+ const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
115
+ const state = await readJson(statePath);
116
+ const decision = decideAutoUpload({
117
+ nowMs,
118
+ pendingBytes: 1, // heartbeats always have "one ping pending"
119
+ state,
120
+ config: THROTTLE_CONFIG,
121
+ });
122
+ if (!decision.allowed) {
123
+ return { sent: false, reason: "throttled", blockedUntilMs: decision.blockedUntilMs };
124
+ }
125
+
126
+ const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
127
+ if (!machineId) return { sent: false, reason: "no-machine-id" };
128
+
129
+ const runtime = resolveRuntimeConfig({ config, env });
130
+ const payload = buildHeartbeatPayload({ machineId, version, env });
131
+
132
+ const controller = new AbortController();
133
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
134
+ let response;
135
+ try {
136
+ response = await fetchFunctionResponse(functionUrlFor(runtime.baseUrl, HEARTBEAT_FUNCTION_SLUG), {
137
+ method: "POST",
138
+ headers: {
139
+ "Content-Type": "application/json",
140
+ apikey: runtime.anonKey,
141
+ },
142
+ body: JSON.stringify(payload),
143
+ signal: controller.signal,
144
+ }, fetchImpl);
145
+ } finally {
146
+ clearTimeout(timer);
147
+ }
148
+
149
+ if (!response || !response.ok) {
150
+ const failedState = recordUploadFailure({
151
+ nowMs,
152
+ state,
153
+ error: { message: `heartbeat http ${response?.status || "error"}`, status: response?.status },
154
+ config: THROTTLE_CONFIG,
155
+ });
156
+ await writeJson(statePath, failedState);
157
+ return { sent: false, reason: "http-error", status: response?.status };
158
+ }
159
+
160
+ const nextState = recordUploadSuccess({ nowMs, state, config: THROTTLE_CONFIG });
161
+ await writeJson(statePath, nextState);
162
+ return { sent: true, reason: "sent" };
163
+ } catch (e) {
164
+ // Includes abort/network errors: record backoff if we can, stay silent.
165
+ try {
166
+ const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
167
+ const state = await readJson(statePath);
168
+ await writeJson(
169
+ statePath,
170
+ recordUploadFailure({
171
+ nowMs,
172
+ state,
173
+ error: { message: String(e?.message || e) },
174
+ config: THROTTLE_CONFIG,
175
+ }),
176
+ );
177
+ } catch {
178
+ // Even state persistence failed — nothing else to do.
179
+ }
180
+ return { sent: false, reason: "error" };
181
+ }
182
+ }
183
+
184
+ module.exports = {
185
+ HEARTBEAT_FUNCTION_SLUG,
186
+ HEARTBEAT_STATE_FILE,
187
+ HEARTBEAT_INTERVAL_MS,
188
+ isTelemetryDisabled,
189
+ hashMachineId,
190
+ resolveShell,
191
+ buildHeartbeatPayload,
192
+ maybeSendHeartbeat,
193
+ };