返回 CodeWhale
product-usage.test.ts
根目录 / web / lib / telemetry / product-usage.test.ts
1 import { existsSync, readFileSync } from "node:fs";
2 import { describe, expect, it, vi } from "vitest";
3 import { handleProductTelemetry, ingestUrl, CANONICAL_INGEST_URL } from "../../app/api/product-telemetry/route";
4 import {
5 COUNTERS_STORAGE_KEY,
6 FUNNEL_STORAGE_KEY,
7 emptyFunnelCounters,
8 INSTALL_ID_ROTATION_MS,
9 INSTALL_STORAGE_KEY,
10 NOTICE_VERSION,
11 PREFERENCE_STORAGE_KEY,
12 SCHEMA_VERSION,
13 buildEnvelope,
14 createUsageRecorder,
15 emptyCounters,
16 privacySignalActive,
17 privacySignalHeader,
18 readUsagePreference,
19 resolveInstallId,
20 usageCountingEnabled,
21 usagePreferenceRecord,
22 validateEnvelope,
23 type StorageLike,
24 } from "./product-usage";
25
26 /** The backend's golden browser fixture, when the ingest checkout carries it. */
27 const GOLDEN_PATH = new URL("../../../telemetry-ingest/test/golden/browser-v3.json", import.meta.url);
28
29 const UUID = "82b77c4f-4cce-4c74-8e17-8a38ba0581ee";
30 const NOW = Date.parse("2026-09-04T20:00:00Z");
31
32 function memoryStorage(seed: Record<string, string> = {}): StorageLike & { data: Map<string, string> } {
33 const data = new Map(Object.entries(seed));
34 return {
35 data,
36 getItem: (key) => data.get(key) ?? null,
37 setItem: (key, value) => void data.set(key, value),
38 removeItem: (key) => void data.delete(key),
39 };
40 }
41
42 function recorderWith(storage: StorageLike, sent: string[] = [], now = () => NOW, blocked?: () => boolean) {
43 const timers: (() => void)[] = [];
44 const recorder = createUsageRecorder({
45 surface: "website",
46 appVersion: "0.9.12",
47 endpoint: "/api/product-telemetry",
48 storage,
49 now,
50 blocked,
51 randomUuid: () => UUID,
52 send: async (_endpoint, body) => {
53 sent.push(body);
54 return true;
55 },
56 setTimer: (callback) => {
57 timers.push(callback);
58 return timers.length;
59 },
60 clearTimer: (handle) => {
61 timers[(handle as number) - 1] = () => {};
62 },
63 });
64 return { recorder, timers, sent };
65 }
66
67 describe("product usage envelope", () => {
68 it("matches the closed browser contract and the backend's golden fixture", () => {
69 const counters = emptyCounters();
70 counters.page_view = 1;
71 const envelope = buildEnvelope({ counters, installId: UUID, appVersion: "0.9.12", surface: "website", now: NOW });
72 expect(validateEnvelope(envelope)).toEqual({ ok: true, envelope });
73 expect(SCHEMA_VERSION).toBe(5);
74 expect(NOTICE_VERSION).toBe(7);
75 expect(envelope.notice_version).toBe(7);
76 expect(envelope).not.toHaveProperty("consent_version");
77 expect(envelope.sent_at).toBe("2026-09-04T20:00:00Z");
78 if (existsSync(GOLDEN_PATH)) {
79 const golden = JSON.parse(readFileSync(GOLDEN_PATH, "utf8"));
80 expect(golden.schema_version).toBe(3);
81 expect(golden.notice_version).toBe(5);
82 expect(validateEnvelope(golden).ok).toBe(true);
83 }
84 });
85
86 it("rejects anything outside the closed field set", () => {
87 const base = buildEnvelope({ counters: emptyCounters(), installId: UUID, appVersion: "0.9.12", surface: "website", now: NOW });
88 expect(validateEnvelope({ ...base, referrer: "x" }).ok).toBe(false);
89 expect(validateEnvelope({ ...base, git_sha: "abc" }).ok).toBe(false);
90 expect(validateEnvelope({ ...base, surface: "tui" }).ok).toBe(false);
91 expect(validateEnvelope({ ...base, notice_version: 4 }).ok).toBe(false);
92 expect(validateEnvelope({ ...base, schema_version: 2 }).ok).toBe(false);
93 // The retired consent field never rides along with the policy version.
94 expect(validateEnvelope({ ...base, consent_version: 4 }).ok).toBe(false);
95 expect(validateEnvelope({ ...base, install_id: "not-a-uuid" }).ok).toBe(false);
96 expect(validateEnvelope({ ...base, events: [] }).ok).toBe(false);
97 const extraCounter = structuredClone(base) as unknown as { events: [{ counters: Record<string, number> }] };
98 extraCounter.events[0].counters.url = 1;
99 expect(validateEnvelope(extraCounter).ok).toBe(false);
100 const negative = structuredClone(base) as unknown as { events: [{ counters: Record<string, number> }] };
101 negative.events[0].counters.page_view = -1;
102 expect(validateEnvelope(negative).ok).toBe(false);
103 // The website route only ever accepts the website surface.
104 expect(validateEnvelope({ ...base, surface: "web-app" }, { surfaces: ["website"] }).ok).toBe(false);
105 });
106 });
107
108 describe("usage preference", () => {
109 it("is on by default, keeps every recorded opt-out, and fails closed on unreadable state", () => {
110 expect(readUsagePreference(null)).toBe("default");
111 expect(readUsagePreference(undefined)).toBe("default");
112 expect(readUsagePreference("")).toBe("off");
113 expect(usageCountingEnabled("default")).toBe(true);
114 // Unreadable stored state is never replaced with the default.
115 expect(readUsagePreference("{not json")).toBe("off");
116 expect(readUsagePreference(JSON.stringify({ version: 4 }))).toBe("off");
117 expect(readUsagePreference(JSON.stringify({ version: 4, granted: "yes" }))).toBe("off");
118 // An opt-out recorded under the old opt-in policy is still an opt-out.
119 expect(readUsagePreference(JSON.stringify({ version: 4, granted: false }))).toBe("off");
120 expect(readUsagePreference(JSON.stringify({ version: 3, granted: false }))).toBe("off");
121 expect(readUsagePreference(JSON.stringify({ version: 4, granted: true }))).toBe("on");
122 expect(readUsagePreference(usagePreferenceRecord(false, NOW))).toBe("off");
123 expect(readUsagePreference(usagePreferenceRecord(true, NOW))).toBe("on");
124 expect(JSON.parse(usagePreferenceRecord(false, NOW))).toEqual({ version: NOTICE_VERSION, granted: false, decidedAt: "2026-09-04T20:00:00Z" });
125 });
126
127 it("counts by default without writing any preference record", async () => {
128 const storage = memoryStorage();
129 const { recorder, timers, sent } = recorderWith(storage);
130 expect(recorder.preference()).toBe("default");
131 recorder.record("page_view");
132 recorder.record("page_view");
133 recorder.record("docs_view");
134 expect(timers).toHaveLength(1);
135 timers[0]();
136 await Promise.resolve();
137 expect(sent).toHaveLength(1);
138 const body = JSON.parse(sent[0]);
139 expect(validateEnvelope(body).ok).toBe(true);
140 expect(body.events[0].counters.page_view).toBe(2);
141 expect(body.events[0].counters.docs_view).toBe(1);
142 expect(body.install_id).toBe(UUID);
143 // Discarded after the attempt; nothing was recorded as an acceptance.
144 expect(recorder.pending()).toEqual(emptyCounters());
145 expect(storage.data.has(COUNTERS_STORAGE_KEY)).toBe(false);
146 expect(storage.data.has(PREFERENCE_STORAGE_KEY)).toBe(false);
147 });
148
149 it("counts nothing and stores nothing after an opt-out, including one recorded under the old policy", () => {
150 for (const seed of [
151 { [PREFERENCE_STORAGE_KEY]: JSON.stringify({ version: 4, granted: false }) },
152 { [PREFERENCE_STORAGE_KEY]: usagePreferenceRecord(false, NOW) },
153 { [PREFERENCE_STORAGE_KEY]: "{corrupt" },
154 ]) {
155 const storage = memoryStorage({ ...seed, [COUNTERS_STORAGE_KEY]: JSON.stringify({ page_view: 9 }), [INSTALL_STORAGE_KEY]: "stale" });
156 const { recorder, timers, sent } = recorderWith(storage);
157 expect(recorder.preference()).toBe("off");
158 recorder.record("page_view");
159 recorder.record("install_copy");
160 expect(recorder.pending()).toEqual(emptyCounters());
161 expect(storage.data.has(COUNTERS_STORAGE_KEY)).toBe(false);
162 expect(storage.data.has(INSTALL_STORAGE_KEY)).toBe(false);
163 expect(timers).toHaveLength(0);
164 expect(sent).toHaveLength(0);
165 }
166 });
167
168 it("clears queued counts and identity on opt-out, cancels pending delivery, and re-enables only deliberately", async () => {
169 const storage = memoryStorage();
170 const { recorder, timers, sent } = recorderWith(storage);
171 recorder.record("page_view");
172 await recorder.flush();
173 expect(sent).toHaveLength(1);
174 expect(storage.data.has(INSTALL_STORAGE_KEY)).toBe(true);
175 recorder.record("download");
176 expect(timers).toHaveLength(2);
177 recorder.disable();
178 expect(recorder.preference()).toBe("off");
179 expect(recorder.pending()).toEqual(emptyCounters());
180 expect(storage.data.has(INSTALL_STORAGE_KEY)).toBe(false);
181 expect(storage.data.has(COUNTERS_STORAGE_KEY)).toBe(false);
182 timers[1]();
183 await Promise.resolve();
184 expect(sent).toHaveLength(1);
185 recorder.record("page_view");
186 expect(recorder.pending()).toEqual(emptyCounters());
187 recorder.enable();
188 expect(recorder.preference()).toBe("on");
189 recorder.record("page_view");
190 expect(recorder.pending().page_view).toBe(1);
191 });
192
193 it("honours another tab's opt-out through sync()", () => {
194 const storage = memoryStorage();
195 const { recorder } = recorderWith(storage);
196 recorder.record("page_view");
197 expect(recorder.pending().page_view).toBe(1);
198 // Another tab turns it off: the shared storage changes underneath us.
199 storage.setItem(PREFERENCE_STORAGE_KEY, usagePreferenceRecord(false, NOW));
200 recorder.sync();
201 expect(recorder.pending()).toEqual(emptyCounters());
202 expect(storage.data.has(COUNTERS_STORAGE_KEY)).toBe(false);
203 });
204 });
205
206 describe("install id", () => {
207 it("is a random v4 id, kept for 90 days and then rotated", () => {
208 const fresh = resolveInstallId(null, NOW, () => UUID);
209 expect(fresh).toEqual({ id: UUID, raw: JSON.stringify({ id: UUID, createdAt: NOW }), rotated: true });
210 const kept = resolveInstallId(fresh.raw, NOW + INSTALL_ID_ROTATION_MS - 1, () => "unused");
211 expect(kept.id).toBe(UUID);
212 expect(kept.rotated).toBe(false);
213 const rotated = resolveInstallId(fresh.raw, NOW + INSTALL_ID_ROTATION_MS, () => "9f1a2b3c-4d5e-4f60-8a1b-2c3d4e5f6a7b");
214 expect(rotated.id).toBe("9f1a2b3c-4d5e-4f60-8a1b-2c3d4e5f6a7b");
215 expect(rotated.rotated).toBe(true);
216 expect(resolveInstallId("garbage", NOW, () => UUID).rotated).toBe(true);
217 });
218 });
219
220 describe("same-origin forwarder", () => {
221 const envelope = buildEnvelope({ counters: { ...emptyCounters(), page_view: 1 }, installId: UUID, appVersion: "0.9.12", surface: "website", now: NOW });
222 const post = (body: unknown) =>
223 new Request("http://localhost/api/product-telemetry", {
224 method: "POST",
225 headers: { "content-type": "application/json" },
226 body: typeof body === "string" ? body : JSON.stringify(body),
227 });
228
229 it("is inert without the exact canonical ingest configured", async () => {
230 expect(ingestUrl({})).toBeNull();
231 expect(ingestUrl({ CODEWHALE_TELEMETRY_INGEST_URL: "https://example.com/v1/telemetry" })).toBeNull();
232 expect(ingestUrl({ CODEWHALE_TELEMETRY_INGEST_URL: CANONICAL_INGEST_URL })).toBe(CANONICAL_INGEST_URL);
233 let forwarded = 0;
234 const response = await handleProductTelemetry(post(envelope), {
235 ingestUrl: null,
236 forward: async () => {
237 forwarded += 1;
238 return { ok: true };
239 },
240 });
241 expect(response.status).toBe(200);
242 expect(await response.json()).toEqual({ accepted: false, reason: "disabled" });
243 expect(forwarded).toBe(0);
244 });
245
246 it("forwards only a validated website batch, and only the batch", async () => {
247 const calls: { url: string; body: string }[] = [];
248 const forward = async (url: string, body: string) => {
249 calls.push({ url, body });
250 return { ok: true };
251 };
252 const accepted = await handleProductTelemetry(post(envelope), { ingestUrl: CANONICAL_INGEST_URL, forward });
253 expect(await accepted.json()).toEqual({ accepted: true });
254 expect(calls).toHaveLength(1);
255 expect(calls[0].url).toBe(CANONICAL_INGEST_URL);
256 expect(JSON.parse(calls[0].body)).toEqual(envelope);
257
258 const rejected = await handleProductTelemetry(post({ ...envelope, surface: "web-app" }), { ingestUrl: CANONICAL_INGEST_URL, forward });
259 expect(rejected.status).toBe(422);
260 expect(calls).toHaveLength(1);
261
262 const invalid = await handleProductTelemetry(post("{"), { ingestUrl: CANONICAL_INGEST_URL, forward });
263 expect(invalid.status).toBe(422);
264
265 const oversized = await handleProductTelemetry(post({ ...envelope, app_version: "0.9.12-" + "x".repeat(5000) }), { ingestUrl: CANONICAL_INGEST_URL, forward });
266 expect(oversized.status).toBe(413);
267 expect(calls).toHaveLength(1);
268 });
269
270 it.each([undefined, "1", "4096"])("cancels oversized chunks with declared length %s and never forwards", async (length) => {
271 let cancelled = false;
272 let forwarded = 0;
273 const body = new ReadableStream<Uint8Array>({
274 start(controller) {
275 controller.enqueue(new Uint8Array(2048));
276 controller.enqueue(new Uint8Array(2049));
277 // Deliberately leave the source open: overflow must cancel it.
278 },
279 cancel() { cancelled = true; },
280 });
281 const request = new Request("http://localhost/api/product-telemetry", {
282 method: "POST", body, duplex: "half",
283 headers: length === undefined ? {} : { "content-length": length },
284 } as RequestInit);
285 const response = await handleProductTelemetry(request, {
286 ingestUrl: CANONICAL_INGEST_URL,
287 forward: async () => { forwarded += 1; return { ok: true }; },
288 });
289 expect(response.status).toBe(413);
290 expect(await response.json()).toEqual({ accepted: false, reason: "too_large" });
291 expect(cancelled).toBe(true);
292 expect(request.body?.locked).toBe(false);
293 expect(forwarded).toBe(0);
294 });
295
296 it("bounds UTF-8 bytes rather than JS character count", async () => {
297 let forwarded = 0;
298 const response = await handleProductTelemetry(post("鲸".repeat(1400)), {
299 ingestUrl: CANONICAL_INGEST_URL,
300 forward: async () => { forwarded += 1; return { ok: true }; },
301 });
302 expect(response.status).toBe(413);
303 expect(forwarded).toBe(0);
304 });
305
306 it("accepts an exact 4096-byte valid envelope across chunks", async () => {
307 const json = JSON.stringify(envelope);
308 const bytes = new TextEncoder().encode(json + " ".repeat(4096 - new TextEncoder().encode(json).byteLength));
309 const body = new ReadableStream<Uint8Array>({ start(controller) {
310 for (let offset = 0; offset < bytes.length; offset += 7) controller.enqueue(bytes.slice(offset, offset + 7));
311 controller.close();
312 } });
313 let forwarded = 0;
314 const response = await handleProductTelemetry(new Request("http://localhost/api/product-telemetry", {
315 method: "POST", body, duplex: "half",
316 } as RequestInit), {
317 ingestUrl: CANONICAL_INGEST_URL,
318 forward: async (_url, value) => { forwarded += 1; expect(JSON.parse(value)).toEqual(envelope); return { ok: true }; },
319 });
320 expect(await response.json()).toEqual({ accepted: true });
321 expect(forwarded).toBe(1);
322 });
323
324 it.each(["stream_failure", "invalid_utf8", "invalid_length"])("rejects %s without forwarding", async (kind) => {
325 const body = new ReadableStream<Uint8Array>({ start(controller) {
326 if (kind === "stream_failure") controller.error(new Error("read failed"));
327 else { controller.enqueue(new Uint8Array([0xff])); controller.close(); }
328 } });
329 let forwarded = 0;
330 const response = await handleProductTelemetry(new Request("http://localhost/api/product-telemetry", {
331 method: "POST", body, duplex: "half",
332 headers: kind === "invalid_length" ? { "content-length": "no" } : {},
333 } as RequestInit), {
334 ingestUrl: CANONICAL_INGEST_URL,
335 forward: async () => { forwarded += 1; return { ok: true }; },
336 });
337 expect(response.status).toBe(kind === "invalid_utf8" ? 422 : 400);
338 expect(forwarded).toBe(0);
339 });
340
341 it("reports an unreachable ingest as unavailable without retrying", async () => {
342 let attempts = 0;
343 const response = await handleProductTelemetry(post(envelope), {
344 ingestUrl: CANONICAL_INGEST_URL,
345 forward: async () => {
346 attempts += 1;
347 throw new Error("down");
348 },
349 });
350 expect(await response.json()).toEqual({ accepted: false, reason: "unavailable" });
351 expect(attempts).toBe(1);
352 });
353 });
354
355
356 describe("website funnel contract and delivery", () => {
357 it("matches the ingest golden and rejects legacy or malformed funnel payloads", async () => {
358 const { validateBatch } = await import("../../../telemetry-ingest/src/schema");
359 const counters = emptyCounters(); counters.page_view = 1;
360 const funnel = emptyFunnelCounters();
361 funnel.home_view = 1; funnel.install_intent = 1; funnel.docs_search = 1; funnel.docs_search_result = 1;
362 const envelope = buildEnvelope({ counters, funnel, installId: UUID, appVersion: "0.9.12", surface: "website", now: NOW });
363 const golden = JSON.parse(readFileSync(new URL("../../../telemetry-ingest/test/golden/browser-v5.json", import.meta.url), "utf8"));
364 expect(envelope).toEqual(golden);
365 expect(validateBatch(envelope).ok).toBe(true);
366 expect(validateEnvelope(envelope).ok).toBe(true);
367 expect(validateEnvelope({ ...envelope, schema_version: 3, notice_version: 5 }).ok).toBe(false);
368 expect(validateEnvelope({ ...envelope, surface: "desktop" }).ok).toBe(false);
369 for (const bad of [-1, 1.5, 4294967296, "1"]) {
370 const invalid = structuredClone(golden); invalid.events[1].counters.docs_search = bad;
371 expect(validateEnvelope(invalid).ok).toBe(false); expect(validateBatch(invalid).ok).toBe(false);
372 }
373 const unexpected = structuredClone(golden); unexpected.events[1].counters.query = "private words";
374 expect(validateEnvelope(unexpected).ok).toBe(false); expect(validateBatch(unexpected).ok).toBe(false);
375 });
376
377 it.each([
378 [200, { accepted: true }, "accepted"],
379 [200, { accepted: false, reason: "disabled" }, "rejected"],
380 [200, { accepted: false, reason: "unavailable" }, "rejected"],
381 [200, { accepted: true, padding: "x".repeat(513) }, "rejected"],
382 [500, { accepted: true }, "rejected"],
383 [200, { other: true }, "rejected"],
384 ] as const)("requires an explicit bounded acceptance receipt (%s)", async (status, payload, expected) => {
385 const fetchMock = vi.fn(async (endpoint: string, init: RequestInit) => { expect(endpoint).toBe("/api/product-telemetry"); expect(init.method).toBe("POST"); return Response.json(payload, { status }); }); vi.stubGlobal("fetch", fetchMock);
386 try {
387 const recorder = createUsageRecorder({ surface: "website", appVersion: "0.10.3", endpoint: "/api/product-telemetry", storage: memoryStorage(), now: () => NOW, randomUuid: () => UUID, setTimer: () => 0, clearTimer: () => {} });
388 recorder.recordFunnel("quickstart_confirmed"); await recorder.flush();
389 expect(recorder.delivery()).toBe(expected); expect(fetchMock).toHaveBeenCalledTimes(1);
390 expect(fetchMock.mock.calls[0][1]).toMatchObject({ credentials: "omit", referrerPolicy: "no-referrer" });
391 expect(recorder.pendingFunnel()).toEqual(emptyFunnelCounters());
392 } finally { vi.unstubAllGlobals(); }
393 });
394
395 it("fails closed on unreadable storage and a failed opt-out write", async () => {
396 const unreadable = memoryStorage(); unreadable.getItem = () => { throw new Error("blocked"); };
397 const sent: string[] = []; const first = recorderWith(unreadable, sent).recorder;
398 expect(first.preference()).toBe("off"); first.recordFunnel("install_confirmed"); await first.flush(); expect(sent).toEqual([]);
399 const storage = memoryStorage(); const write = storage.setItem;
400 storage.setItem = (key, value) => { if (key === PREFERENCE_STORAGE_KEY) throw new Error("quota"); write(key, value); };
401 const second = recorderWith(storage, sent).recorder;
402 expect(second.disable()).toBe(false); expect(second.preference()).toBe("off");
403 second.record("page_view"); second.recordFunnel("install_confirmed"); await second.flush();
404 expect(sent).toEqual([]); expect(storage.data.has(INSTALL_STORAGE_KEY)).toBe(false);
405 });
406
407 it("aborts delivery and erases both queues when counting is turned off", async () => {
408 const storage = memoryStorage(); let signal: AbortSignal | undefined;
409 const recorder = createUsageRecorder({ surface: "website", appVersion: "0.10.3", endpoint: "/api/product-telemetry", storage, now: () => NOW, randomUuid: () => UUID, setTimer: () => 0, clearTimer: () => {}, send: async (_url, _body, abort) => {
410 signal = abort; return new Promise<boolean>((resolve) => abort!.addEventListener("abort", () => resolve(false), { once: true }));
411 } });
412 recorder.record("install_copy"); recorder.recordFunnel("install_intent"); const delivery = recorder.flush();
413 expect(signal?.aborted).toBe(false); expect(recorder.disable()).toBe(true); await delivery; expect(signal?.aborted).toBe(true);
414 for (const key of [COUNTERS_STORAGE_KEY, FUNNEL_STORAGE_KEY, INSTALL_STORAGE_KEY]) expect(storage.data.has(key)).toBe(false);
415 recorder.recordFunnel("quickstart_confirmed"); await recorder.flush(); expect(recorder.pendingFunnel()).toEqual(emptyFunnelCounters());
416 });
417
418 it("reschedules new interactions during delivery without retrying the previous batch", async () => {
419 const timers: (() => void)[] = []; const sent: { events: { event: string; counters: Record<string, number> }[] }[] = [];
420 let finish: ((accepted: boolean) => void) | undefined;
421 const recorder = createUsageRecorder({ surface: "website", appVersion: "0.10.3", endpoint: "/api/product-telemetry", storage: memoryStorage(), now: () => NOW, randomUuid: () => UUID, setTimer: (callback) => { timers.push(callback); return timers.length; }, clearTimer: () => {}, send: async (_url, body) => {
422 sent.push(JSON.parse(body)); return sent.length === 1 ? new Promise<boolean>((resolve) => { finish = resolve; }) : true;
423 } });
424 recorder.recordFunnel("install_intent"); const first = recorder.flush(); recorder.recordFunnel("docs_search"); timers.at(-1)!();
425 finish!(false); await first; expect(timers).toHaveLength(3); timers.at(-1)!(); await Promise.resolve(); await Promise.resolve(); expect(sent).toHaveLength(2);
426 expect(sent[0].events.find((event) => event.event === "funnel_usage")!.counters.install_intent).toBe(1);
427 const second = sent[1].events.find((event) => event.event === "funnel_usage")!.counters;
428 expect(second.install_intent).toBe(0); expect(second.docs_search).toBe(1);
429 });
430 });
431
432 describe("browser privacy signals", () => {
433 it("reads Global Privacy Control and Do Not Track, including the legacy properties", () => {
434 expect(privacySignalActive({}, {})).toBe(false);
435 expect(privacySignalActive({ globalPrivacyControl: false, doNotTrack: "0" }, { doNotTrack: "unspecified" })).toBe(false);
436 expect(privacySignalActive({ globalPrivacyControl: true }, {})).toBe(true);
437 expect(privacySignalActive({ doNotTrack: "1" }, {})).toBe(true);
438 expect(privacySignalActive({}, { doNotTrack: "1" })).toBe(true);
439 expect(privacySignalActive({}, { doNotTrack: "yes" })).toBe(true);
440 expect(privacySignalActive({ msDoNotTrack: "1" }, {})).toBe(true);
441 expect(privacySignalActive(null, null)).toBe(false);
442 });
443
444 it("reads the same two signals from request headers", () => {
445 expect(privacySignalHeader(new Headers())).toBe(false);
446 expect(privacySignalHeader(new Headers({ "sec-gpc": "0", dnt: "0" }))).toBe(false);
447 expect(privacySignalHeader(new Headers({ "Sec-GPC": "1" }))).toBe(true);
448 expect(privacySignalHeader(new Headers({ DNT: "1" }))).toBe(true);
449 });
450
451 it("counts nothing, reads and writes no install id, and sends nothing while a signal is present", async () => {
452 const storage = memoryStorage();
453 const reads: string[] = [];
454 const watched: StorageLike = {
455 getItem: (key) => (reads.push(key), storage.getItem(key)),
456 setItem: storage.setItem,
457 removeItem: storage.removeItem,
458 };
459 const { recorder, timers, sent } = recorderWith(watched, [], () => NOW, () => true);
460 recorder.record("page_view");
461 recorder.record("install_copy");
462 recorder.recordFunnel("star_exit");
463 await recorder.flush();
464 expect(reads).toEqual([]);
465 expect(storage.data.size).toBe(0);
466 expect(sent).toEqual([]);
467 expect(timers).toEqual([]);
468 expect(recorder.pending()).toEqual(emptyCounters());
469 expect(recorder.pendingFunnel()).toEqual(emptyFunnelCounters());
470 });
471
472 it("clears counts and the install id from an earlier visit but keeps the person's own choice", () => {
473 const choice = usagePreferenceRecord(true, NOW);
474 const storage = memoryStorage({
475 [COUNTERS_STORAGE_KEY]: JSON.stringify({ ...emptyCounters(), page_view: 3 }),
476 [FUNNEL_STORAGE_KEY]: JSON.stringify({ ...emptyFunnelCounters(), home_view: 1 }),
477 [INSTALL_STORAGE_KEY]: JSON.stringify({ id: UUID, createdAt: NOW }),
478 [PREFERENCE_STORAGE_KEY]: choice,
479 });
480 recorderWith(storage, [], () => NOW, () => true);
481 expect([...storage.data.keys()]).toEqual([PREFERENCE_STORAGE_KEY]);
482 expect(storage.data.get(PREFERENCE_STORAGE_KEY)).toBe(choice);
483 });
484
485 it("drops what was queued when a signal appears mid-session, and counts as before without one", async () => {
486 let signal = false;
487 const storage = memoryStorage();
488 const { recorder, sent } = recorderWith(storage, [], () => NOW, () => signal);
489 recorder.record("page_view");
490 expect(recorder.pending().page_view).toBe(1);
491 signal = true;
492 await recorder.flush();
493 expect(sent).toEqual([]);
494 expect(storage.data.size).toBe(0);
495 signal = false;
496 recorder.record("page_view");
497 await recorder.flush();
498 expect(sent).toHaveLength(1);
499 expect(storage.data.has(INSTALL_STORAGE_KEY)).toBe(true);
500 });
501 });
502
503 describe("forwarder and browser privacy signals", () => {
504 const envelope = buildEnvelope({ counters: { ...emptyCounters(), page_view: 1 }, installId: UUID, appVersion: "0.9.12", surface: "website", now: NOW });
505
506 it.each([["Sec-GPC"], ["DNT"]])("answers %s: 1 as disabled before reading the body and forwards nothing", async (header) => {
507 let bodyRead = false;
508 const body = new ReadableStream<Uint8Array>({
509 pull(controller) {
510 bodyRead = true;
511 controller.enqueue(new TextEncoder().encode(JSON.stringify(envelope)));
512 controller.close();
513 },
514 }, { highWaterMark: 0 });
515 const request = new Request("http://localhost/api/product-telemetry", {
516 method: "POST",
517 headers: { "content-type": "application/json", [header]: "1" },
518 body,
519 duplex: "half",
520 } as RequestInit);
521 let forwarded = 0;
522 const response = await handleProductTelemetry(request, {
523 ingestUrl: CANONICAL_INGEST_URL,
524 forward: async () => {
525 forwarded += 1;
526 return { ok: true };
527 },
528 });
529 expect(response.status).toBe(200);
530 expect(await response.json()).toEqual({ accepted: false, reason: "disabled" });
531 expect(bodyRead).toBe(false);
532 expect(forwarded).toBe(0);
533 });
534
535 it("still forwards a valid batch when the signals are absent or zero", async () => {
536 for (const headers of [{} as Record<string, string>, { "sec-gpc": "0", dnt: "0" }]) {
537 let forwarded = 0;
538 const response = await handleProductTelemetry(
539 new Request("http://localhost/api/product-telemetry", {
540 method: "POST",
541 headers: { "content-type": "application/json", ...headers },
542 body: JSON.stringify(envelope),
543 }),
544 { ingestUrl: CANONICAL_INGEST_URL, forward: async () => ((forwarded += 1), { ok: true }) },
545 );
546 expect(await response.json()).toEqual({ accepted: true });
547 expect(forwarded).toBe(1);
548 }
549 });
550 });
551
551 lines TYPESCRIPT