Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions frontend/instrumentation-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import posthog from "posthog-js";
import {
browserRequestsNoTracking,
classifyClientErrorName,
getPostHogConfig,
sanitizeEvent,
Expand All @@ -12,6 +13,11 @@ const posthogConfig = getPostHogConfig({
NEXT_PUBLIC_POSTHOG_UI_HOST: process.env.NEXT_PUBLIC_POSTHOG_UI_HOST,
});

// Computed once. posthog-js treats cookieless_mode "always" as capturing before
// it checks respect_dnt, so DNT and GPC visitors never get posthog.init at all.
const trackingOptedOut =
typeof window !== "undefined" && browserRequestsNoTracking(window.navigator, window);

function capturePageview(url: string) {
posthog.capture("$pageview", { path: sanitizeRoute(url) });
}
Expand All @@ -31,7 +37,7 @@ function captureClientError(errorKind: "error" | "unhandled_rejection", cause: u
});
}

if (typeof window !== "undefined" && posthogConfig) {
if (typeof window !== "undefined" && posthogConfig && !trackingOptedOut) {
posthog.init(posthogConfig.token, {
api_host: posthogConfig.apiHost,
ui_host: posthogConfig.uiHost,
Expand Down Expand Up @@ -77,7 +83,10 @@ if (typeof window !== "undefined" && posthogConfig) {
web_vitals_allowed_metrics: ["CLS", "FCP", "INP", "LCP"],
web_vitals_attribution: false,
},
before_send: (event) => sanitizeEvent(event) as typeof event | null,
before_send: (event) =>
browserRequestsNoTracking(window.navigator, window)
? null
: (sanitizeEvent(event) as typeof event | null),
});

window.addEventListener("error", (event) => captureClientError("error", event.error));
Expand All @@ -89,5 +98,5 @@ if (typeof window !== "undefined" && posthogConfig) {
}

export function onRouterTransitionStart(url: string) {
if (typeof window !== "undefined" && posthogConfig) capturePageview(url);
if (typeof window !== "undefined" && posthogConfig && !trackingOptedOut) capturePageview(url);
}
29 changes: 29 additions & 0 deletions frontend/lib/posthog-privacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,35 @@ export function getPostHogConfig(env: PostHogEnvironment) {
return { token, apiHost: POSTHOG_API_HOST, uiHost: POSTHOG_UI_HOST } as const;
}

function readSignal(source: unknown, key: string): unknown {
if (source === null || (typeof source !== "object" && typeof source !== "function")) {
return undefined;
}
try {
return (source as Record<string, unknown>)[key];
} catch {
return undefined;
}
}

function isYesLike(value: unknown, accepted: readonly string[]): boolean {
if (value === true) return true;
return typeof value === "string" && accepted.includes(value.toLowerCase());
}

// posthog-js's is_capturing() returns true under cookieless_mode "always"
// before it consults respect_dnt, so the browser's opt-out signals have to be
// checked here instead. A throwing getter counts as no signal.
export function browserRequestsNoTracking(nav: unknown, win?: unknown): boolean {
const dnt = ["1", "yes"] as const;
return (
isYesLike(readSignal(nav, "doNotTrack"), dnt) ||
isYesLike(readSignal(nav, "msDoNotTrack"), dnt) ||
isYesLike(readSignal(win, "doNotTrack"), dnt) ||
isYesLike(readSignal(nav, "globalPrivacyControl"), ["1", "true", "yes"])
);
}

export function sanitizeRoute(input: unknown): string {
if (typeof input !== "string" || /^[a-z][a-z\d+.-]*:/i.test(input) || input.startsWith("//")) {
return OTHER_PATH;
Expand Down
21 changes: 21 additions & 0 deletions frontend/test/posthog-source.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,24 @@ test("newsletter submissions report a fixed result and error class only", async
assert.equal(calls.length, 3);
for (const [call] of calls) assert.doesNotMatch(call, /email|message|data\./iu);
});

test("init, listeners and pageviews sit behind the DNT/GPC guard, and before_send re-checks it", async () => {
const instrumentation = await read("instrumentation-client.ts");
assert.match(
instrumentation,
/const trackingOptedOut =[\s\S]*?browserRequestsNoTracking\(window\.navigator, window\)/u,
);
assert.match(
instrumentation,
/if \(typeof window !== "undefined" && posthogConfig && !trackingOptedOut\) \{\s*posthog\.init\(/u,
);
assert.match(
instrumentation,
/onRouterTransitionStart\(url: string\) \{\s*if \(typeof window !== "undefined" && posthogConfig && !trackingOptedOut\)/u,
);
const beforeSend =
instrumentation.match(/before_send: \(event\) =>[\s\S]*?\n\s*\}\);/u)?.[0] ?? "";
assert.match(beforeSend, /browserRequestsNoTracking\(window\.navigator, window\)/u);
assert.match(beforeSend, /\? null/u);
assert.match(instrumentation, /respect_dnt: true/u);
});
49 changes: 49 additions & 0 deletions frontend/test/posthog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import { type TestContext, test } from "node:test";
import {
ALLOWED_CTA_IDS,
ALLOWED_ROUTES,
browserRequestsNoTracking,
classifyClientErrorName,
getPostHogConfig,
sanitizeEvent,
Expand Down Expand Up @@ -864,3 +865,51 @@ test("the public PostHog pipeline stops events rejected by before_send", (t) =>
const capture = createSdkCapture(t);
assert.equal(capture({ event: "private fixture", properties: ENVELOPE }), undefined);
});

test("browser opt-out signals are detected", () => {
assert.equal(browserRequestsNoTracking({ doNotTrack: "1" }), true);
assert.equal(browserRequestsNoTracking({ doNotTrack: "yes" }), true);
assert.equal(browserRequestsNoTracking({ doNotTrack: "YES" }), true);
assert.equal(browserRequestsNoTracking({ msDoNotTrack: "1" }), true);
assert.equal(browserRequestsNoTracking({}, { doNotTrack: "1" }), true);
assert.equal(browserRequestsNoTracking({}, { doNotTrack: true }), true);
assert.equal(browserRequestsNoTracking({ globalPrivacyControl: true }), true);
assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "1" }), true);
assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "true" }), true);
});

test("browsers without an opt-out signal are not flagged", () => {
for (const value of ["0", "unspecified", "no", "", null, undefined, 0, false]) {
assert.equal(browserRequestsNoTracking({ doNotTrack: value }), false, String(value));
assert.equal(browserRequestsNoTracking({}, { doNotTrack: value }), false, String(value));
}
assert.equal(browserRequestsNoTracking({ globalPrivacyControl: false }), false);
assert.equal(browserRequestsNoTracking({ globalPrivacyControl: "false" }), false);
assert.equal(browserRequestsNoTracking({}), false);
assert.equal(browserRequestsNoTracking(undefined), false);
assert.equal(browserRequestsNoTracking(null, null), false);
assert.equal(browserRequestsNoTracking("navigator", 42), false);
});

test("a throwing signal getter counts as no signal unless another says yes", () => {
const throwing = {
get doNotTrack(): string {
throw new Error("blocked");
},
};
assert.equal(browserRequestsNoTracking(throwing), false);
assert.equal(browserRequestsNoTracking(throwing, throwing), false);
assert.equal(browserRequestsNoTracking(throwing, { doNotTrack: "1" }), true);
const gpc = Object.defineProperties(
{},
{
doNotTrack: {
get() {
throw new Error("blocked");
},
},
globalPrivacyControl: { value: true },
},
);
assert.equal(browserRequestsNoTracking(gpc), true);
});
Loading