Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: consume consent-aware website PostHog handoff (#16976)

Rohit Malhotraa8c05584ec6b
diff --git a/__tests__/components/providers/telemetry-provider.test.tsx b/__tests__/components/providers/telemetry-provider.test.tsx
index 9949d1d432..a3a24e51ae 100644
--- a/__tests__/components/providers/telemetry-provider.test.tsx
+++ b/__tests__/components/providers/telemetry-provider.test.tsx
@@ -16,10 +16,21 @@ const runtimeConfig = {
uiHost: "https://posthog.example.com",
};
+function encodeHandoff(value: unknown): string {
+ const encoded = btoa(
+ encodeURIComponent(JSON.stringify(value)).replace(
+ /%([0-9A-F]{2})/g,
+ (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)),
+ ),
+ );
+ return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
+}
+
describe("TelemetryProvider", () => {
let configureBootstrapMock: ReturnType<typeof vi.spyOn>;
let configureTelemetryMock: ReturnType<typeof vi.spyOn>;
let initializeClientMock: ReturnType<typeof vi.spyOn>;
+ let setWebsiteAttributionMock: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
configureBootstrapMock = vi
@@ -31,8 +42,12 @@ describe("TelemetryProvider", () => {
initializeClientMock = vi
.spyOn(telemetry, "initializePostHogClient")
.mockResolvedValue(null);
+ setWebsiteAttributionMock = vi
+ .spyOn(telemetry, "setTelemetryWebsiteAttribution")
+ .mockImplementation(() => undefined);
useTelemetryMock.mockClear();
window.location.hash = "";
+ localStorage.clear();
sessionStorage.clear();
});
@@ -85,6 +100,216 @@ describe("TelemetryProvider", () => {
});
});
+ it("consumes structured website handoff IDs and attribution from the URL", () => {
+ window.location.hash = `oh_ph_handoff=${encodeHandoff({
+ v: 1,
+ exp: Date.now() + 60_000,
+ nonce: "nonce-structured",
+ distinct_id: "website-anon-id",
+ session_id: "website-session-id",
+ attribution: {
+ utm_source: "newsletter",
+ utm_medium: "email",
+ utm_campaign: "launch",
+ landing_page_category: "home",
+ cta_id: "hero-cloud",
+ cta_surface: "homepage_hero",
+ referring_domain_category: "search",
+ full_url: "https://www.openhands.dev/?secret=value",
+ },
+ })}`;
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div data-testid="child" />
+ </TelemetryProvider>,
+ );
+
+ expect(configureBootstrapMock).toHaveBeenCalledWith({
+ distinctID: "website-anon-id",
+ sessionID: "website-session-id",
+ });
+ expect(setWebsiteAttributionMock).toHaveBeenCalledWith({
+ utm_source: "newsletter",
+ utm_medium: "email",
+ utm_campaign: "launch",
+ landing_page_category: "home",
+ cta_id: "hero-cloud",
+ cta_surface: "homepage_hero",
+ referring_domain_category: "search",
+ });
+ expect(window.location.hash).toBe("");
+ });
+
+ it("consumes structured website handoff IDs from query params", () => {
+ const encoded = encodeHandoff({
+ v: 1,
+ exp: Date.now() + 60_000,
+ nonce: "nonce-query",
+ distinct_id: "docs-anon-id",
+ session_id: "docs-session-id",
+ attribution: { cta_surface: "docs_link" },
+ });
+ window.history.replaceState(
+ null,
+ "",
+ `/canvas?keep=1&oh_ph_handoff=${encoded}#section=top`,
+ );
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+
+ expect(configureBootstrapMock).toHaveBeenCalledWith({
+ distinctID: "docs-anon-id",
+ sessionID: "docs-session-id",
+ });
+ expect(setWebsiteAttributionMock).toHaveBeenCalledWith({
+ cta_surface: "docs_link",
+ });
+ expect(window.location.search).toBe("?keep=1");
+ expect(window.location.hash).toBe("#section=top");
+ });
+
+ it("drops malformed or expired handoffs and removes them from the URL", () => {
+ window.location.hash = `oh_ph_handoff=${encodeHandoff({
+ v: 1,
+ exp: Date.now() - 1,
+ nonce: "nonce-expired",
+ distinct_id: "website-anon-id",
+ session_id: "website-session-id",
+ })}`;
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+
+ expect(configureBootstrapMock).toHaveBeenCalledWith(undefined);
+ expect(setWebsiteAttributionMock).toHaveBeenCalledWith(undefined);
+ expect(window.location.hash).toBe("");
+ });
+
+ it("falls back to a stored handoff when a forwarded URL nonce was already consumed", () => {
+ const encoded = encodeHandoff({
+ v: 1,
+ exp: Date.now() + 60_000,
+ nonce: "nonce-forwarded",
+ distinct_id: "url-docs-id",
+ session_id: "url-docs-session",
+ attribution: { cta_surface: "docs_link" },
+ });
+ localStorage.setItem(
+ "posthog_bootstrap:consumed_nonces",
+ JSON.stringify({ "nonce-forwarded": Date.now() + 60_000 }),
+ );
+ sessionStorage.setItem(
+ "posthog_bootstrap",
+ JSON.stringify({
+ bootstrap: { distinctID: "stored-docs-id", sessionID: "stored-session" },
+ exp: Date.now() + 60_000,
+ attribution: { cta_surface: "docs_link" },
+ }),
+ );
+ window.history.replaceState(
+ null,
+ "",
+ `/canvas?oh_ph_handoff=${encoded}`,
+ );
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+
+ expect(configureBootstrapMock).toHaveBeenCalledWith({
+ distinctID: "stored-docs-id",
+ sessionID: "stored-session",
+ });
+ expect(setWebsiteAttributionMock).toHaveBeenCalledWith({
+ cta_surface: "docs_link",
+ });
+ expect(window.location.search).toBe("");
+ expect(sessionStorage.getItem("posthog_bootstrap")).toBeNull();
+ });
+
+ it("prevents replay of a consumed structured handoff URL", () => {
+ const encoded = encodeHandoff({
+ v: 1,
+ exp: Date.now() + 60_000,
+ nonce: "nonce-replay",
+ distinct_id: "website-anon-id",
+ session_id: "website-session-id",
+ });
+
+ window.location.hash = `oh_ph_handoff=${encoded}`;
+ const firstView = render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+ expect(configureBootstrapMock).toHaveBeenLastCalledWith({
+ distinctID: "website-anon-id",
+ sessionID: "website-session-id",
+ });
+
+ firstView.unmount();
+ configureBootstrapMock.mockClear();
+ setWebsiteAttributionMock.mockClear();
+ sessionStorage.clear();
+ window.location.hash = `oh_ph_handoff=${encoded}`;
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+
+ expect(configureBootstrapMock).toHaveBeenCalledWith(undefined);
+ expect(setWebsiteAttributionMock).toHaveBeenCalledWith(undefined);
+ });
+
+ it("stores consumed structured handoff nonces in a pruned bounded map", () => {
+ const now = Date.now();
+ localStorage.setItem(
+ "posthog_bootstrap:consumed_nonces",
+ JSON.stringify({
+ expired: now - 60_000,
+ ...Object.fromEntries(
+ Array.from({ length: 105 }, (_, index) => [
+ `existing-${index}`,
+ now + 10_000 + index,
+ ]),
+ ),
+ }),
+ );
+ window.location.hash = `oh_ph_handoff=${encodeHandoff({
+ v: 1,
+ exp: now + 120_000,
+ nonce: "bounded-new",
+ distinct_id: "website-anon-id",
+ session_id: "website-session-id",
+ })}`;
+
+ render(
+ <TelemetryProvider config={runtimeConfig}>
+ <div />
+ </TelemetryProvider>,
+ );
+
+ const stored = JSON.parse(
+ localStorage.getItem("posthog_bootstrap:consumed_nonces") ?? "{}",
+ );
+ expect(Object.keys(stored)).toHaveLength(100);
+ expect(stored.expired).toBeUndefined();
+ expect(stored["bounded-new"]).toBe(now + 120_000);
+ expect(localStorage.getItem("posthog_bootstrap:bounded-new")).toBeNull();
+ });
+
it("mounts telemetry lifecycle when analytics are enabled", () => {
render(
<TelemetryProvider config={runtimeConfig}>
diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.ts
index a6611437d6..814536328f 100644
--- a/__tests__/services/telemetry.test.ts
+++ b/__tests__/services/telemetry.test.ts
@@ -51,6 +51,7 @@ import {
setTelemetryBackendContext,
setTelemetryCloudContext,
setTelemetryConsent,
+ setTelemetryWebsiteAttribution,
setTelemetryIdentity,
subscribeTelemetryConsent,
trackEvent,
@@ -86,6 +87,7 @@ describe("Telemetry Service", () => {
);
await setTelemetryIdentity(null);
setTelemetryBackendContext({});
+ setTelemetryWebsiteAttribution(undefined);
});
afterEach(() => {
@@ -156,6 +158,15 @@ describe("Telemetry Service", () => {
agentServerVersion: "1.36.2",
automationSdkVersion: "1.36.3",
});
+ setTelemetryWebsiteAttribution({
+ utm_source: "newsletter",
+ utm_medium: "email",
+ utm_campaign: "launch",
+ landing_page_category: "home",
+ cta_id: "hero-cloud",
+ cta_surface: "homepage_hero",
+ referring_domain_category: "search",
+ });
expect(
config.before_send({
event: "backend_context_event",
@@ -169,6 +180,13 @@ describe("Telemetry Service", () => {
agent_server_version: "1.36.2",
automation_sdk_version: "1.36.3",
backend_version: "1.36.2",
+ utm_source: "newsletter",
+ utm_medium: "email",
+ utm_campaign: "launch",
+ landing_page_category: "home",
+ cta_id: "hero-cloud",
+ cta_surface: "homepage_hero",
+ referring_domain_category: "search",
custom: "value",
}),
});
@@ -600,16 +618,33 @@ describe("Telemetry Service", () => {
});
describe("clearTelemetryData", () => {
- it("clears all telemetry data from localStorage", async () => {
+ it("clears all telemetry data from browser storage", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
localStorage.setItem("openhands-telemetry-first-use", "true");
+ localStorage.setItem(
+ "posthog_bootstrap:consumed_nonces",
+ JSON.stringify({ "nonce-a": Date.now() + 60_000 }),
+ );
+ localStorage.setItem("posthog_bootstrap:legacy", "legacy");
+ sessionStorage.setItem(
+ "posthog_bootstrap",
+ JSON.stringify({
+ bootstrap: { distinctID: "website-anon", sessionID: "session-a" },
+ attribution: { cta_surface: "docs_link" },
+ }),
+ );
await clearTelemetryData();
expect(localStorage.getItem("openhands-telemetry-consent")).toBeNull();
expect(getPendingCloudTelemetryConsent()).toBeNull();
expect(localStorage.getItem("openhands-telemetry-first-use")).toBeNull();
+ expect(
+ localStorage.getItem("posthog_bootstrap:consumed_nonces"),
+ ).toBeNull();
+ expect(localStorage.getItem("posthog_bootstrap:legacy")).toBeNull();
+ expect(sessionStorage.getItem("posthog_bootstrap")).toBeNull();
expect(mockPosthog.reset).toHaveBeenCalledWith(true);
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
await expect(getTelemetryDistinctIdForConsentSync()).resolves.toBe(
diff --git a/src/components/providers/telemetry-provider.tsx b/src/components/providers/telemetry-provider.tsx
index ced175a0b8..bae2163adf 100644
--- a/src/components/providers/telemetry-provider.tsx
+++ b/src/components/providers/telemetry-provider.tsx
@@ -5,10 +5,36 @@ import {
configurePostHogBootstrap,
configureTelemetry,
initializePostHogClient,
+ setTelemetryWebsiteAttribution,
type TelemetryConfiguration,
+ type WebsiteHandoffAttribution,
} from "#/services/telemetry";
const POSTHOG_BOOTSTRAP_KEY = "posthog_bootstrap";
+const POSTHOG_HANDOFF_PARAM = "oh_ph_handoff";
+const CONSUMED_HANDOFF_NONCES_KEY = `${POSTHOG_BOOTSTRAP_KEY}:consumed_nonces`;
+const MAX_CONSUMED_HANDOFF_NONCES = 100;
+const consumedHandoffNonces = new Set<string>();
+
+type PostHogHandoff = {
+ bootstrap: BootstrapConfig;
+ attribution?: WebsiteHandoffAttribution;
+};
+
+type StoredHandoff = PostHogHandoff & {
+ exp?: number;
+ nonce?: string;
+};
+
+const ATTRIBUTION_KEYS = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "landing_page_category",
+ "cta_id",
+ "cta_surface",
+ "referring_domain_category",
+] as const;
function isBootstrapConfig(value: unknown): value is BootstrapConfig {
if (typeof value !== "object" || value === null) return false;
@@ -19,43 +45,227 @@ function isBootstrapConfig(value: unknown): value is BootstrapConfig {
);
}
-function readBootstrapIds(): BootstrapConfig | undefined {
- if (typeof window === "undefined" || typeof sessionStorage === "undefined") {
- return undefined;
+function safeSessionStorage(): Storage | null {
+ if (typeof window === "undefined") return null;
+
+ try {
+ return window.sessionStorage;
+ } catch {
+ return null;
}
+}
- const params = new URLSearchParams(window.location.hash.slice(1));
- const distinctID = params.get("distinct_id");
- const sessionID = params.get("session_id");
- if (distinctID && sessionID) {
- const bootstrap = { distinctID, sessionID };
- try {
- sessionStorage.setItem(POSTHOG_BOOTSTRAP_KEY, JSON.stringify(bootstrap));
- } catch {
- // OAuth continuity is best effort when browser storage is unavailable.
+function safeLocalStorage(): Storage | null {
+ if (typeof window === "undefined") return null;
+
+ try {
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+function base64UrlDecode(value: string): string {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
+ const decoded = atob(padded);
+ const encoded = Array.from(
+ decoded,
+ (char) => `%${char.charCodeAt(0).toString(16).padStart(2, "0")}`,
+ ).join("");
+ return decodeURIComponent(encoded);
+}
+
+function sanitizeAttribution(
+ value: unknown,
+): WebsiteHandoffAttribution | undefined {
+ if (typeof value !== "object" || value === null) return undefined;
+ const source = value as Record<string, unknown>;
+ const attribution: WebsiteHandoffAttribution = {};
+
+ for (const key of ATTRIBUTION_KEYS) {
+ const candidate = source[key];
+ if (typeof candidate === "string" && candidate.trim()) {
+ attribution[key] = candidate.trim().slice(0, 80);
}
+ }
+
+ return Object.keys(attribution).length > 0 ? attribution : undefined;
+}
+
+function pruneConsumedNonceMap(
+ nonces: Record<string, number>,
+ now = Date.now(),
+): Record<string, number> {
+ return Object.fromEntries(
+ Object.entries(nonces)
+ .filter(([, exp]) => Number.isFinite(exp) && exp >= now)
+ .sort(([, leftExp], [, rightExp]) => rightExp - leftExp)
+ .slice(0, MAX_CONSUMED_HANDOFF_NONCES),
+ );
+}
+
+function getConsumedNonceMap(): Record<string, number> {
+ const storage = safeLocalStorage();
+ if (!storage) return {};
+
+ try {
+ const stored = storage.getItem(CONSUMED_HANDOFF_NONCES_KEY);
+ if (!stored) return {};
+ const parsed: unknown = JSON.parse(stored);
+ if (typeof parsed !== "object" || parsed === null) return {};
+ return pruneConsumedNonceMap(parsed as Record<string, number>);
+ } catch {
+ return {};
+ }
+}
+
+function setConsumedNonceMap(nonces: Record<string, number>): void {
+ const storage = safeLocalStorage();
+ if (!storage) return;
+
+ try {
+ storage.setItem(
+ CONSUMED_HANDOFF_NONCES_KEY,
+ JSON.stringify(pruneConsumedNonceMap(nonces)),
+ );
+ } catch {
+ // In-memory replay protection still applies for this page lifetime.
+ }
+}
+
+function isHandoffNonceConsumed(nonce: string): boolean {
+ if (consumedHandoffNonces.has(nonce)) return true;
+ return Object.prototype.hasOwnProperty.call(getConsumedNonceMap(), nonce);
+}
+
+function markHandoffNonceConsumed(nonce: string, exp: number): void {
+ consumedHandoffNonces.add(nonce);
+ setConsumedNonceMap({
+ ...getConsumedNonceMap(),
+ [nonce]: exp,
+ });
+}
+
+function removeHandoffFromUrl(
+ searchParams: URLSearchParams,
+ hashParams: URLSearchParams,
+): void {
+ for (const params of [searchParams, hashParams]) {
+ params.delete(POSTHOG_HANDOFF_PARAM);
+ params.delete("distinct_id");
+ params.delete("session_id");
+ }
+
+ const nextSearch = searchParams.toString();
+ const nextHash = hashParams.toString();
+
+ try {
+ window.history.replaceState(
+ null,
+ "",
+ `${window.location.pathname}${nextSearch ? `?${nextSearch}` : ""}${nextHash ? `#${nextHash}` : ""}`,
+ );
+ } catch {
+ // Telemetry must never prevent the application from rendering.
+ }
+}
+
+function parseStructuredHandoff(encoded: string): StoredHandoff | undefined {
+ try {
+ const parsed: unknown = JSON.parse(base64UrlDecode(encoded));
+ if (typeof parsed !== "object" || parsed === null) return undefined;
+
+ const candidate = parsed as Record<string, unknown>;
+ if (candidate.v !== 1) return undefined;
+ if (typeof candidate.exp !== "number" || candidate.exp < Date.now())
+ return undefined;
+ if (typeof candidate.nonce !== "string" || !candidate.nonce)
+ return undefined;
+ if (isHandoffNonceConsumed(candidate.nonce)) return undefined;
+ if (typeof candidate.distinct_id !== "string" || !candidate.distinct_id)
+ return undefined;
+ if (typeof candidate.session_id !== "string" || !candidate.session_id)
+ return undefined;
+
+ const handoff = {
+ bootstrap: {
+ distinctID: candidate.distinct_id.slice(0, 256),
+ sessionID: candidate.session_id.slice(0, 256),
+ },
+ attribution: sanitizeAttribution(candidate.attribution),
+ exp: candidate.exp,
+ nonce: candidate.nonce,
+ };
+ markHandoffNonceConsumed(candidate.nonce, candidate.exp);
+ return handoff;
+ } catch {
+ return undefined;
+ }
+}
+
+function readHandoffFromUrl(): PostHogHandoff | null | undefined {
+ const hashParams = new URLSearchParams(window.location.hash.slice(1));
+ const searchParams = new URLSearchParams(window.location.search);
+ const structured =
+ hashParams.get(POSTHOG_HANDOFF_PARAM) ??
+ searchParams.get(POSTHOG_HANDOFF_PARAM);
+ const distinctID =
+ hashParams.get("distinct_id") ?? searchParams.get("distinct_id");
+ const sessionID =
+ hashParams.get("session_id") ?? searchParams.get("session_id");
+ if (!structured && !(distinctID && sessionID)) return undefined;
+
+ const handoff = structured
+ ? parseStructuredHandoff(structured)
+ : {
+ bootstrap: { distinctID: distinctID ?? "", sessionID: sessionID ?? "" },
+ };
+
+ if (handoff) {
try {
- window.history.replaceState(
- null,
- "",
- window.location.pathname + window.location.search,
+ safeSessionStorage()?.setItem(
+ POSTHOG_BOOTSTRAP_KEY,
+ JSON.stringify(handoff),
);
} catch {
- // Telemetry must never prevent the application from rendering.
+ // OAuth continuity is best effort when browser storage is unavailable.
}
- return bootstrap;
}
+ removeHandoffFromUrl(searchParams, hashParams);
+ return handoff ?? null;
+}
+
+function isStoredHandoff(value: unknown): value is StoredHandoff {
+ if (isBootstrapConfig(value)) return true;
+ if (typeof value !== "object" || value === null) return false;
+ const candidate = value as Record<string, unknown>;
+ return isBootstrapConfig(candidate.bootstrap);
+}
+
+function readStoredHandoff(): PostHogHandoff | undefined {
+ const storage = safeSessionStorage();
+ if (!storage) return undefined;
+
try {
- const stored = sessionStorage.getItem(POSTHOG_BOOTSTRAP_KEY);
+ const stored = storage.getItem(POSTHOG_BOOTSTRAP_KEY);
if (!stored) return undefined;
- sessionStorage.removeItem(POSTHOG_BOOTSTRAP_KEY);
+ storage.removeItem(POSTHOG_BOOTSTRAP_KEY);
const parsed: unknown = JSON.parse(stored);
- return isBootstrapConfig(parsed) ? parsed : undefined;
+ if (!isStoredHandoff(parsed)) return undefined;
+
+ if (isBootstrapConfig(parsed)) return { bootstrap: parsed };
+ if (typeof parsed.exp === "number" && parsed.exp < Date.now())
+ return undefined;
+ return {
+ bootstrap: parsed.bootstrap,
+ attribution: sanitizeAttribution(parsed.attribution),
+ };
} catch {
try {
- sessionStorage.removeItem(POSTHOG_BOOTSTRAP_KEY);
+ storage.removeItem(POSTHOG_BOOTSTRAP_KEY);
} catch {
// Ignore unavailable storage.
}
@@ -63,6 +273,13 @@ function readBootstrapIds(): BootstrapConfig | undefined {
}
}
+function readPostHogHandoff(): PostHogHandoff | undefined {
+ if (typeof window === "undefined") return undefined;
+ const urlHandoff = readHandoffFromUrl();
+ if (urlHandoff) return urlHandoff;
+ return readStoredHandoff();
+}
+
function TelemetryLifecycle() {
useTelemetry();
return null;
@@ -84,7 +301,9 @@ export function TelemetryProvider({
React.useLayoutEffect(() => {
configureTelemetry(analyticsEnabled ? { apiKey, apiHost, uiHost } : false);
if (!configuredBootstrap.current) {
- configurePostHogBootstrap(readBootstrapIds());
+ const handoff = readPostHogHandoff();
+ configurePostHogBootstrap(handoff?.bootstrap);
+ setTelemetryWebsiteAttribution(handoff?.attribution);
configuredBootstrap.current = true;
}
}, [analyticsEnabled, apiHost, apiKey, uiHost]);
diff --git a/src/services/telemetry.ts b/src/services/telemetry.ts
index d00d150986..d026e225db 100644
--- a/src/services/telemetry.ts
+++ b/src/services/telemetry.ts
@@ -58,6 +58,8 @@ const TELEMETRY_CONSENT_PENDING_LOCAL_REVOCATION_KEY =
const TELEMETRY_CONSENT_CHANGE_EVENT = "openhands-telemetry-consent-change";
const TELEMETRY_FIRST_USE_KEY = "openhands-telemetry-first-use";
const TELEMETRY_SESSION_KEY = "openhands-telemetry-session";
+const POSTHOG_BOOTSTRAP_STORAGE_PREFIX = "posthog_bootstrap";
+
const POSTHOG_INSTANCE_NAME = "agent-canvas";
const POSTHOG_PAGEVIEW_CAPTURE_MODE = "history_change";
@@ -87,6 +89,19 @@ export interface TelemetryConfig {
uiHost?: string;
}
+export type WebsiteHandoffAttribution = Partial<
+ Record<
+ | "utm_source"
+ | "utm_medium"
+ | "utm_campaign"
+ | "landing_page_category"
+ | "cta_id"
+ | "cta_surface"
+ | "referring_domain_category",
+ string
+ >
+>;
+
export type TelemetryConfiguration = TelemetryConfig | false;
export type TelemetryConsent = "granted" | "denied" | "pending";
@@ -103,6 +118,19 @@ let pendingBootstrap: BootstrapConfig | undefined;
let telemetryConfig: TelemetryConfig = {};
let telemetryDisabled = false;
+function removeStorageKeysWithPrefix(storage: Storage, prefix: string): void {
+ const keysToRemove: string[] = [];
+
+ for (let index = 0; index < storage.length; index += 1) {
+ const key = storage.key(index);
+ if (key?.startsWith(prefix)) keysToRemove.push(key);
+ }
+
+ for (const key of keysToRemove) {
+ storage.removeItem(key);
+ }
+}
+
/** Deployment-level opt-out injected by static-server.mjs (see file header). */
function isRuntimeDoNotTrackEnabled(): boolean {
return (
@@ -152,6 +180,13 @@ function getEventDeploymentKind(
let telemetryBackendContext = getBackendTelemetryProperties({});
let telemetryCloudContext = getCloudTelemetryProperties();
+let telemetryWebsiteAttribution: WebsiteHandoffAttribution = {};
+
+export function setTelemetryWebsiteAttribution(
+ attribution: WebsiteHandoffAttribution | undefined,
+): void {
+ telemetryWebsiteAttribution = attribution ?? {};
+}
export function setTelemetryBackendContext(
context: BackendTelemetryContextInput,
@@ -173,6 +208,7 @@ function addCanvasEventProperties(
const properties = {
...telemetryBackendContext,
...telemetryCloudContext,
+ ...telemetryWebsiteAttribution,
...event.properties,
};
@@ -887,18 +923,24 @@ export async function clearTelemetryData(): Promise<void> {
);
localStorage.removeItem(TELEMETRY_CONSENT_KEY);
localStorage.removeItem(TELEMETRY_FIRST_USE_KEY);
+ removeStorageKeysWithPrefix(localStorage, POSTHOG_BOOTSTRAP_STORAGE_PREFIX);
} catch {
// Continue clearing the in-memory and SDK identity if storage is blocked.
}
clearPendingCloudTelemetryConsent();
try {
sessionStorage.removeItem(TELEMETRY_SESSION_KEY);
+ removeStorageKeysWithPrefix(
+ sessionStorage,
+ POSTHOG_BOOTSTRAP_STORAGE_PREFIX,
+ );
} catch {
// Continue clearing the in-memory and SDK identity if storage is blocked.
}
telemetryBackendContext = getBackendTelemetryProperties({});
telemetryCloudContext = getCloudTelemetryProperties();
+ telemetryWebsiteAttribution = {};
desiredTelemetryIdentity = null;
desiredIdentityRevision += 1;
appliedIdentityRevision = -1;