返回 CodeWhale
product-usage.ts
根目录 / web / lib / telemetry / product-usage.ts
1 import { readBoundedBody } from "../bounded-body";
2
3 /**
4 * product-usage.ts — aggregate, default-on, user-disableable usage counting
5 * for the website.
6 *
7 * This is the browser side of the first-party telemetry contract
8 * (telemetry-ingest/src/schema.ts, docs/TELEMETRY.md): closed schema version
9 * 5 carrying policy notice version 7, the unchanged `product_usage` event with thirteen
10 * unsigned counters, a random v4 install id unrelated to any person and
11 * rotated every 90 days, and fixed aggregate `funnel_usage` counters — no URL, referrer, error
12 * text, account, or content ever enters the envelope. There is no analytics
13 * SDK and no processor token in the browser; the same-origin route
14 * (app/api/product-telemetry) forwards a validated batch to the canonical
15 * ingest only when the operator has configured that exact endpoint.
16 *
17 * Counting is on by default and every recorded opt-out stays off. The only
18 * stored state is the person's own choice: an explicit "off" from any policy
19 * version disables counting, an explicit "on" keeps it, and the absence of a
20 * record is the default. Unreadable stored state fails closed. The notice
21 * version is policy metadata, never a record that anyone accepted anything.
22 * Turning counting off clears the queued counts and the install id, cancels
23 * any pending delivery, and — through the `storage` event — does the same in
24 * every other open tab.
25 *
26 * Framework-free and injectable so the contract is testable in Node: the
27 * storage, clock, id source, and transport are parameters with browser
28 * defaults.
29 */
30
31 export const SCHEMA_VERSION = 5;
32 export const LEGACY_SCHEMA_VERSION = 3;
33 export const NOTICE_VERSION = 7;
34 export const LEGACY_NOTICE_VERSION = 5;
35 export const INSTALL_ID_ROTATION_MS = 90 * 24 * 60 * 60 * 1000;
36 export const MAX_ENVELOPE_BYTES = 4 * 1024;
37 /** Counts wait this long after the last interaction before one delivery. */
38 export const FLUSH_DELAY_MS = 20_000;
39
40 /** Kept under its historical key so an opt-out recorded under the old policy still counts. */
41 export const PREFERENCE_STORAGE_KEY = "cw-usage-consent";
42 export const INSTALL_STORAGE_KEY = "cw-usage-install";
43 export const COUNTERS_STORAGE_KEY = "cw-usage-counters";
44 export const FUNNEL_STORAGE_KEY = "cw-usage-funnel-counters";
45
46 export const PRODUCT_COUNTER_FIELDS = [
47 "page_view",
48 "docs_view",
49 "install_copy",
50 "download",
51 "signup",
52 "login",
53 "session_create",
54 "session_resume",
55 "turn_submit",
56 "turn_complete",
57 "settings_open",
58 "integration_connect",
59 "error_shown",
60 ] as const;
61
62 export const FUNNEL_COUNTER_FIELDS = [
63 "home_view", "install_view", "quickstart_view", "contribute_view",
64 "install_intent", "install_confirmed", "star_exit", "issue_exit",
65 "help_wanted_exit", "guide_exit", "docs_search", "docs_search_empty",
66 "docs_search_result", "quickstart_confirmed",
67 ] as const;
68
69 export type FunnelCounter = (typeof FUNNEL_COUNTER_FIELDS)[number];
70 export type FunnelCounters = Record<FunnelCounter, number>;
71
72 export type ProductCounter = (typeof PRODUCT_COUNTER_FIELDS)[number];
73 export type ProductCounters = Record<ProductCounter, number>;
74
75 export const SURFACES = ["website", "web-app", "desktop"] as const;
76 export type Surface = (typeof SURFACES)[number];
77
78 export const ENVELOPE_FIELDS = [
79 "schema_version",
80 "notice_version",
81 "sent_at",
82 "install_id",
83 "app_version",
84 "git_sha",
85 "surface",
86 "os",
87 "arch",
88 "libc",
89 "tty",
90 "events",
91 ] as const;
92
93 export interface ProductUsageEnvelope {
94 schema_version: 3 | 5;
95 notice_version: 5 | 7;
96 sent_at: string;
97 install_id: string;
98 app_version: string;
99 git_sha: null;
100 surface: Surface;
101 os: "other";
102 arch: "other";
103 libc: "none";
104 tty: false;
105 events: ({ event: "product_usage"; counters: ProductCounters } | { event: "funnel_usage"; counters: FunnelCounters })[];
106 }
107
108 const U32_MAX = 4294967295;
109 const SENT_AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
110 const INSTALL_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
111 const VERSION_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/;
112
113 export function emptyCounters(): ProductCounters {
114 return Object.fromEntries(PRODUCT_COUNTER_FIELDS.map((field) => [field, 0])) as ProductCounters;
115 }
116
117 export function emptyFunnelCounters(): FunnelCounters {
118 return Object.fromEntries(FUNNEL_COUNTER_FIELDS.map((field) => [field, 0])) as FunnelCounters;
119 }
120
121 function isPlainObject(value: unknown): value is Record<string, unknown> {
122 return typeof value === "object" && value !== null && !Array.isArray(value);
123 }
124
125 function keysExactly(value: Record<string, unknown>, expected: readonly string[]): string | null {
126 const actual = Object.keys(value);
127 for (const key of actual) if (!expected.includes(key)) return `unexpected key ${key}`;
128 for (const key of expected) if (!(key in value)) return `missing key ${key}`;
129 return null;
130 }
131
132 /**
133 * The closed-set validator, mirroring the ingest's rules for a browser
134 * batch: exact key sets everywhere, constant envelope values, bounded aggregate
135 * `product_usage` and `funnel_usage` events, every counter a u32. Unknown keys reject the whole
136 * envelope — there is no sanitising path.
137 */
138 export function validateEnvelope(
139 value: unknown,
140 options: { surfaces?: readonly Surface[] } = {},
141 ): { ok: true; envelope: ProductUsageEnvelope } | { ok: false; reason: string } {
142 const surfaces = options.surfaces ?? SURFACES;
143 if (!isPlainObject(value)) return { ok: false, reason: "not an object" };
144 const keyError = keysExactly(value, ENVELOPE_FIELDS);
145 if (keyError) return { ok: false, reason: `envelope: ${keyError}` };
146 const legacy = value.schema_version === LEGACY_SCHEMA_VERSION;
147 if (!legacy && value.schema_version !== SCHEMA_VERSION) return { ok: false, reason: "schema_version" };
148 if (value.notice_version !== (legacy ? LEGACY_NOTICE_VERSION : NOTICE_VERSION)) return { ok: false, reason: "notice_version" };
149 if (typeof value.sent_at !== "string" || !SENT_AT_RE.test(value.sent_at)) return { ok: false, reason: "sent_at" };
150 if (typeof value.install_id !== "string" || !INSTALL_ID_RE.test(value.install_id)) return { ok: false, reason: "install_id" };
151 if (typeof value.app_version !== "string" || value.app_version.length > 64 || !VERSION_RE.test(value.app_version)) {
152 return { ok: false, reason: "app_version" };
153 }
154 if (value.git_sha !== null) return { ok: false, reason: "git_sha" };
155 if (typeof value.surface !== "string" || !surfaces.includes(value.surface as Surface) || (!legacy && value.surface !== "website")) return { ok: false, reason: "surface" };
156 if (value.os !== "other") return { ok: false, reason: "os" };
157 if (value.arch !== "other") return { ok: false, reason: "arch" };
158 if (value.libc !== "none") return { ok: false, reason: "libc" };
159 if (value.tty !== false) return { ok: false, reason: "tty" };
160 if (!Array.isArray(value.events) || value.events.length < 1 || value.events.length > (legacy ? 1 : 200)) return { ok: false, reason: "events" };
161 for (const event of value.events) {
162 if (!isPlainObject(event)) return { ok: false, reason: "event: not an object" };
163 const eventKeyError = keysExactly(event, ["event", "counters"]);
164 if (eventKeyError) return { ok: false, reason: `event: ${eventKeyError}` };
165 const fields = event.event === "product_usage" ? PRODUCT_COUNTER_FIELDS : !legacy && event.event === "funnel_usage" ? FUNNEL_COUNTER_FIELDS : null;
166 if (!fields) return { ok: false, reason: "event: name" };
167 if (!isPlainObject(event.counters)) return { ok: false, reason: "counters: not an object" };
168 const counterKeyError = keysExactly(event.counters, fields);
169 if (counterKeyError) return { ok: false, reason: `counters: ${counterKeyError}` };
170 for (const field of fields) {
171 const item = event.counters[field];
172 if (typeof item !== "number" || !Number.isInteger(item) || item < 0 || item > U32_MAX) {
173 return { ok: false, reason: `counters: ${field}` };
174 }
175 }
176 }
177 return { ok: true, envelope: value as unknown as ProductUsageEnvelope };
178 }
179
180 /** RFC3339 UTC at second precision, exactly `to_rfc3339_opts(Secs, true)`. */
181 export function sentAt(now: number): string {
182 return new Date(Math.floor(now / 1000) * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
183 }
184
185 export function buildEnvelope(input: {
186 counters: ProductCounters;
187 funnel?: FunnelCounters;
188 installId: string;
189 appVersion: string;
190 surface: Surface;
191 now: number;
192 }): ProductUsageEnvelope {
193 return {
194 schema_version: SCHEMA_VERSION,
195 notice_version: NOTICE_VERSION,
196 sent_at: sentAt(input.now),
197 install_id: input.installId,
198 app_version: input.appVersion,
199 git_sha: null,
200 surface: input.surface,
201 os: "other",
202 arch: "other",
203 libc: "none",
204 tty: false,
205 events: [
206 { event: "product_usage", counters: { ...input.counters } },
207 ...(input.funnel && hasFunnelCounts(input.funnel) ? [{ event: "funnel_usage" as const, counters: { ...input.funnel } }] : []),
208 ],
209 };
210 }
211
212 // --------------------------------------------------------------- preference
213
214 export interface UsagePreferenceRecord {
215 /** Policy notice version in force when the choice was made. Metadata only. */
216 version: number;
217 granted: boolean;
218 decidedAt: string;
219 }
220
221 /** `default` is the absence of a record: counting is on. `on` / `off` are explicit choices. */
222 export type UsagePreference = "on" | "off" | "default";
223
224 /**
225 * Reads the stored choice. Counting is on by default, so no record means
226 * `default`. Any explicit refusal — from this policy version or an older one
227 * — stays `off`; an old decline is still a decline. A record that exists but
228 * cannot be read fails closed as `off` rather than being replaced by the
229 * default.
230 */
231 export function readUsagePreference(raw: string | null | undefined): UsagePreference {
232 if (raw === null || raw === undefined) return "default";
233 try {
234 const parsed = JSON.parse(raw) as Partial<UsagePreferenceRecord>;
235 if (!isPlainObject(parsed) || typeof parsed.granted !== "boolean") return "off";
236 return parsed.granted ? "on" : "off";
237 } catch {
238 return "off";
239 }
240 }
241
242 export function usageCountingEnabled(preference: UsagePreference): boolean {
243 return preference !== "off";
244 }
245
246 export function usagePreferenceRecord(granted: boolean, now: number): string {
247 const record: UsagePreferenceRecord = { version: NOTICE_VERSION, granted, decidedAt: sentAt(now) };
248 return JSON.stringify(record);
249 }
250
251 export interface PrivacySignalSource {
252 globalPrivacyControl?: unknown;
253 doNotTrack?: unknown;
254 msDoNotTrack?: unknown;
255 }
256
257 const DO_NOT_TRACK_VALUES = ["1", "yes"];
258
259 export function privacySignalActive(
260 navigatorLike: object | null | undefined = typeof navigator === "undefined" ? null : navigator,
261 windowLike: object | null | undefined = typeof window === "undefined" ? null : window,
262 ): boolean {
263 const nav = navigatorLike as PrivacySignalSource | null | undefined;
264 const win = windowLike as PrivacySignalSource | null | undefined;
265 try {
266 if (nav?.globalPrivacyControl === true) return true;
267 return [nav?.doNotTrack, nav?.msDoNotTrack, win?.doNotTrack, win?.msDoNotTrack]
268 .some((value) => typeof value === "string" && DO_NOT_TRACK_VALUES.includes(value));
269 } catch {
270 return false;
271 }
272 }
273
274 export function privacySignalHeader(headers: Pick<Headers, "get">): boolean {
275 return headers.get("sec-gpc")?.trim() === "1" || headers.get("dnt")?.trim() === "1";
276 }
277
278 export function clearUsageState(storage: StorageLike): void {
279 for (const key of [COUNTERS_STORAGE_KEY, FUNNEL_STORAGE_KEY, INSTALL_STORAGE_KEY]) {
280 try {
281 storage.removeItem(key);
282 } catch {}
283 }
284 }
285
286 // --------------------------------------------------------------- install id
287
288 interface InstallRecord {
289 id: string;
290 createdAt: number;
291 }
292
293 /** The current install id, or a fresh one when missing, malformed, or older than 90 days. */
294 export function resolveInstallId(
295 raw: string | null | undefined,
296 now: number,
297 randomUuid: () => string,
298 ): { id: string; raw: string; rotated: boolean } {
299 try {
300 if (raw) {
301 const parsed = JSON.parse(raw) as Partial<InstallRecord>;
302 if (
303 isPlainObject(parsed) &&
304 typeof parsed.id === "string" &&
305 INSTALL_ID_RE.test(parsed.id) &&
306 typeof parsed.createdAt === "number" &&
307 now - parsed.createdAt >= 0 &&
308 now - parsed.createdAt < INSTALL_ID_ROTATION_MS
309 ) {
310 return { id: parsed.id, raw, rotated: false };
311 }
312 }
313 } catch {
314 /* unreadable: rotate */
315 }
316 const id = randomUuid();
317 const record: InstallRecord = { id, createdAt: now };
318 return { id, raw: JSON.stringify(record), rotated: true };
319 }
320
321 // ----------------------------------------------------------------- counters
322
323 export function readCounters(raw: string | null | undefined): ProductCounters {
324 const counters = emptyCounters();
325 if (!raw) return counters;
326 try {
327 const parsed = JSON.parse(raw) as Record<string, unknown>;
328 if (!isPlainObject(parsed)) return counters;
329 for (const field of PRODUCT_COUNTER_FIELDS) {
330 const value = parsed[field];
331 if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= U32_MAX) {
332 counters[field] = value;
333 }
334 }
335 } catch {
336 /* unreadable: start from zero */
337 }
338 return counters;
339 }
340
341 export function hasCounts(counters: ProductCounters): boolean {
342 return PRODUCT_COUNTER_FIELDS.some((field) => counters[field] > 0);
343 }
344
345 export function readFunnelCounters(raw: string | null | undefined): FunnelCounters {
346 const counters = emptyFunnelCounters();
347 if (!raw) return counters;
348 try {
349 const parsed: unknown = JSON.parse(raw);
350 if (!isPlainObject(parsed)) return counters;
351 for (const field of FUNNEL_COUNTER_FIELDS) {
352 const value = parsed[field];
353 if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= U32_MAX) counters[field] = value;
354 }
355 } catch {}
356 return counters;
357 }
358
359 export function hasFunnelCounts(counters: FunnelCounters): boolean {
360 return FUNNEL_COUNTER_FIELDS.some((field) => counters[field] > 0);
361 }
362
363 // ----------------------------------------------------------------- recorder
364
365 export interface StorageLike {
366 getItem(key: string): string | null;
367 setItem(key: string, value: string): void;
368 removeItem(key: string): void;
369 }
370
371 export interface RecorderOptions {
372 surface: Surface;
373 appVersion: string;
374 /** Same-origin route that forwards to the canonical ingest. */
375 endpoint: string;
376 storage: StorageLike;
377 now?: () => number;
378 randomUuid?: () => string;
379 /** Transport; returns whether the batch was accepted. Never retried. */
380 send?: (endpoint: string, body: string, signal?: AbortSignal) => Promise<boolean>;
381 setTimer?: (callback: () => void, delayMs: number) => unknown;
382 clearTimer?: (handle: unknown) => void;
383 flushDelayMs?: number;
384 blocked?: () => boolean;
385 }
386
387 export interface UsageRecorder {
388 preference(): UsagePreference;
389 /** Deliberately turn counting back on after an opt-out. */
390 enable(): boolean;
391 /** Record a durable opt-out and clear everything queued in this browser. */
392 disable(): boolean;
393 /** Re-read the preference from storage (another tab may have changed it). */
394 sync(): void;
395 record(counter: ProductCounter): void;
396 recordFunnel(counter: FunnelCounter): void;
397 pendingFunnel(): FunnelCounters;
398 delivery(): "idle" | "accepted" | "rejected";
399 /** Deliver whatever is queued now (also used on pagehide). */
400 flush(): Promise<void>;
401 pending(): ProductCounters;
402 }
403
404 function browserSend(endpoint: string, body: string, signal?: AbortSignal): Promise<boolean> {
405 if (typeof fetch !== "function") return Promise.resolve(false);
406 const controller = typeof AbortController === "function" ? new AbortController() : null;
407 const timer = controller ? setTimeout(() => controller.abort(), 1500) : null;
408 return fetch(endpoint, {
409 method: "POST",
410 headers: { "content-type": "application/json" },
411 body,
412 keepalive: true,
413 credentials: "omit",
414 referrerPolicy: "no-referrer",
415 signal: signal && controller ? AbortSignal.any([signal, controller.signal]) : signal ?? controller?.signal,
416 })
417 .then(async (response) => {
418 if (!response.ok) return false;
419 const bytes = await readBoundedBody(response, 512);
420 const receipt: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
421 return isPlainObject(receipt) && receipt.accepted === true;
422 })
423 .catch(() => false)
424 .finally(() => {
425 if (timer !== null) clearTimeout(timer);
426 });
427 }
428
429 export function createUsageRecorder(options: RecorderOptions): UsageRecorder {
430 const now = options.now ?? (() => Date.now());
431 const randomUuid = options.randomUuid ?? (() => crypto.randomUUID());
432 const send = options.send ?? browserSend;
433 const setTimer = options.setTimer ?? ((callback, delay) => setTimeout(callback, delay));
434 const clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
435 const flushDelayMs = options.flushDelayMs ?? FLUSH_DELAY_MS;
436 const { storage } = options;
437
438 let counters = emptyCounters();
439 let funnel = emptyFunnelCounters();
440 let deliveryController: AbortController | null = null;
441 let delivery: "idle" | "accepted" | "rejected" = "idle";
442 let timer: unknown = null;
443 let inFlight = false;
444 let sessionOff = false;
445
446 const read = (key: string) => {
447 try {
448 return storage.getItem(key);
449 } catch {
450 return null;
451 }
452 };
453 const write = (key: string, value: string) => {
454 try {
455 storage.setItem(key, value);
456 return storage.getItem(key) === value;
457 } catch {
458 return false;
459 }
460 };
461 const remove = (key: string) => {
462 try {
463 storage.removeItem(key);
464 } catch {
465 /* nothing to clear */
466 }
467 };
468
469 const cancelTimer = () => {
470 if (timer !== null) clearTimer(timer);
471 timer = null;
472 };
473
474 /** Everything queued and every identity goes; nothing pending survives. */
475 const clearAll = () => {
476 cancelTimer();
477 deliveryController?.abort();
478 counters = emptyCounters();
479 funnel = emptyFunnelCounters();
480 clearUsageState(storage);
481 };
482
483 const preference = (): UsagePreference => {
484 if (sessionOff || options.blocked?.()) return "off";
485 try { return readUsagePreference(storage.getItem(PREFERENCE_STORAGE_KEY)); } catch { return "off"; }
486 };
487 const enabled = () => usageCountingEnabled(preference());
488
489 const schedule = () => {
490 if (timer !== null) return;
491 timer = setTimer(() => {
492 timer = null;
493 void flush();
494 }, flushDelayMs);
495 };
496
497 const flush = async () => {
498 if (inFlight) return;
499 cancelTimer();
500 if (!enabled()) {
501 clearAll();
502 return;
503 }
504 const batch = counters;
505 const funnelBatch = funnel;
506 if (!hasCounts(batch) && !hasFunnelCounts(funnelBatch)) return;
507 const install = resolveInstallId(read(INSTALL_STORAGE_KEY), now(), randomUuid);
508 if (install.rotated && !write(INSTALL_STORAGE_KEY, install.raw)) {
509 delivery = "rejected";
510 clearAll();
511 return;
512 }
513 const envelope = buildEnvelope({
514 counters: batch,
515 funnel: funnelBatch,
516 installId: install.id,
517 appVersion: options.appVersion,
518 surface: options.surface,
519 now: now(),
520 });
521 const body = JSON.stringify(envelope);
522 if (!validateEnvelope(envelope).ok || body.length > MAX_ENVELOPE_BYTES) return;
523 // Discard after one attempt, accepted or not: there is no retry queue,
524 // and a count that did not land is not worth remembering.
525 counters = emptyCounters();
526 funnel = emptyFunnelCounters();
527 remove(COUNTERS_STORAGE_KEY);
528 remove(FUNNEL_STORAGE_KEY);
529 inFlight = true;
530 deliveryController = new AbortController();
531 try {
532 delivery = await send(options.endpoint, body, deliveryController.signal) ? "accepted" : "rejected";
533 } catch {
534 delivery = "rejected";
535 } finally {
536 deliveryController = null;
537 inFlight = false;
538 if (enabled() && (hasCounts(counters) || hasFunnelCounts(funnel))) schedule();
539 }
540 };
541
542 // Hydrate any counts a previous page on this origin left behind, but only
543 // while counting is allowed; otherwise clear them as an opt-out's debris.
544 if (enabled()) {
545 counters = readCounters(read(COUNTERS_STORAGE_KEY));
546 funnel = readFunnelCounters(read(FUNNEL_STORAGE_KEY));
547 } else {
548 clearAll();
549 }
550
551 return {
552 preference,
553 enable() {
554 const saved = write(PREFERENCE_STORAGE_KEY, usagePreferenceRecord(true, now()));
555 if (saved) sessionOff = false;
556 return saved;
557 },
558 disable() {
559 sessionOff = true;
560 const saved = write(PREFERENCE_STORAGE_KEY, usagePreferenceRecord(false, now()));
561 if (saved) sessionOff = false;
562 clearAll();
563 return saved;
564 },
565 sync() {
566 if (!enabled()) clearAll();
567 },
568 record(counter) {
569 if (!enabled()) {
570 clearAll();
571 return;
572 }
573 if (counters[counter] < U32_MAX) counters[counter] += 1;
574 write(COUNTERS_STORAGE_KEY, JSON.stringify(counters));
575 schedule();
576 },
577 recordFunnel(counter) {
578 if (!enabled()) { clearAll(); return; }
579 if (!(FUNNEL_COUNTER_FIELDS as readonly string[]).includes(counter)) return;
580 if (funnel[counter] < U32_MAX) funnel[counter] += 1;
581 write(FUNNEL_STORAGE_KEY, JSON.stringify(funnel));
582 schedule();
583 },
584 pendingFunnel: () => ({ ...funnel }),
585 delivery: () => delivery,
586 flush,
587 pending: () => ({ ...counters }),
588 };
589 }
590
590 lines TYPESCRIPT