@ciridae/telemetry 0.2.1 → 0.3.1

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.
@@ -16,6 +16,8 @@ export type CiridaeTelemetryConfiguration = {
16
16
  backendUrl?: string;
17
17
  environment?: string;
18
18
  projectId?: string;
19
+ serviceName?: string;
20
+ serviceVersion?: string;
19
21
  };
20
22
  export type CiridaeTelemetry = {
21
23
  initialize(pathname: string): void;
@@ -1,6 +1,7 @@
1
1
  import posthog from "posthog-js";
2
2
  import { filterCapturedEvent, isSensitiveTelemetryPath } from "./filterCapturedEvent.js";
3
3
  import { maskSensitiveUrlParameters, SENSITIVE_URL_PARAMETER_NAMES, } from "./maskSensitiveUrlParameters.js";
4
+ import { redactCapturedLog } from "./redactCapturedLog.js";
4
5
  const POSTHOG_US_API_HOST = "https://us.i.posthog.com";
5
6
  const POSTHOG_US_UI_HOST = "https://us.posthog.com";
6
7
  const POSTHOG_EU_API_HOST = "https://eu.i.posthog.com";
@@ -13,6 +14,13 @@ export function createCiridaeTelemetry(configuration) {
13
14
  initializationSubscribers.add(subscriber);
14
15
  return () => initializationSubscribers.delete(subscriber);
15
16
  }
17
+ function registerEventAttribution() {
18
+ posthog.register({
19
+ environment: configuration.environment || "development",
20
+ source: "frontend",
21
+ ...(configuration.projectId ? { project_id: configuration.projectId } : {}),
22
+ });
23
+ }
16
24
  function resetPostHog() {
17
25
  if (!initialized)
18
26
  return;
@@ -22,6 +30,8 @@ export function createCiridaeTelemetry(configuration) {
22
30
  catch (error) {
23
31
  console.error("Error resetting PostHog:", error);
24
32
  }
33
+ // reset() clears registered properties along with the identity.
34
+ registerEventAttribution();
25
35
  }
26
36
  const productCapabilities = createPostHogProductCapabilities(() => initialized, subscribeToInitialization);
27
37
  return {
@@ -31,11 +41,10 @@ export function createCiridaeTelemetry(configuration) {
31
41
  if (!configuration.posthogApiKey.trim())
32
42
  return;
33
43
  posthog.init(configuration.posthogApiKey, buildPostHogConfiguration(configuration));
34
- posthog.register({
35
- environment: configuration.environment || "development",
36
- source: "frontend",
37
- ...(configuration.projectId ? { project_id: configuration.projectId } : {}),
38
- });
44
+ registerEventAttribution();
45
+ if (configuration.serviceName) {
46
+ posthog.logger.info("PostHog log ingestion canary", { telemetry_canary: true });
47
+ }
39
48
  initialized = true;
40
49
  for (const subscriber of initializationSubscribers)
41
50
  subscriber();
@@ -154,6 +163,23 @@ function buildPostHogConfiguration(configuration) {
154
163
  capture_dead_clicks: true,
155
164
  capture_performance: { web_vitals: true },
156
165
  capture_exceptions: true,
166
+ ...(configuration.serviceName
167
+ ? {
168
+ logs: {
169
+ serviceName: configuration.serviceName,
170
+ environment: configuration.environment || "development",
171
+ resourceAttributes: {
172
+ source: "frontend",
173
+ ...(configuration.projectId ? { project_id: configuration.projectId } : {}),
174
+ },
175
+ ...(configuration.serviceVersion
176
+ ? { serviceVersion: configuration.serviceVersion }
177
+ : {}),
178
+ captureConsoleLogs: true,
179
+ beforeSend: redactCapturedLog,
180
+ },
181
+ }
182
+ : {}),
157
183
  enable_heatmaps: true,
158
184
  loaded: exposePostHogOnWindow,
159
185
  session_recording: {
@@ -176,7 +202,11 @@ function sameUser(current, next) {
176
202
  function getPostHogUiHost(apiHost, configuredUiHost) {
177
203
  if (configuredUiHost)
178
204
  return configuredUiHost;
179
- if (apiHost.replace(/\/+$/, "") === POSTHOG_EU_API_HOST)
205
+ let apiHostWithoutTrailingSlashes = apiHost;
206
+ while (apiHostWithoutTrailingSlashes.endsWith("/")) {
207
+ apiHostWithoutTrailingSlashes = apiHostWithoutTrailingSlashes.slice(0, -1);
208
+ }
209
+ if (apiHostWithoutTrailingSlashes === POSTHOG_EU_API_HOST)
180
210
  return POSTHOG_EU_UI_HOST;
181
211
  return POSTHOG_US_UI_HOST;
182
212
  }
@@ -0,0 +1,2 @@
1
+ import type { CaptureLogOptions } from "posthog-js";
2
+ export declare function redactCapturedLog(record: CaptureLogOptions): CaptureLogOptions;
@@ -0,0 +1,96 @@
1
+ import { SENSITIVE_URL_PARAMETER_NAMES } from "./maskSensitiveUrlParameters.js";
2
+ const REDACTED_LOG_VALUE = "[REDACTED]";
3
+ const MAX_LOG_ATTRIBUTE_DEPTH = 8;
4
+ const sensitiveLogFieldNames = new Set([
5
+ ...SENSITIVE_URL_PARAMETER_NAMES,
6
+ "authorization",
7
+ "cookie",
8
+ "credential",
9
+ "credentials",
10
+ "password",
11
+ "passwd",
12
+ "secret",
13
+ ].map(normalizeFieldName));
14
+ const SENSITIVE_ASSIGNMENT_PATTERN = /(["']?(?:authorization|cookie|credentials?|password|passwd|secret|session(?:[_-]?id)?|api[_ -]?key|access[_ -]?token|refresh[_ -]?token|id[_ -]?token|token)["']?\s*[:=]\s*)(?:Bearer\s+[\w.~+/=-]+|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;}\]]+)/gi;
15
+ const URL_PARAMETER_PATTERN = /([?&#])([^=?&#\s]+)=([^&#\s]+)/g;
16
+ const BEARER_TOKEN_PATTERN = /\b(Bearer\s+)[\w.~+/=-]+/gi;
17
+ const JSON_WEB_TOKEN_PATTERN = /\beyJ[\w-]+\.[\w-]+\.[\w-]*\b/g;
18
+ export function redactCapturedLog(record) {
19
+ return {
20
+ ...record,
21
+ body: redactSensitiveText(record.body),
22
+ ...(record.attributes
23
+ ? { attributes: redactLogAttributes(record.attributes, new WeakSet(), 0) }
24
+ : {}),
25
+ };
26
+ }
27
+ function redactLogAttributes(attributes, seenObjects, depth) {
28
+ return Object.fromEntries(Object.entries(attributes).map(([name, value]) => [
29
+ name,
30
+ isSensitiveLogFieldName(name)
31
+ ? REDACTED_LOG_VALUE
32
+ : redactLogAttributeValue(value, seenObjects, depth + 1),
33
+ ]));
34
+ }
35
+ function redactLogAttributeValue(value, seenObjects, depth) {
36
+ if (typeof value === "string")
37
+ return redactSensitiveText(value);
38
+ if (value === null ||
39
+ value === undefined ||
40
+ typeof value === "number" ||
41
+ typeof value === "boolean") {
42
+ return value;
43
+ }
44
+ if (typeof value !== "object")
45
+ return redactSensitiveText(String(value));
46
+ if (depth > MAX_LOG_ATTRIBUTE_DEPTH || seenObjects.has(value))
47
+ return REDACTED_LOG_VALUE;
48
+ seenObjects.add(value);
49
+ try {
50
+ if (Array.isArray(value)) {
51
+ return value.map((entry) => redactLogAttributeValue(entry, seenObjects, depth + 1));
52
+ }
53
+ if (!isLogAttributeRecord(value))
54
+ return REDACTED_LOG_VALUE;
55
+ return redactLogAttributes(value, seenObjects, depth);
56
+ }
57
+ finally {
58
+ seenObjects.delete(value);
59
+ }
60
+ }
61
+ function redactSensitiveText(value) {
62
+ return value
63
+ .replace(SENSITIVE_ASSIGNMENT_PATTERN, `$1${REDACTED_LOG_VALUE}`)
64
+ .replace(URL_PARAMETER_PATTERN, redactSensitiveUrlParameter)
65
+ .replace(BEARER_TOKEN_PATTERN, `$1${REDACTED_LOG_VALUE}`)
66
+ .replace(JSON_WEB_TOKEN_PATTERN, REDACTED_LOG_VALUE);
67
+ }
68
+ function isSensitiveLogFieldName(name) {
69
+ const normalizedName = normalizeFieldName(name);
70
+ return (sensitiveLogFieldNames.has(normalizedName) ||
71
+ normalizedName.endsWith("apikey") ||
72
+ normalizedName.endsWith("authorization") ||
73
+ normalizedName.endsWith("cookie") ||
74
+ normalizedName.endsWith("credential") ||
75
+ normalizedName.endsWith("credentials") ||
76
+ normalizedName.endsWith("token") ||
77
+ normalizedName.endsWith("password") ||
78
+ normalizedName.endsWith("secret"));
79
+ }
80
+ function redactSensitiveUrlParameter(match, prefix, encodedName) {
81
+ try {
82
+ const decodedName = decodeURIComponent(encodedName);
83
+ if (!sensitiveLogFieldNames.has(normalizeFieldName(decodedName)))
84
+ return match;
85
+ return `${prefix}${encodedName}=${REDACTED_LOG_VALUE}`;
86
+ }
87
+ catch {
88
+ return match;
89
+ }
90
+ }
91
+ function normalizeFieldName(name) {
92
+ return name.toLowerCase().replace(/[^a-z\d]/g, "");
93
+ }
94
+ function isLogAttributeRecord(value) {
95
+ return Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null;
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciridae/telemetry",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "engines": {