tokenusage-cli 0.1.0 → 0.2.1

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 (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,541 +1,541 @@
1
- "use strict";
2
-
3
- // Account-aggregated (cross-device) cloud reads for the local server.
4
- //
5
- // The native menu-bar / tray popover talks only to the local CLI server and
6
- // knows nothing about OAuth/JWT. To make the popover show the SAME cross-device
7
- // totals the dashboard shows in "account view", the local server mints a
8
- // short-lived access token from the InsForge refresh token it already relays
9
- // (see local-api.js cookie relay) and proxies the `token-usage-account-*` edge
10
- // functions. Those functions mirror the local `token-usage-usage-*` response
11
- // schema exactly, so the popover renders the cloud payload unchanged.
12
-
13
- const { DEFAULT_BASE_URL, DEFAULT_ANON_KEY } = require("./runtime-config");
14
- const { expandHeatmapCompact } = require("./heatmap-compact");
15
- const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
16
-
17
- // usage-* (local CLI) → account-* (cloud) slug map. Only these have a
18
- // cross-device cloud equivalent; project-usage / usage-limits / category
19
- // breakdown remain local-only and are intentionally absent here.
20
- const USAGE_TO_ACCOUNT_SLUG = {
21
- "token-usage-usage-summary": "token-usage-account-summary",
22
- "token-usage-usage-daily": "token-usage-account-daily",
23
- "token-usage-usage-hourly": "token-usage-account-hourly",
24
- "token-usage-usage-monthly": "token-usage-account-monthly",
25
- "token-usage-usage-heatmap": "token-usage-account-heatmap",
26
- "token-usage-usage-model-breakdown": "token-usage-account-model-breakdown",
27
- };
28
-
29
- function accountSlugFor(usageSlug) {
30
- return USAGE_TO_ACCOUNT_SLUG[usageSlug] || null;
31
- }
32
-
33
- // The heatmap renders a 52-week grid out of a handful of active days, so the
34
- // dense form is mostly zero-filled cells and repeated keys: ~42 KB on the wire
35
- // for ~12 KB of data, and this proxy accounts for 94% of those reads. Asking
36
- // for the sparse rows and rebuilding the grid in `expandHeatmapCompact` gives
37
- // the caller a byte-identical payload. An edge that predates the compact branch
38
- // ignores the param and answers densely, which that helper passes through.
39
- const HEATMAP_ACCOUNT_SLUG = "token-usage-account-heatmap";
40
-
41
- // Mirror of dashboard/src/contexts/InsforgeAuthContext.jsx
42
- // `accessTokenFromRefreshPayload`: the refresh response may put the token at the
43
- // top level or nested under `session`, in camelCase or snake_case.
44
- function accessTokenFromRefreshPayload(data) {
45
- if (!data || typeof data !== "object") return null;
46
- const session = data.session && typeof data.session === "object" ? data.session : null;
47
- const raw =
48
- (typeof data.accessToken === "string" && data.accessToken) ||
49
- (typeof data.access_token === "string" && data.access_token) ||
50
- (session && typeof session.accessToken === "string" && session.accessToken) ||
51
- (session && typeof session.access_token === "string" && session.access_token) ||
52
- null;
53
- return raw && raw.length > 0 ? raw : null;
54
- }
55
-
56
- function refreshTokenFromRefreshPayload(data) {
57
- if (!data || typeof data !== "object") return null;
58
- const session = data.session && typeof data.session === "object" ? data.session : null;
59
- const raw =
60
- (typeof data.refreshToken === "string" && data.refreshToken) ||
61
- (typeof data.refresh_token === "string" && data.refresh_token) ||
62
- (session && typeof session.refreshToken === "string" && session.refreshToken) ||
63
- (session && typeof session.refresh_token === "string" && session.refresh_token) ||
64
- null;
65
- return raw && raw.length > 0 ? raw : null;
66
- }
67
-
68
- function decodeJwtExpMs(token) {
69
- try {
70
- const part = String(token || "").split(".")[1];
71
- if (!part) return 0;
72
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
73
- const payload = JSON.parse(json);
74
- if (payload && Number.isFinite(payload.exp)) return payload.exp * 1000;
75
- } catch {
76
- /* ignore */
77
- }
78
- return 0;
79
- }
80
-
81
- // The account id the access token was minted for. Used to key the payload cache
82
- // below on something the backend does NOT rotate: the refresh token changes
83
- // under us on rotation, which would throw away a still-warm cache entry on
84
- // exactly the reads that repeat most.
85
- function decodeJwtSub(token) {
86
- try {
87
- const part = String(token || "").split(".")[1];
88
- if (!part) return "";
89
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
90
- const payload = JSON.parse(json);
91
- if (payload && typeof payload.sub === "string") return payload.sub;
92
- } catch {
93
- /* ignore */
94
- }
95
- return "";
96
- }
97
-
98
- // Module-level access-token cache, keyed by the cloud base URL and refresh token
99
- // that produced it.
100
- // The popover polls frequently, so caching avoids hammering /api/auth/refresh.
101
- let tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
102
-
103
- // In-flight refresh de-duplication ("single flight"), keyed the same way as
104
- // `tokenCache`. A full popover refresh fires six account reads concurrently; on
105
- // a cold cache every one of them used to POST /api/auth/refresh with the SAME
106
- // refresh token. When the backend rotates refresh tokens, the losers of that
107
- // race present an already-consumed token and fail — which is exactly the
108
- // intermittent "Activity silently dropped to this-machine data" symptom.
109
- const mintInflight = new Map();
110
-
111
- // Ordinary cross-device reads may lag by two minutes for summaries and five
112
- // minutes for charts. Uploads and explicit refreshes invalidate this window.
113
- // Serialized copies prevent consumers from changing another consumer's data.
114
- const SUMMARY_PAYLOAD_TTL_MS = 120_000;
115
- const PAYLOAD_TTL_MS = 300_000;
116
- const PAYLOAD_CACHE_MAX = 64;
117
- const payloadCache = new Map();
118
- const payloadInflight = new Map();
119
- const payloadVersions = new Map();
120
- let payloadGeneration = 0;
121
- let sessionGeneration = 0;
122
-
123
- // Mirrors the params `fetchAccountFunction` actually puts on the wire, so two
124
- // requests share an entry only when they would have produced the same URL.
125
- function payloadCacheKey({ root, sub, slug, searchParams }) {
126
- const params = accountFunctionParams(slug, searchParams);
127
- params.sort();
128
- return `${root}\0${sub}\0${slug}\0${params}`;
129
- }
130
-
131
- function accountFunctionParams(slug, searchParams) {
132
- const params = new URLSearchParams();
133
- if (searchParams && typeof searchParams.entries === "function") {
134
- for (const [key, value] of searchParams.entries()) {
135
- if (key === "account" || key === "scope" || key === "refresh") continue;
136
- if (value == null || value === "") continue;
137
- params.set(key, String(value));
138
- }
139
- }
140
- if (slug === HEATMAP_ACCOUNT_SLUG) params.set("format", "compact");
141
- return params;
142
- }
143
-
144
- function payloadCacheGet(key, now) {
145
- const hit = payloadCache.get(key);
146
- if (!hit) return null;
147
- if (hit.expMs <= now()) {
148
- payloadCache.delete(key);
149
- return null;
150
- }
151
- // Re-insert so the eviction below drops the coldest entry, not this one.
152
- payloadCache.delete(key);
153
- payloadCache.set(key, hit);
154
- try {
155
- return JSON.parse(hit.body);
156
- } catch {
157
- payloadCache.delete(key);
158
- return null;
159
- }
160
- }
161
-
162
- function payloadCacheSet(key, data, now, ttlMs) {
163
- let body;
164
- try {
165
- body = JSON.stringify(data);
166
- } catch {
167
- return; // Not serializable: skip the cache rather than fail the read.
168
- }
169
- if (body === undefined) return;
170
- payloadCache.set(key, { expMs: now() + ttlMs, body });
171
- while (payloadCache.size > PAYLOAD_CACHE_MAX) {
172
- const oldest = payloadCache.keys().next();
173
- if (oldest.done) break;
174
- payloadCache.delete(oldest.value);
175
- }
176
- }
177
-
178
- function invalidateCloudAccountPayloadCache({ sessionChanged = false } = {}) {
179
- if (sessionChanged) {
180
- sessionGeneration += 1;
181
- tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
182
- mintInflight.clear();
183
- }
184
- payloadGeneration += 1;
185
- payloadCache.clear();
186
- payloadInflight.clear();
187
- payloadVersions.clear();
188
- }
189
-
190
- function getCloudAccountSessionGeneration() {
191
- return sessionGeneration;
192
- }
193
-
194
- function __resetCloudAccountCacheForTests() {
195
- tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
196
- mintInflight.clear();
197
- invalidateCloudAccountPayloadCache({ sessionChanged: true });
198
- }
199
-
200
- // Failure classes surfaced to local-api so it can tell an intentional local
201
- // view ("signed out", "cloud sync off") apart from a temporary cloud outage.
202
- class AccountAuthError extends Error {
203
- constructor(code, message) {
204
- super(message || code);
205
- this.name = "AccountAuthError";
206
- this.code = code;
207
- }
208
- }
209
-
210
- function csrfTokenFromRefreshPayload(data) {
211
- if (!data || typeof data !== "object") return null;
212
- const raw =
213
- (typeof data.csrfToken === "string" && data.csrfToken) ||
214
- (typeof data.csrf_token === "string" && data.csrf_token) ||
215
- null;
216
- return raw && raw.length > 0 ? raw : null;
217
- }
218
-
219
- /**
220
- * Perform the actual refresh POST. Throws a classified `AccountAuthError` on
221
- * every failure so callers can distinguish a transient outage (timeout,
222
- * offline, rotated-token rejection) from an intentionally local view.
223
- */
224
- async function performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs }) {
225
- const mintSessionGeneration = sessionGeneration;
226
- const headers = { "Content-Type": "application/json", Accept: "application/json" };
227
- if (anonKey) headers.apikey = anonKey;
228
-
229
- let timeoutId;
230
- const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
231
- const signal = controller ? controller.signal : undefined;
232
-
233
- if (controller && timeoutMs && timeoutMs > 0) {
234
- timeoutId = setTimeout(() => {
235
- controller.abort();
236
- }, timeoutMs);
237
- }
238
-
239
- let res;
240
- try {
241
- res = await fetchImpl(`${root}/api/auth/refresh?client_type=mobile`, {
242
- method: "POST",
243
- headers,
244
- body: JSON.stringify({ refresh_token: refreshToken }),
245
- signal,
246
- });
247
- } catch (e) {
248
- const aborted = e && (e.name === "AbortError" || e.name === "TimeoutError");
249
- throw new AccountAuthError(
250
- aborted ? "auth_timeout" : "auth_network",
251
- e?.message || "token refresh failed",
252
- );
253
- } finally {
254
- if (timeoutId) {
255
- clearTimeout(timeoutId);
256
- }
257
- }
258
- if (!res || !res.ok) {
259
- const err = new AccountAuthError(
260
- "auth_rejected",
261
- `token refresh failed with HTTP ${res ? res.status : "?"}`,
262
- );
263
- err.status = res ? res.status : 0;
264
- throw err;
265
- }
266
-
267
- let data = null;
268
- try {
269
- data = await res.json();
270
- } catch (e) {
271
- throw new AccountAuthError("auth_invalid", e?.message || "token refresh returned invalid JSON");
272
- }
273
-
274
- const accessToken = accessTokenFromRefreshPayload(data);
275
- if (!accessToken) {
276
- throw new AccountAuthError("auth_invalid", "token refresh returned no access token");
277
- }
278
-
279
- const expMs = decodeJwtExpMs(accessToken) || now() + 10 * 60_000;
280
- if (mintSessionGeneration !== sessionGeneration) {
281
- throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
282
- }
283
- const rotated = refreshTokenFromRefreshPayload(data);
284
- // The caller persists a rotation before its next account read. Key the
285
- // still-valid access token by that current refresh token, not the consumed one.
286
- tokenCache = { cacheKey: `${root}\0${rotated || refreshToken}`, accessToken, expMs };
287
- return {
288
- accessToken,
289
- refreshToken: rotated && rotated !== refreshToken ? rotated : null,
290
- // Rotating the refresh token can invalidate the csrf token paired with the
291
- // previous session state. Surface the fresh one so the caller can keep the
292
- // relayed (refresh, csrf) pair in sync — a stale relayed csrf breaks the
293
- // dashboard's cookie-path refresh with 403 Invalid CSRF.
294
- csrfToken: csrfTokenFromRefreshPayload(data),
295
- };
296
- }
297
-
298
- /**
299
- * Mint (or reuse a cached) InsForge access token from a refresh token.
300
- *
301
- * Concurrent callers with the same (baseUrl, refreshToken) share ONE in-flight
302
- * refresh; see `mintInflight`.
303
- *
304
- * @param {boolean} [throwOnFailure] when true, reject with a classified
305
- * `AccountAuthError` instead of resolving to `null`.
306
- * @returns {Promise<{accessToken: string, refreshToken: string|null, csrfToken: string|null}|null>}
307
- * null when no refresh token is available or the refresh failed.
308
- */
309
- async function mintAccessToken({
310
- baseUrl,
311
- anonKey,
312
- refreshToken,
313
- fetchImpl = fetch,
314
- now = Date.now,
315
- skewMs = 60_000,
316
- timeoutMs,
317
- throwOnFailure = false,
318
- } = {}) {
319
- if (!refreshToken) {
320
- if (throwOnFailure) throw new AccountAuthError("auth_missing_refresh_token", "not signed in");
321
- return null;
322
- }
323
- const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
324
- const cacheKey = `${root}\0${refreshToken}`;
325
- if (
326
- tokenCache.cacheKey === cacheKey &&
327
- tokenCache.accessToken &&
328
- tokenCache.expMs - skewMs > now()
329
- ) {
330
- return { accessToken: tokenCache.accessToken, refreshToken: null, csrfToken: null };
331
- }
332
-
333
- let inflight = mintInflight.get(cacheKey);
334
- if (!inflight) {
335
- inflight = performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs })
336
- .finally(() => {
337
- // Only clear our own entry: a later caller may already have started a
338
- // fresh mint after this one settled.
339
- if (mintInflight.get(cacheKey) === inflight) mintInflight.delete(cacheKey);
340
- });
341
- mintInflight.set(cacheKey, inflight);
342
- }
343
-
344
- try {
345
- return await inflight;
346
- } catch (e) {
347
- if (throwOnFailure) throw e;
348
- return null;
349
- }
350
- }
351
-
352
- /**
353
- * GET a `token-usage-account-*` edge function, forwarding the popover's query
354
- * params (minus `account`/`scope`, which are local-only routing knobs).
355
- */
356
- async function fetchAccountFunction({
357
- baseUrl,
358
- anonKey,
359
- accessToken,
360
- slug,
361
- searchParams,
362
- fetchImpl = fetch,
363
- timeoutMs,
364
- } = {}) {
365
- const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
366
- const url = new URL(functionUrlFor(root, slug));
367
- url.search = accountFunctionParams(slug, searchParams).toString();
368
- const headers = { Accept: "application/json", Authorization: `Bearer ${accessToken}` };
369
- if (anonKey) headers.apikey = anonKey;
370
-
371
- let timeoutId;
372
- const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
373
- const signal = controller ? controller.signal : undefined;
374
-
375
- if (controller && timeoutMs && timeoutMs > 0) {
376
- timeoutId = setTimeout(() => {
377
- controller.abort();
378
- }, timeoutMs);
379
- }
380
-
381
- try {
382
- const res = await fetchFunctionResponse(url.toString(), { method: "GET", headers, signal }, fetchImpl);
383
- if (!res || !res.ok) {
384
- const err = new Error(`Account fetch failed with HTTP ${res ? res.status : "?"}`);
385
- err.status = res ? res.status : 0;
386
- const failure = res?.json ? await res.json().catch(() => ({})) : {};
387
- if (typeof failure?.code === "string") err.code = failure.code;
388
- if (typeof failure?.recovery_url === "string") err.recoveryUrl = failure.recovery_url;
389
- throw err;
390
- }
391
- const data = await res.json();
392
- return slug === HEATMAP_ACCOUNT_SLUG ? expandHeatmapCompact(data) : data;
393
- } finally {
394
- if (timeoutId) {
395
- clearTimeout(timeoutId);
396
- }
397
- }
398
- }
399
-
400
- /**
401
- * High-level helper used by local-api: mint a token from `refreshToken`, then
402
- * fetch the cross-device aggregate matching `usageSlug`.
403
- *
404
- * @returns {Promise<{data: any, rotatedRefreshToken: string|null, rotatedCsrfToken: string|null}|null>}
405
- * null when there is no cloud equivalent, no refresh token, or the refresh
406
- * failed. Throws only when the account endpoint itself errors (so callers can
407
- * distinguish "not signed in" from "cloud request failed").
408
- */
409
- async function fetchAccountUsage({
410
- usageSlug,
411
- searchParams,
412
- baseUrl = DEFAULT_BASE_URL,
413
- anonKey = DEFAULT_ANON_KEY,
414
- refreshToken,
415
- fetchImpl = fetch,
416
- now = Date.now,
417
- timeoutMs,
418
- onSessionRefreshed,
419
- } = {}) {
420
- const slug = accountSlugFor(usageSlug);
421
- if (!slug) return null;
422
- if (!refreshToken) return null;
423
-
424
- const sessionAtStart = sessionGeneration;
425
- const startTime = now();
426
- const getRemainingTimeout = () => {
427
- if (!timeoutMs) return undefined;
428
- const elapsed = now() - startTime;
429
- const remaining = timeoutMs - elapsed;
430
- return remaining > 0 ? remaining : 1;
431
- };
432
-
433
- // `throwOnFailure` keeps "not signed in" (null, handled above) distinct from
434
- // "signed in but the refresh call failed" (throws) so the caller does not
435
- // silently downgrade an account view into a this-machine view.
436
- const minted = await mintAccessToken({
437
- baseUrl,
438
- anonKey,
439
- refreshToken,
440
- fetchImpl,
441
- now,
442
- timeoutMs: getRemainingTimeout(),
443
- throwOnFailure: true,
444
- });
445
- if (!minted) return null;
446
- if (sessionAtStart !== sessionGeneration) {
447
- throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
448
- }
449
-
450
- // The refresh already consumed the old credential. Persist its replacement
451
- // before an edge read can wait, fail, or overlap a different account query.
452
- if (typeof onSessionRefreshed === "function" && (minted.refreshToken || minted.csrfToken)) {
453
- await onSessionRefreshed({ refreshToken: minted.refreshToken, csrfToken: minted.csrfToken });
454
- if (sessionAtStart !== sessionGeneration) {
455
- throw new AccountAuthError("auth_session_changed", "account session changed during token persistence");
456
- }
457
- }
458
-
459
- // Keyed after the mint so rotation cannot invalidate the entry, and so a
460
- // revoked session fails here rather than being served from cache.
461
- const sub = decodeJwtSub(minted.accessToken);
462
- const cacheKey = sub
463
- ? payloadCacheKey({ root: String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, ""), sub, slug, searchParams })
464
- : null;
465
- const force = searchParams?.get("refresh") === "1";
466
- if (cacheKey && !force) {
467
- const cached = payloadCacheGet(cacheKey, now);
468
- if (cached !== null) {
469
- // Still surface a rotation from this mint: dropping it would leave the
470
- // caller relaying a refresh token the backend has already consumed.
471
- return {
472
- data: cached,
473
- rotatedRefreshToken: minted.refreshToken,
474
- rotatedCsrfToken: minted.csrfToken,
475
- };
476
- }
477
- }
478
-
479
- const flightKey = cacheKey ? `${cacheKey}\0${payloadGeneration}\0${force ? "refresh" : `normal:${payloadVersions.get(cacheKey) || 0}`}` : null;
480
- let pending = flightKey && payloadInflight.get(flightKey);
481
- if (!pending) {
482
- // A forced read supersedes an older ordinary read of the same account.
483
- // Keep concurrent forced consumers together without sharing its old flight.
484
- if (force && cacheKey) {
485
- payloadCache.delete(cacheKey);
486
- payloadVersions.set(cacheKey, (payloadVersions.get(cacheKey) || 0) + 1);
487
- }
488
- const generation = payloadGeneration;
489
- const version = payloadVersions.get(cacheKey) || 0;
490
- pending = (async () => {
491
- try {
492
- const data = await fetchAccountFunction({
493
- baseUrl, anonKey, accessToken: minted.accessToken, slug, searchParams,
494
- fetchImpl, timeoutMs: getRemainingTimeout(),
495
- });
496
- if (generation === payloadGeneration && version === (payloadVersions.get(cacheKey) || 0) && cacheKey && data != null) {
497
- payloadCacheSet(cacheKey, data, now, slug === "token-usage-account-summary" ? SUMMARY_PAYLOAD_TTL_MS : PAYLOAD_TTL_MS);
498
- }
499
- return JSON.stringify(data);
500
- } catch (error) {
501
- if (error.status === 401 && sessionAtStart === sessionGeneration) {
502
- invalidateCloudAccountPayloadCache({ sessionChanged: true });
503
- error.invalidatedSessionGeneration = sessionGeneration;
504
- }
505
- throw error;
506
- }
507
- })();
508
- if (flightKey) {
509
- payloadInflight.set(flightKey, pending);
510
- const cleanup = () => {
511
- if (payloadInflight.get(flightKey) === pending) payloadInflight.delete(flightKey);
512
- };
513
- pending.then(cleanup, cleanup);
514
- }
515
- }
516
- const body = await pending;
517
- if (sessionAtStart !== sessionGeneration) {
518
- throw new AccountAuthError("auth_session_changed", "account session changed during account read");
519
- }
520
- const data = body === undefined ? undefined : JSON.parse(body);
521
- return { data, rotatedRefreshToken: minted.refreshToken, rotatedCsrfToken: minted.csrfToken };
522
- }
523
-
524
- module.exports = {
525
- AccountAuthError,
526
- USAGE_TO_ACCOUNT_SLUG,
527
- PAYLOAD_TTL_MS,
528
- SUMMARY_PAYLOAD_TTL_MS,
529
- invalidateCloudAccountPayloadCache,
530
- getCloudAccountSessionGeneration,
531
- HEATMAP_ACCOUNT_SLUG,
532
- accountSlugFor,
533
- accessTokenFromRefreshPayload,
534
- refreshTokenFromRefreshPayload,
535
- decodeJwtExpMs,
536
- decodeJwtSub,
537
- mintAccessToken,
538
- fetchAccountFunction,
539
- fetchAccountUsage,
540
- __resetCloudAccountCacheForTests,
541
- };
1
+ "use strict";
2
+
3
+ // Account-aggregated (cross-device) cloud reads for the local server.
4
+ //
5
+ // The native menu-bar / tray popover talks only to the local CLI server and
6
+ // knows nothing about OAuth/JWT. To make the popover show the SAME cross-device
7
+ // totals the dashboard shows in "account view", the local server mints a
8
+ // short-lived access token from the InsForge refresh token it already relays
9
+ // (see local-api.js cookie relay) and proxies the `token-usage-account-*` edge
10
+ // functions. Those functions mirror the local `token-usage-usage-*` response
11
+ // schema exactly, so the popover renders the cloud payload unchanged.
12
+
13
+ const { DEFAULT_BASE_URL, DEFAULT_ANON_KEY } = require("./runtime-config");
14
+ const { expandHeatmapCompact } = require("./heatmap-compact");
15
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
16
+
17
+ // usage-* (local CLI) → account-* (cloud) slug map. Only these have a
18
+ // cross-device cloud equivalent; project-usage / usage-limits / category
19
+ // breakdown remain local-only and are intentionally absent here.
20
+ const USAGE_TO_ACCOUNT_SLUG = {
21
+ "token-usage-usage-summary": "token-usage-account-summary",
22
+ "token-usage-usage-daily": "token-usage-account-daily",
23
+ "token-usage-usage-hourly": "token-usage-account-hourly",
24
+ "token-usage-usage-monthly": "token-usage-account-monthly",
25
+ "token-usage-usage-heatmap": "token-usage-account-heatmap",
26
+ "token-usage-usage-model-breakdown": "token-usage-account-model-breakdown",
27
+ };
28
+
29
+ function accountSlugFor(usageSlug) {
30
+ return USAGE_TO_ACCOUNT_SLUG[usageSlug] || null;
31
+ }
32
+
33
+ // The heatmap renders a 52-week grid out of a handful of active days, so the
34
+ // dense form is mostly zero-filled cells and repeated keys: ~42 KB on the wire
35
+ // for ~12 KB of data, and this proxy accounts for 94% of those reads. Asking
36
+ // for the sparse rows and rebuilding the grid in `expandHeatmapCompact` gives
37
+ // the caller a byte-identical payload. An edge that predates the compact branch
38
+ // ignores the param and answers densely, which that helper passes through.
39
+ const HEATMAP_ACCOUNT_SLUG = "token-usage-account-heatmap";
40
+
41
+ // Mirror of dashboard/src/contexts/InsforgeAuthContext.jsx
42
+ // `accessTokenFromRefreshPayload`: the refresh response may put the token at the
43
+ // top level or nested under `session`, in camelCase or snake_case.
44
+ function accessTokenFromRefreshPayload(data) {
45
+ if (!data || typeof data !== "object") return null;
46
+ const session = data.session && typeof data.session === "object" ? data.session : null;
47
+ const raw =
48
+ (typeof data.accessToken === "string" && data.accessToken) ||
49
+ (typeof data.access_token === "string" && data.access_token) ||
50
+ (session && typeof session.accessToken === "string" && session.accessToken) ||
51
+ (session && typeof session.access_token === "string" && session.access_token) ||
52
+ null;
53
+ return raw && raw.length > 0 ? raw : null;
54
+ }
55
+
56
+ function refreshTokenFromRefreshPayload(data) {
57
+ if (!data || typeof data !== "object") return null;
58
+ const session = data.session && typeof data.session === "object" ? data.session : null;
59
+ const raw =
60
+ (typeof data.refreshToken === "string" && data.refreshToken) ||
61
+ (typeof data.refresh_token === "string" && data.refresh_token) ||
62
+ (session && typeof session.refreshToken === "string" && session.refreshToken) ||
63
+ (session && typeof session.refresh_token === "string" && session.refresh_token) ||
64
+ null;
65
+ return raw && raw.length > 0 ? raw : null;
66
+ }
67
+
68
+ function decodeJwtExpMs(token) {
69
+ try {
70
+ const part = String(token || "").split(".")[1];
71
+ if (!part) return 0;
72
+ const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
73
+ const payload = JSON.parse(json);
74
+ if (payload && Number.isFinite(payload.exp)) return payload.exp * 1000;
75
+ } catch {
76
+ /* ignore */
77
+ }
78
+ return 0;
79
+ }
80
+
81
+ // The account id the access token was minted for. Used to key the payload cache
82
+ // below on something the backend does NOT rotate: the refresh token changes
83
+ // under us on rotation, which would throw away a still-warm cache entry on
84
+ // exactly the reads that repeat most.
85
+ function decodeJwtSub(token) {
86
+ try {
87
+ const part = String(token || "").split(".")[1];
88
+ if (!part) return "";
89
+ const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
90
+ const payload = JSON.parse(json);
91
+ if (payload && typeof payload.sub === "string") return payload.sub;
92
+ } catch {
93
+ /* ignore */
94
+ }
95
+ return "";
96
+ }
97
+
98
+ // Module-level access-token cache, keyed by the cloud base URL and refresh token
99
+ // that produced it.
100
+ // The popover polls frequently, so caching avoids hammering /api/auth/refresh.
101
+ let tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
102
+
103
+ // In-flight refresh de-duplication ("single flight"), keyed the same way as
104
+ // `tokenCache`. A full popover refresh fires six account reads concurrently; on
105
+ // a cold cache every one of them used to POST /api/auth/refresh with the SAME
106
+ // refresh token. When the backend rotates refresh tokens, the losers of that
107
+ // race present an already-consumed token and fail — which is exactly the
108
+ // intermittent "Activity silently dropped to this-machine data" symptom.
109
+ const mintInflight = new Map();
110
+
111
+ // Ordinary cross-device reads may lag by two minutes for summaries and five
112
+ // minutes for charts. Uploads and explicit refreshes invalidate this window.
113
+ // Serialized copies prevent consumers from changing another consumer's data.
114
+ const SUMMARY_PAYLOAD_TTL_MS = 120_000;
115
+ const PAYLOAD_TTL_MS = 300_000;
116
+ const PAYLOAD_CACHE_MAX = 64;
117
+ const payloadCache = new Map();
118
+ const payloadInflight = new Map();
119
+ const payloadVersions = new Map();
120
+ let payloadGeneration = 0;
121
+ let sessionGeneration = 0;
122
+
123
+ // Mirrors the params `fetchAccountFunction` actually puts on the wire, so two
124
+ // requests share an entry only when they would have produced the same URL.
125
+ function payloadCacheKey({ root, sub, slug, searchParams }) {
126
+ const params = accountFunctionParams(slug, searchParams);
127
+ params.sort();
128
+ return `${root}\0${sub}\0${slug}\0${params}`;
129
+ }
130
+
131
+ function accountFunctionParams(slug, searchParams) {
132
+ const params = new URLSearchParams();
133
+ if (searchParams && typeof searchParams.entries === "function") {
134
+ for (const [key, value] of searchParams.entries()) {
135
+ if (key === "account" || key === "scope" || key === "refresh") continue;
136
+ if (value == null || value === "") continue;
137
+ params.set(key, String(value));
138
+ }
139
+ }
140
+ if (slug === HEATMAP_ACCOUNT_SLUG) params.set("format", "compact");
141
+ return params;
142
+ }
143
+
144
+ function payloadCacheGet(key, now) {
145
+ const hit = payloadCache.get(key);
146
+ if (!hit) return null;
147
+ if (hit.expMs <= now()) {
148
+ payloadCache.delete(key);
149
+ return null;
150
+ }
151
+ // Re-insert so the eviction below drops the coldest entry, not this one.
152
+ payloadCache.delete(key);
153
+ payloadCache.set(key, hit);
154
+ try {
155
+ return JSON.parse(hit.body);
156
+ } catch {
157
+ payloadCache.delete(key);
158
+ return null;
159
+ }
160
+ }
161
+
162
+ function payloadCacheSet(key, data, now, ttlMs) {
163
+ let body;
164
+ try {
165
+ body = JSON.stringify(data);
166
+ } catch {
167
+ return; // Not serializable: skip the cache rather than fail the read.
168
+ }
169
+ if (body === undefined) return;
170
+ payloadCache.set(key, { expMs: now() + ttlMs, body });
171
+ while (payloadCache.size > PAYLOAD_CACHE_MAX) {
172
+ const oldest = payloadCache.keys().next();
173
+ if (oldest.done) break;
174
+ payloadCache.delete(oldest.value);
175
+ }
176
+ }
177
+
178
+ function invalidateCloudAccountPayloadCache({ sessionChanged = false } = {}) {
179
+ if (sessionChanged) {
180
+ sessionGeneration += 1;
181
+ tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
182
+ mintInflight.clear();
183
+ }
184
+ payloadGeneration += 1;
185
+ payloadCache.clear();
186
+ payloadInflight.clear();
187
+ payloadVersions.clear();
188
+ }
189
+
190
+ function getCloudAccountSessionGeneration() {
191
+ return sessionGeneration;
192
+ }
193
+
194
+ function __resetCloudAccountCacheForTests() {
195
+ tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
196
+ mintInflight.clear();
197
+ invalidateCloudAccountPayloadCache({ sessionChanged: true });
198
+ }
199
+
200
+ // Failure classes surfaced to local-api so it can tell an intentional local
201
+ // view ("signed out", "cloud sync off") apart from a temporary cloud outage.
202
+ class AccountAuthError extends Error {
203
+ constructor(code, message) {
204
+ super(message || code);
205
+ this.name = "AccountAuthError";
206
+ this.code = code;
207
+ }
208
+ }
209
+
210
+ function csrfTokenFromRefreshPayload(data) {
211
+ if (!data || typeof data !== "object") return null;
212
+ const raw =
213
+ (typeof data.csrfToken === "string" && data.csrfToken) ||
214
+ (typeof data.csrf_token === "string" && data.csrf_token) ||
215
+ null;
216
+ return raw && raw.length > 0 ? raw : null;
217
+ }
218
+
219
+ /**
220
+ * Perform the actual refresh POST. Throws a classified `AccountAuthError` on
221
+ * every failure so callers can distinguish a transient outage (timeout,
222
+ * offline, rotated-token rejection) from an intentionally local view.
223
+ */
224
+ async function performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs }) {
225
+ const mintSessionGeneration = sessionGeneration;
226
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
227
+ if (anonKey) headers.apikey = anonKey;
228
+
229
+ let timeoutId;
230
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
231
+ const signal = controller ? controller.signal : undefined;
232
+
233
+ if (controller && timeoutMs && timeoutMs > 0) {
234
+ timeoutId = setTimeout(() => {
235
+ controller.abort();
236
+ }, timeoutMs);
237
+ }
238
+
239
+ let res;
240
+ try {
241
+ res = await fetchImpl(`${root}/api/auth/refresh?client_type=mobile`, {
242
+ method: "POST",
243
+ headers,
244
+ body: JSON.stringify({ refresh_token: refreshToken }),
245
+ signal,
246
+ });
247
+ } catch (e) {
248
+ const aborted = e && (e.name === "AbortError" || e.name === "TimeoutError");
249
+ throw new AccountAuthError(
250
+ aborted ? "auth_timeout" : "auth_network",
251
+ e?.message || "token refresh failed",
252
+ );
253
+ } finally {
254
+ if (timeoutId) {
255
+ clearTimeout(timeoutId);
256
+ }
257
+ }
258
+ if (!res || !res.ok) {
259
+ const err = new AccountAuthError(
260
+ "auth_rejected",
261
+ `token refresh failed with HTTP ${res ? res.status : "?"}`,
262
+ );
263
+ err.status = res ? res.status : 0;
264
+ throw err;
265
+ }
266
+
267
+ let data = null;
268
+ try {
269
+ data = await res.json();
270
+ } catch (e) {
271
+ throw new AccountAuthError("auth_invalid", e?.message || "token refresh returned invalid JSON");
272
+ }
273
+
274
+ const accessToken = accessTokenFromRefreshPayload(data);
275
+ if (!accessToken) {
276
+ throw new AccountAuthError("auth_invalid", "token refresh returned no access token");
277
+ }
278
+
279
+ const expMs = decodeJwtExpMs(accessToken) || now() + 10 * 60_000;
280
+ if (mintSessionGeneration !== sessionGeneration) {
281
+ throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
282
+ }
283
+ const rotated = refreshTokenFromRefreshPayload(data);
284
+ // The caller persists a rotation before its next account read. Key the
285
+ // still-valid access token by that current refresh token, not the consumed one.
286
+ tokenCache = { cacheKey: `${root}\0${rotated || refreshToken}`, accessToken, expMs };
287
+ return {
288
+ accessToken,
289
+ refreshToken: rotated && rotated !== refreshToken ? rotated : null,
290
+ // Rotating the refresh token can invalidate the csrf token paired with the
291
+ // previous session state. Surface the fresh one so the caller can keep the
292
+ // relayed (refresh, csrf) pair in sync — a stale relayed csrf breaks the
293
+ // dashboard's cookie-path refresh with 403 Invalid CSRF.
294
+ csrfToken: csrfTokenFromRefreshPayload(data),
295
+ };
296
+ }
297
+
298
+ /**
299
+ * Mint (or reuse a cached) InsForge access token from a refresh token.
300
+ *
301
+ * Concurrent callers with the same (baseUrl, refreshToken) share ONE in-flight
302
+ * refresh; see `mintInflight`.
303
+ *
304
+ * @param {boolean} [throwOnFailure] when true, reject with a classified
305
+ * `AccountAuthError` instead of resolving to `null`.
306
+ * @returns {Promise<{accessToken: string, refreshToken: string|null, csrfToken: string|null}|null>}
307
+ * null when no refresh token is available or the refresh failed.
308
+ */
309
+ async function mintAccessToken({
310
+ baseUrl,
311
+ anonKey,
312
+ refreshToken,
313
+ fetchImpl = fetch,
314
+ now = Date.now,
315
+ skewMs = 60_000,
316
+ timeoutMs,
317
+ throwOnFailure = false,
318
+ } = {}) {
319
+ if (!refreshToken) {
320
+ if (throwOnFailure) throw new AccountAuthError("auth_missing_refresh_token", "not signed in");
321
+ return null;
322
+ }
323
+ const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
324
+ const cacheKey = `${root}\0${refreshToken}`;
325
+ if (
326
+ tokenCache.cacheKey === cacheKey &&
327
+ tokenCache.accessToken &&
328
+ tokenCache.expMs - skewMs > now()
329
+ ) {
330
+ return { accessToken: tokenCache.accessToken, refreshToken: null, csrfToken: null };
331
+ }
332
+
333
+ let inflight = mintInflight.get(cacheKey);
334
+ if (!inflight) {
335
+ inflight = performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs })
336
+ .finally(() => {
337
+ // Only clear our own entry: a later caller may already have started a
338
+ // fresh mint after this one settled.
339
+ if (mintInflight.get(cacheKey) === inflight) mintInflight.delete(cacheKey);
340
+ });
341
+ mintInflight.set(cacheKey, inflight);
342
+ }
343
+
344
+ try {
345
+ return await inflight;
346
+ } catch (e) {
347
+ if (throwOnFailure) throw e;
348
+ return null;
349
+ }
350
+ }
351
+
352
+ /**
353
+ * GET a `token-usage-account-*` edge function, forwarding the popover's query
354
+ * params (minus `account`/`scope`, which are local-only routing knobs).
355
+ */
356
+ async function fetchAccountFunction({
357
+ baseUrl,
358
+ anonKey,
359
+ accessToken,
360
+ slug,
361
+ searchParams,
362
+ fetchImpl = fetch,
363
+ timeoutMs,
364
+ } = {}) {
365
+ const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
366
+ const url = new URL(functionUrlFor(root, slug));
367
+ url.search = accountFunctionParams(slug, searchParams).toString();
368
+ const headers = { Accept: "application/json", Authorization: `Bearer ${accessToken}` };
369
+ if (anonKey) headers.apikey = anonKey;
370
+
371
+ let timeoutId;
372
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
373
+ const signal = controller ? controller.signal : undefined;
374
+
375
+ if (controller && timeoutMs && timeoutMs > 0) {
376
+ timeoutId = setTimeout(() => {
377
+ controller.abort();
378
+ }, timeoutMs);
379
+ }
380
+
381
+ try {
382
+ const res = await fetchFunctionResponse(url.toString(), { method: "GET", headers, signal }, fetchImpl);
383
+ if (!res || !res.ok) {
384
+ const err = new Error(`Account fetch failed with HTTP ${res ? res.status : "?"}`);
385
+ err.status = res ? res.status : 0;
386
+ const failure = res?.json ? await res.json().catch(() => ({})) : {};
387
+ if (typeof failure?.code === "string") err.code = failure.code;
388
+ if (typeof failure?.recovery_url === "string") err.recoveryUrl = failure.recovery_url;
389
+ throw err;
390
+ }
391
+ const data = await res.json();
392
+ return slug === HEATMAP_ACCOUNT_SLUG ? expandHeatmapCompact(data) : data;
393
+ } finally {
394
+ if (timeoutId) {
395
+ clearTimeout(timeoutId);
396
+ }
397
+ }
398
+ }
399
+
400
+ /**
401
+ * High-level helper used by local-api: mint a token from `refreshToken`, then
402
+ * fetch the cross-device aggregate matching `usageSlug`.
403
+ *
404
+ * @returns {Promise<{data: any, rotatedRefreshToken: string|null, rotatedCsrfToken: string|null}|null>}
405
+ * null when there is no cloud equivalent, no refresh token, or the refresh
406
+ * failed. Throws only when the account endpoint itself errors (so callers can
407
+ * distinguish "not signed in" from "cloud request failed").
408
+ */
409
+ async function fetchAccountUsage({
410
+ usageSlug,
411
+ searchParams,
412
+ baseUrl = DEFAULT_BASE_URL,
413
+ anonKey = DEFAULT_ANON_KEY,
414
+ refreshToken,
415
+ fetchImpl = fetch,
416
+ now = Date.now,
417
+ timeoutMs,
418
+ onSessionRefreshed,
419
+ } = {}) {
420
+ const slug = accountSlugFor(usageSlug);
421
+ if (!slug) return null;
422
+ if (!refreshToken) return null;
423
+
424
+ const sessionAtStart = sessionGeneration;
425
+ const startTime = now();
426
+ const getRemainingTimeout = () => {
427
+ if (!timeoutMs) return undefined;
428
+ const elapsed = now() - startTime;
429
+ const remaining = timeoutMs - elapsed;
430
+ return remaining > 0 ? remaining : 1;
431
+ };
432
+
433
+ // `throwOnFailure` keeps "not signed in" (null, handled above) distinct from
434
+ // "signed in but the refresh call failed" (throws) so the caller does not
435
+ // silently downgrade an account view into a this-machine view.
436
+ const minted = await mintAccessToken({
437
+ baseUrl,
438
+ anonKey,
439
+ refreshToken,
440
+ fetchImpl,
441
+ now,
442
+ timeoutMs: getRemainingTimeout(),
443
+ throwOnFailure: true,
444
+ });
445
+ if (!minted) return null;
446
+ if (sessionAtStart !== sessionGeneration) {
447
+ throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
448
+ }
449
+
450
+ // The refresh already consumed the old credential. Persist its replacement
451
+ // before an edge read can wait, fail, or overlap a different account query.
452
+ if (typeof onSessionRefreshed === "function" && (minted.refreshToken || minted.csrfToken)) {
453
+ await onSessionRefreshed({ refreshToken: minted.refreshToken, csrfToken: minted.csrfToken });
454
+ if (sessionAtStart !== sessionGeneration) {
455
+ throw new AccountAuthError("auth_session_changed", "account session changed during token persistence");
456
+ }
457
+ }
458
+
459
+ // Keyed after the mint so rotation cannot invalidate the entry, and so a
460
+ // revoked session fails here rather than being served from cache.
461
+ const sub = decodeJwtSub(minted.accessToken);
462
+ const cacheKey = sub
463
+ ? payloadCacheKey({ root: String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, ""), sub, slug, searchParams })
464
+ : null;
465
+ const force = searchParams?.get("refresh") === "1";
466
+ if (cacheKey && !force) {
467
+ const cached = payloadCacheGet(cacheKey, now);
468
+ if (cached !== null) {
469
+ // Still surface a rotation from this mint: dropping it would leave the
470
+ // caller relaying a refresh token the backend has already consumed.
471
+ return {
472
+ data: cached,
473
+ rotatedRefreshToken: minted.refreshToken,
474
+ rotatedCsrfToken: minted.csrfToken,
475
+ };
476
+ }
477
+ }
478
+
479
+ const flightKey = cacheKey ? `${cacheKey}\0${payloadGeneration}\0${force ? "refresh" : `normal:${payloadVersions.get(cacheKey) || 0}`}` : null;
480
+ let pending = flightKey && payloadInflight.get(flightKey);
481
+ if (!pending) {
482
+ // A forced read supersedes an older ordinary read of the same account.
483
+ // Keep concurrent forced consumers together without sharing its old flight.
484
+ if (force && cacheKey) {
485
+ payloadCache.delete(cacheKey);
486
+ payloadVersions.set(cacheKey, (payloadVersions.get(cacheKey) || 0) + 1);
487
+ }
488
+ const generation = payloadGeneration;
489
+ const version = payloadVersions.get(cacheKey) || 0;
490
+ pending = (async () => {
491
+ try {
492
+ const data = await fetchAccountFunction({
493
+ baseUrl, anonKey, accessToken: minted.accessToken, slug, searchParams,
494
+ fetchImpl, timeoutMs: getRemainingTimeout(),
495
+ });
496
+ if (generation === payloadGeneration && version === (payloadVersions.get(cacheKey) || 0) && cacheKey && data != null) {
497
+ payloadCacheSet(cacheKey, data, now, slug === "token-usage-account-summary" ? SUMMARY_PAYLOAD_TTL_MS : PAYLOAD_TTL_MS);
498
+ }
499
+ return JSON.stringify(data);
500
+ } catch (error) {
501
+ if (error.status === 401 && sessionAtStart === sessionGeneration) {
502
+ invalidateCloudAccountPayloadCache({ sessionChanged: true });
503
+ error.invalidatedSessionGeneration = sessionGeneration;
504
+ }
505
+ throw error;
506
+ }
507
+ })();
508
+ if (flightKey) {
509
+ payloadInflight.set(flightKey, pending);
510
+ const cleanup = () => {
511
+ if (payloadInflight.get(flightKey) === pending) payloadInflight.delete(flightKey);
512
+ };
513
+ pending.then(cleanup, cleanup);
514
+ }
515
+ }
516
+ const body = await pending;
517
+ if (sessionAtStart !== sessionGeneration) {
518
+ throw new AccountAuthError("auth_session_changed", "account session changed during account read");
519
+ }
520
+ const data = body === undefined ? undefined : JSON.parse(body);
521
+ return { data, rotatedRefreshToken: minted.refreshToken, rotatedCsrfToken: minted.csrfToken };
522
+ }
523
+
524
+ module.exports = {
525
+ AccountAuthError,
526
+ USAGE_TO_ACCOUNT_SLUG,
527
+ PAYLOAD_TTL_MS,
528
+ SUMMARY_PAYLOAD_TTL_MS,
529
+ invalidateCloudAccountPayloadCache,
530
+ getCloudAccountSessionGeneration,
531
+ HEATMAP_ACCOUNT_SLUG,
532
+ accountSlugFor,
533
+ accessTokenFromRefreshPayload,
534
+ refreshTokenFromRefreshPayload,
535
+ decodeJwtExpMs,
536
+ decodeJwtSub,
537
+ mintAccessToken,
538
+ fetchAccountFunction,
539
+ fetchAccountUsage,
540
+ __resetCloudAccountCacheForTests,
541
+ };