@ciridae/telemetry 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # @ciridae/telemetry
2
+
3
+ Shared PostHog analytics, identity, replay, and privacy lifecycle for Ciridae frontends.
4
+
5
+ Install from npm:
6
+
7
+ ```bash
8
+ npm install @ciridae/telemetry
9
+ ```
10
+
11
+ Use the published package for new and updated consumers.
12
+
13
+ Create one telemetry facade and pass it to the optional React integration:
14
+
15
+ ```ts
16
+ import { createCiridaeTelemetry } from "@ciridae/telemetry/client";
17
+ import { CiridaeTelemetryProvider } from "@ciridae/telemetry/react";
18
+ ```
@@ -0,0 +1,3 @@
1
+ import type { CiridaeTelemetry } from "./createCiridaeTelemetry.js";
2
+ export declare const CiridaeTelemetryContext: import("@types/react").Context<CiridaeTelemetry | null>;
3
+ export declare function useCiridaeTelemetry(): CiridaeTelemetry;
@@ -0,0 +1,9 @@
1
+ import { createContext, useContext } from "react";
2
+ export const CiridaeTelemetryContext = createContext(null);
3
+ export function useCiridaeTelemetry() {
4
+ const telemetry = useContext(CiridaeTelemetryContext);
5
+ if (!telemetry) {
6
+ throw new Error("useCiridaeTelemetry must render below CiridaeTelemetryProvider.");
7
+ }
8
+ return telemetry;
9
+ }
@@ -0,0 +1,8 @@
1
+ import { type ReactNode } from "react";
2
+ import type { CiridaeTelemetry, TelemetryUser } from "./createCiridaeTelemetry.js";
3
+ export declare function CiridaeTelemetryProvider({ children, pathname, telemetry, user, }: {
4
+ children: ReactNode;
5
+ pathname: string;
6
+ telemetry: CiridaeTelemetry;
7
+ user: TelemetryUser | null | undefined;
8
+ }): import("@types/react").JSX.Element;
@@ -0,0 +1,19 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useSyncExternalStore } from "react";
3
+ import { CiridaeTelemetryContext } from "./CiridaeTelemetryContext.js";
4
+ import { isSensitiveTelemetryPath } from "./filterCapturedEvent.js";
5
+ export function CiridaeTelemetryProvider({ children, pathname, telemetry, user, }) {
6
+ const initialized = useSyncExternalStore(telemetry.subscribeToInitialization, telemetry.isInitialized, () => false);
7
+ useEffect(() => {
8
+ telemetry.initialize(pathname);
9
+ }, [pathname, telemetry]);
10
+ useEffect(() => {
11
+ if (!initialized || isSensitiveTelemetryPath(pathname) || user === undefined)
12
+ return;
13
+ if (user)
14
+ telemetry.identify(user);
15
+ else
16
+ telemetry.clearIdentity();
17
+ }, [initialized, pathname, telemetry, user]);
18
+ return (_jsx(CiridaeTelemetryContext.Provider, { value: telemetry, children: children }));
19
+ }
@@ -0,0 +1,23 @@
1
+ export type TelemetryUser = {
2
+ id: string;
3
+ name?: string | null;
4
+ email?: string | null;
5
+ emailVerified?: boolean;
6
+ };
7
+ export type CiridaeTelemetryConfiguration = {
8
+ posthogApiKey: string;
9
+ posthogApiHost?: string;
10
+ posthogUiHost?: string;
11
+ backendUrl?: string;
12
+ environment?: string;
13
+ projectId?: string;
14
+ };
15
+ export type CiridaeTelemetry = {
16
+ initialize(pathname: string): void;
17
+ isInitialized(): boolean;
18
+ subscribeToInitialization(subscriber: () => void): () => void;
19
+ identify(user: TelemetryUser): void;
20
+ clearIdentity(): void;
21
+ capture(eventName: string, properties?: Record<string, unknown>): void;
22
+ };
23
+ export declare function createCiridaeTelemetry(configuration: CiridaeTelemetryConfiguration): CiridaeTelemetry;
@@ -0,0 +1,136 @@
1
+ import posthog from "posthog-js";
2
+ import { filterCapturedEvent, isSensitiveTelemetryPath } from "./filterCapturedEvent.js";
3
+ import { maskSensitiveUrlParameters, SENSITIVE_URL_PARAMETER_NAMES, } from "./maskSensitiveUrlParameters.js";
4
+ const POSTHOG_US_API_HOST = "https://us.i.posthog.com";
5
+ const POSTHOG_US_UI_HOST = "https://us.posthog.com";
6
+ const POSTHOG_EU_API_HOST = "https://eu.i.posthog.com";
7
+ const POSTHOG_EU_UI_HOST = "https://eu.posthog.com";
8
+ export function createCiridaeTelemetry(configuration) {
9
+ let initialized = false;
10
+ let identifiedUser = null;
11
+ const initializationSubscribers = new Set();
12
+ function resetPostHog() {
13
+ if (!initialized)
14
+ return;
15
+ try {
16
+ posthog.reset();
17
+ }
18
+ catch (error) {
19
+ console.error("Error resetting PostHog:", error);
20
+ }
21
+ }
22
+ return {
23
+ initialize(pathname) {
24
+ if (initialized || isSensitiveTelemetryPath(pathname))
25
+ return;
26
+ if (!configuration.posthogApiKey.trim())
27
+ return;
28
+ posthog.init(configuration.posthogApiKey, buildPostHogConfiguration(configuration));
29
+ posthog.register({
30
+ environment: configuration.environment || "development",
31
+ source: "frontend",
32
+ ...(configuration.projectId ? { project_id: configuration.projectId } : {}),
33
+ });
34
+ initialized = true;
35
+ for (const subscriber of initializationSubscribers)
36
+ subscriber();
37
+ },
38
+ isInitialized() {
39
+ return initialized;
40
+ },
41
+ subscribeToInitialization(subscriber) {
42
+ initializationSubscribers.add(subscriber);
43
+ return () => initializationSubscribers.delete(subscriber);
44
+ },
45
+ identify(user) {
46
+ if (!initialized || sameUser(identifiedUser, user))
47
+ return;
48
+ if (identifiedUser && identifiedUser.id !== user.id)
49
+ resetPostHog();
50
+ posthog.identify(user.id, {
51
+ user_id: user.id,
52
+ ...(user.name ? { display_name: user.name } : {}),
53
+ ...(user.email ? { email: user.email } : {}),
54
+ ...(user.emailVerified === undefined ? {} : { email_verified: user.emailVerified }),
55
+ });
56
+ identifiedUser = user;
57
+ },
58
+ clearIdentity() {
59
+ if (!initialized)
60
+ return;
61
+ identifiedUser = null;
62
+ if (isPostHogIdentified())
63
+ resetPostHog();
64
+ },
65
+ capture(eventName, properties) {
66
+ if (!initialized)
67
+ return;
68
+ posthog.capture(eventName, properties);
69
+ },
70
+ };
71
+ }
72
+ function buildPostHogConfiguration(configuration) {
73
+ const apiHost = configuration.posthogApiHost || POSTHOG_US_API_HOST;
74
+ return {
75
+ api_host: apiHost,
76
+ ui_host: getPostHogUiHost(apiHost, configuration.posthogUiHost),
77
+ tracing_headers: getTracingHeaderHostnames(configuration.backendUrl),
78
+ defaults: "2026-05-30",
79
+ person_profiles: "identified_only",
80
+ autocapture: { capture_copied_text: true },
81
+ before_send: filterCapturedEvent,
82
+ mask_personal_data_properties: true,
83
+ custom_personal_data_properties: Array.from(SENSITIVE_URL_PARAMETER_NAMES),
84
+ capture_pageview: "history_change",
85
+ capture_pageleave: true,
86
+ capture_dead_clicks: true,
87
+ capture_performance: { web_vitals: true },
88
+ capture_exceptions: true,
89
+ enable_heatmaps: true,
90
+ loaded: exposePostHogOnWindow,
91
+ session_recording: {
92
+ maskAllInputs: true,
93
+ maskCapturedNetworkRequestFn: (request) => ({
94
+ ...request,
95
+ name: maskSensitiveUrlParameters(request.name),
96
+ }),
97
+ recordCrossOriginIframes: true,
98
+ },
99
+ cross_subdomain_cookie: false,
100
+ };
101
+ }
102
+ function sameUser(current, next) {
103
+ return (current?.id === next.id &&
104
+ current.name === next.name &&
105
+ current.email === next.email &&
106
+ current.emailVerified === next.emailVerified);
107
+ }
108
+ function getPostHogUiHost(apiHost, configuredUiHost) {
109
+ if (configuredUiHost)
110
+ return configuredUiHost;
111
+ if (apiHost.replace(/\/+$/, "") === POSTHOG_EU_API_HOST)
112
+ return POSTHOG_EU_UI_HOST;
113
+ return POSTHOG_US_UI_HOST;
114
+ }
115
+ function getTracingHeaderHostnames(backendUrl) {
116
+ if (!backendUrl?.trim())
117
+ return [];
118
+ try {
119
+ const hostname = new URL(backendUrl, window.location.origin).hostname;
120
+ return hostname ? [hostname] : [];
121
+ }
122
+ catch {
123
+ return [];
124
+ }
125
+ }
126
+ function exposePostHogOnWindow(client) {
127
+ Object.assign(window, { posthog: client });
128
+ }
129
+ function isPostHogIdentified() {
130
+ try {
131
+ return posthog._isIdentified();
132
+ }
133
+ catch {
134
+ return true;
135
+ }
136
+ }
@@ -0,0 +1,2 @@
1
+ export * from "../createCiridaeTelemetry.js";
2
+ export { maskSensitiveUrlParameters } from "../maskSensitiveUrlParameters.js";
@@ -0,0 +1,2 @@
1
+ export * from "../createCiridaeTelemetry.js";
2
+ export { maskSensitiveUrlParameters } from "../maskSensitiveUrlParameters.js";
@@ -0,0 +1,3 @@
1
+ export * from "../CiridaeTelemetryProvider.js";
2
+ export * from "../CiridaeTelemetryContext.js";
3
+ export type { CiridaeTelemetry, TelemetryUser } from "../createCiridaeTelemetry.js";
@@ -0,0 +1,2 @@
1
+ export * from "../CiridaeTelemetryProvider.js";
2
+ export * from "../CiridaeTelemetryContext.js";
@@ -0,0 +1,3 @@
1
+ import type { CaptureResult } from "posthog-js";
2
+ export declare function isSensitiveTelemetryPath(pathname: string | undefined): boolean;
3
+ export declare function filterCapturedEvent(event: CaptureResult | null): CaptureResult | null;
@@ -0,0 +1,54 @@
1
+ import { maskSensitiveUrlParameters } from "./maskSensitiveUrlParameters.js";
2
+ const SIGN_IN_CALLBACK_PATH = "/signincallback";
3
+ const DIRECT_REFERRER_VALUE = "$direct";
4
+ const URL_PROPERTIES_TO_MASK = [
5
+ "$current_url",
6
+ "$referrer",
7
+ "$initial_current_url",
8
+ "$initial_referrer",
9
+ "$session_entry_url",
10
+ "$session_entry_referrer",
11
+ ];
12
+ const REFERRER_DOMAIN_PROPERTY_PAIRS = [
13
+ ["$referrer", "$referring_domain"],
14
+ ["$initial_referrer", "$initial_referring_domain"],
15
+ ["$session_entry_referrer", "$session_entry_referring_domain"],
16
+ ];
17
+ export function isSensitiveTelemetryPath(pathname) {
18
+ return (pathname === SIGN_IN_CALLBACK_PATH || Boolean(pathname?.startsWith(`${SIGN_IN_CALLBACK_PATH}/`)));
19
+ }
20
+ export function filterCapturedEvent(event) {
21
+ if (!event)
22
+ return null;
23
+ if (isSensitiveRouteUrl(event.properties.$current_url))
24
+ return null;
25
+ let properties = event.properties;
26
+ for (const propertyName of URL_PROPERTIES_TO_MASK) {
27
+ const value = properties[propertyName];
28
+ if (typeof value !== "string")
29
+ continue;
30
+ const maskedValue = maskSensitiveUrlParameters(value);
31
+ if (maskedValue !== value)
32
+ properties = { ...properties, [propertyName]: maskedValue };
33
+ }
34
+ for (const [referrerProperty, domainProperty] of REFERRER_DOMAIN_PROPERTY_PAIRS) {
35
+ if (!isSensitiveRouteUrl(properties[referrerProperty]))
36
+ continue;
37
+ properties = {
38
+ ...properties,
39
+ [referrerProperty]: DIRECT_REFERRER_VALUE,
40
+ [domainProperty]: DIRECT_REFERRER_VALUE,
41
+ };
42
+ }
43
+ return properties === event.properties ? event : { ...event, properties };
44
+ }
45
+ function isSensitiveRouteUrl(value) {
46
+ if (typeof value !== "string")
47
+ return false;
48
+ try {
49
+ return isSensitiveTelemetryPath(new URL(value, "https://ciridae-telemetry.local").pathname);
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
@@ -0,0 +1,2 @@
1
+ export declare const SENSITIVE_URL_PARAMETER_NAMES: readonly ["customToken", "redirect_path", "token", "auth", "email", "code", "state", "id_token", "access_token", "refresh_token", "session", "session_id", "api_key", "key"];
2
+ export declare function maskSensitiveUrlParameters(url: string): string;
@@ -0,0 +1,100 @@
1
+ const REDACTED_URL_PARAMETER_VALUE = "[REDACTED]";
2
+ const URL_BASE_FOR_RELATIVE_PATHS = "https://ciridae-telemetry.local";
3
+ export const SENSITIVE_URL_PARAMETER_NAMES = [
4
+ "customToken",
5
+ "redirect_path",
6
+ "token",
7
+ "auth",
8
+ "email",
9
+ "code",
10
+ "state",
11
+ "id_token",
12
+ "access_token",
13
+ "refresh_token",
14
+ "session",
15
+ "session_id",
16
+ "api_key",
17
+ "key",
18
+ ];
19
+ const sensitiveUrlParameterNames = new Set(SENSITIVE_URL_PARAMETER_NAMES.map((name) => name.toLowerCase()));
20
+ export function maskSensitiveUrlParameters(url) {
21
+ if (!url.includes("?") && !url.includes("#"))
22
+ return url;
23
+ try {
24
+ const shape = getUrlShape(url);
25
+ const parsedUrl = new URL(url, URL_BASE_FOR_RELATIVE_PATHS);
26
+ parsedUrl.search = maskUrlSearch(parsedUrl.search);
27
+ parsedUrl.hash = maskUrlHash(parsedUrl.hash);
28
+ return restoreUrlShape(parsedUrl, shape);
29
+ }
30
+ catch {
31
+ return url;
32
+ }
33
+ }
34
+ function getUrlShape(url) {
35
+ if (/^[a-z][a-z\d+.-]*:/i.test(url))
36
+ return "absolute";
37
+ if (url.startsWith("//"))
38
+ return "protocolRelative";
39
+ if (url.startsWith("/"))
40
+ return "path";
41
+ if (url.startsWith("?"))
42
+ return "query";
43
+ if (url.startsWith("#"))
44
+ return "hash";
45
+ return "relative";
46
+ }
47
+ function restoreUrlShape(url, shape) {
48
+ const path = decodeRedactedMarker(`${url.pathname}${url.search}${url.hash}`);
49
+ if (shape === "absolute")
50
+ return decodeRedactedMarker(url.toString());
51
+ if (shape === "protocolRelative")
52
+ return `//${url.host}${path}`;
53
+ if (shape === "path")
54
+ return path;
55
+ if (shape === "query")
56
+ return decodeRedactedMarker(`${url.search}${url.hash}`);
57
+ if (shape === "hash")
58
+ return decodeRedactedMarker(url.hash);
59
+ return path.startsWith("/") ? path.slice(1) : path;
60
+ }
61
+ function maskUrlSearch(search) {
62
+ if (!search)
63
+ return search;
64
+ const prefix = search.startsWith("?") ? "?" : "";
65
+ const parameters = new URLSearchParams(prefix ? search.slice(1) : search);
66
+ const maskedParameters = new URLSearchParams();
67
+ let hasRedaction = false;
68
+ for (const [name, value] of parameters.entries()) {
69
+ if (sensitiveUrlParameterNames.has(name.toLowerCase())) {
70
+ maskedParameters.append(name, REDACTED_URL_PARAMETER_VALUE);
71
+ hasRedaction = true;
72
+ }
73
+ else {
74
+ maskedParameters.append(name, value);
75
+ }
76
+ }
77
+ if (!hasRedaction)
78
+ return search;
79
+ const serializedParameters = decodeRedactedMarker(maskedParameters.toString());
80
+ return serializedParameters ? `${prefix}${serializedParameters}` : search;
81
+ }
82
+ function maskUrlHash(hash) {
83
+ if (!hash)
84
+ return hash;
85
+ const prefix = hash.startsWith("#") ? "#" : "";
86
+ const value = prefix ? hash.slice(1) : hash;
87
+ if (!value)
88
+ return hash;
89
+ const queryStartIndex = value.indexOf("?");
90
+ if (queryStartIndex !== -1) {
91
+ return `${prefix}${value.slice(0, queryStartIndex)}?${maskUrlSearch(value.slice(queryStartIndex + 1))}`;
92
+ }
93
+ if (!value.includes("="))
94
+ return hash;
95
+ const maskedParameters = maskUrlSearch(value);
96
+ return maskedParameters === value ? hash : `${prefix}${maskedParameters}`;
97
+ }
98
+ function decodeRedactedMarker(value) {
99
+ return value.replace(/%5bredacted%5d/gi, () => REDACTED_URL_PARAMETER_VALUE);
100
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@ciridae/telemetry",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "private": false,
6
+ "engines": {
7
+ "node": ">=22.18"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/ciridae-ai/ciridae.git",
12
+ "directory": "packages/telemetry"
13
+ },
14
+ "homepage": "https://github.com/ciridae-ai/ciridae#readme",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "exports": {
19
+ "./package.json": "./package.json",
20
+ "./*": {
21
+ "types": "./dist/entries/*.d.ts",
22
+ "default": "./dist/entries/*.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "peerDependencies": {
30
+ "@types/react": ">=18",
31
+ "react": ">=18"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "@types/react": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "dependencies": {
39
+ "posthog-js": "1.398.2"
40
+ }
41
+ }