@open-mercato/telemetry 0.11.1-develop.8347.1.c2e2f21d36 → 0.11.1-develop.8350.1.e377eb9f50

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.
@@ -1,2 +1,2 @@
1
- [build:telemetry] found 32 entry points
1
+ [build:telemetry] found 34 entry points
2
2
  [build:telemetry] built successfully
@@ -2,8 +2,6 @@
2
2
  import * as React from "react";
3
3
  import { registerTelemetryErrorReporter } from "@open-mercato/shared/lib/telemetry/runtime";
4
4
  import { groupableCode } from "@open-mercato/shared/lib/telemetry/error-code";
5
- import { serializeError } from "../facade/serialize.js";
6
- import { redactAttributes } from "../facade/redact.js";
7
5
  import { createBackupHeaderPropagator } from "./propagator.js";
8
6
  let bootstrapped = false;
9
7
  let disposeErrorReporter;
@@ -22,7 +20,10 @@ async function startBrowserTelemetry(config) {
22
20
  { DocumentLoadInstrumentation },
23
21
  { FetchInstrumentation },
24
22
  { W3CTraceContextPropagator },
25
- { defaultTextMapSetter, SpanStatusCode }
23
+ { defaultTextMapSetter, SpanStatusCode },
24
+ { createRedactingSpanProcessor },
25
+ { serializeError },
26
+ { redactAttributes }
26
27
  ] = await Promise.all([
27
28
  import("@opentelemetry/sdk-trace-web"),
28
29
  import("@opentelemetry/sdk-trace-base"),
@@ -32,7 +33,10 @@ async function startBrowserTelemetry(config) {
32
33
  import("@opentelemetry/instrumentation-document-load"),
33
34
  import("@opentelemetry/instrumentation-fetch"),
34
35
  import("@opentelemetry/core"),
35
- import("@opentelemetry/api")
36
+ import("@opentelemetry/api"),
37
+ import("../provider/redacting-span-processor.js"),
38
+ import("../facade/serialize.js"),
39
+ import("../facade/redact.js")
36
40
  ]);
37
41
  const provider = new WebTracerProvider({
38
42
  resource: resourceFromAttributes({
@@ -46,12 +50,12 @@ async function startBrowserTelemetry(config) {
46
50
  root: new TraceIdRatioBasedSampler(config.samplingRatio)
47
51
  }),
48
52
  spanProcessors: [
49
- new BatchSpanProcessor(
53
+ createRedactingSpanProcessor(new BatchSpanProcessor(
50
54
  new OTLPTraceExporter({ url: config.endpoint }),
51
55
  // The interesting spans arrive in bursts around a navigation; a short delay keeps them
52
56
  // close together in the trace view without one request per span.
53
57
  { scheduledDelayMillis: 3e3, maxQueueSize: 512 }
54
- )
58
+ ))
55
59
  ]
56
60
  });
57
61
  provider.register({
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/browser/BrowserTelemetry.tsx"],
4
- "sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * The `/browser` entry and its pure serialization/redaction helpers must not\n * import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport { serializeError } from '../facade/serialize'\nimport { redactAttributes } from '../facade/redact'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\nlet disposeErrorReporter: (() => void) | undefined\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n disposeErrorReporter?.()\n disposeErrorReporter = undefined\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter, SpanStatusCode },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n ),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n\n const tracer = provider.getTracer('@open-mercato/telemetry/browser')\n return (error, context) => {\n const serialized = serializeError(error)\n const attributes = redactAttributes({ ...context?.attributes, module: context?.module })\n delete attributes['error.code']\n const code = groupableCode(context?.code)\n if (code) attributes['error.code'] = code\n const span = tracer.startSpan('browser.error', { attributes })\n try {\n span.recordException(serialized)\n span.setStatus({ code: SpanStatusCode.ERROR })\n } finally {\n span.end()\n }\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n const reporter = startBrowserTelemetry(config)\n const dispose = registerTelemetryErrorReporter((...args) => {\n void reporter.then((reportError) => reportError(...args)).catch(() => {})\n })\n disposeErrorReporter = dispose\n void reporter.catch(() => {\n dispose()\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
5
- "mappings": ";AAyBA,YAAY,WAAW;AACvB,SAAS,sCAA6D;AACtE,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AAEjC,SAAS,oCAAoC;AAG7C,IAAI,eAAe;AACnB,IAAI;AAMG,SAAS,iCAAuC;AACrD,yBAAuB;AACvB,yBAAuB;AACvB,iBAAe;AACjB;AAEA,eAAe,sBAAsB,QAA0E;AAC7G,QAAM;AAAA,IACJ,EAAE,kBAAkB;AAAA,IACpB,EAAE,oBAAoB,oBAAoB,yBAAyB;AAAA,IACnE,EAAE,kBAAkB;AAAA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AAU,aAAc;AAC7B,mBAAe;AACf,UAAM,WAAW,sBAAsB,MAAM;AAC7C,UAAM,UAAU,+BAA+B,IAAI,SAAS;AAC1D,WAAK,SAAS,KAAK,CAAC,gBAAgB,YAAY,GAAG,IAAI,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC1E,CAAC;AACD,2BAAuB;AACvB,SAAK,SAAS,MAAM,MAAM;AACxB,cAAQ;AAAA,IAEV,CAAC;AAAA,EACH,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;",
4
+ "sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * The `/browser` entry and its pure serialization/redaction helpers must not\n * import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\nlet disposeErrorReporter: (() => void) | undefined\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n disposeErrorReporter?.()\n disposeErrorReporter = undefined\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter, SpanStatusCode },\n { createRedactingSpanProcessor },\n { serializeError },\n { redactAttributes },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n import('../provider/redacting-span-processor'),\n import('../facade/serialize'),\n import('../facade/redact'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n createRedactingSpanProcessor(new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n )),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n\n const tracer = provider.getTracer('@open-mercato/telemetry/browser')\n return (error, context) => {\n const serialized = serializeError(error)\n const attributes = redactAttributes({ ...context?.attributes, module: context?.module })\n delete attributes['error.code']\n const code = groupableCode(context?.code)\n if (code) attributes['error.code'] = code\n const span = tracer.startSpan('browser.error', { attributes })\n try {\n span.recordException(serialized)\n span.setStatus({ code: SpanStatusCode.ERROR })\n } finally {\n span.end()\n }\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n const reporter = startBrowserTelemetry(config)\n const dispose = registerTelemetryErrorReporter((...args) => {\n void reporter.then((reportError) => reportError(...args)).catch(() => {})\n })\n disposeErrorReporter = dispose\n void reporter.catch(() => {\n dispose()\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
5
+ "mappings": ";AAyBA,YAAY,WAAW;AACvB,SAAS,sCAA6D;AACtE,SAAS,qBAAqB;AAE9B,SAAS,oCAAoC;AAG7C,IAAI,eAAe;AACnB,IAAI;AAMG,SAAS,iCAAuC;AACrD,yBAAuB;AACvB,yBAAuB;AACvB,iBAAe;AACjB;AAEA,eAAe,sBAAsB,QAA0E;AAC7G,QAAM;AAAA,IACJ,EAAE,kBAAkB;AAAA,IACpB,EAAE,oBAA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MAAM,CAAC;AAAA,IAC/C,UAAE;AACA,WAAK,IAAI;AAAA,IACX;AAAA,EACF;AACF;AAEA,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAOO,SAAS,iBAAiB,EAAE,OAAO,GAA8C;AACtF,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,UAAU,aAAc;AAC7B,mBAAe;AACf,UAAM,WAAW,sBAAsB,MAAM;AAC7C,UAAM,UAAU,+BAA+B,IAAI,SAAS;AAC1D,WAAK,SAAS,KAAK,CAAC,gBAAgB,YAAY,GAAG,IAAI,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC1E,CAAC;AACD,2BAAuB;AACvB,SAAK,SAAS,MAAM,MAAM;AACxB,cAAQ;AAAA,IAEV,CAAC;AAAA,EACH,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -4,18 +4,56 @@ const AUTH_SCHEME_RE = /\b(Bearer|Basic|ApiKey)\s+[A-Za-z0-9._~+/=-]+/gi;
4
4
  function redactPii(text) {
5
5
  return text.replace(EMAIL_RE, "[redacted-email]").replace(SECRET_HEADER_RE, (_match, name, separator) => `${name}${separator}[redacted]`).replace(AUTH_SCHEME_RE, (_match, scheme) => `${scheme} [redacted]`);
6
6
  }
7
+ const UUID_PATH_SEGMENT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ const URL_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set(["http.target", "http.url", "url.full", "url.path"]);
9
+ function redactQuery(query) {
10
+ return query.split("&").map((parameter) => {
11
+ const separator = parameter.indexOf("=");
12
+ return separator < 0 ? parameter : `${parameter.slice(0, separator)}=[redacted]`;
13
+ }).join("&");
14
+ }
15
+ function redactPathSegment(segment) {
16
+ if (/%(?![0-9a-f]{2})/i.test(segment)) return "[redacted]";
17
+ const decoded = segment.replace(
18
+ /%([0-9a-f]{2})/gi,
19
+ (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16))
20
+ );
21
+ return /^[A-Za-z0-9_-]{32,}$/.test(decoded) && !UUID_PATH_SEGMENT_RE.test(decoded) ? "[redacted]" : segment;
22
+ }
23
+ function redactUrl(url) {
24
+ const fragmentIndex = url.indexOf("#");
25
+ const withoutFragment = fragmentIndex < 0 ? url : url.slice(0, fragmentIndex);
26
+ const queryIndex = withoutFragment.indexOf("?");
27
+ const path = queryIndex < 0 ? withoutFragment : withoutFragment.slice(0, queryIndex);
28
+ const authority = /^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/]*/i.exec(path)?.[0] ?? "";
29
+ const userInfoEnd = authority.lastIndexOf("@");
30
+ const redactedAuthority = userInfoEnd < 0 ? authority : `${authority.slice(0, authority.indexOf("//") + 2)}${authority.slice(userInfoEnd + 1)}`;
31
+ const redactedPath = path.slice(authority.length).split("/").map(redactPathSegment).join("/");
32
+ const query = queryIndex < 0 ? "" : `?${redactQuery(withoutFragment.slice(queryIndex + 1))}`;
33
+ const fragment = fragmentIndex < 0 ? "" : "#[redacted]";
34
+ return `${redactedAuthority}${redactedPath}${query}${fragment}`;
35
+ }
36
+ function redactSpanName(name) {
37
+ return redactPii(name.split(/(\s+)/).map(
38
+ (part) => part.startsWith("/") || /^[a-z][a-z0-9+.-]{0,31}:\/\//i.test(part) ? redactUrl(part) : part
39
+ ).join(""));
40
+ }
7
41
  const SECRET_KEY_RE = /(authorization|cookie|password|passwd|\bpwd\b|secret|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|^token$|\bbearer\b|private[-_]?key|credential)/i;
8
42
  function redactAttributes(attributes) {
9
43
  const result = {};
10
44
  for (const [key, value] of Object.entries(attributes)) {
11
45
  if (SECRET_KEY_RE.test(key)) result[key] = "[redacted]";
12
- else if (typeof value === "string") result[key] = redactPii(value);
13
- else result[key] = value;
46
+ else if (typeof value === "string") {
47
+ const cleaned = key === "next.span_name" ? redactSpanName(value) : key === "url.query" ? redactQuery(value) : URL_ATTRIBUTE_KEYS.has(key) ? redactUrl(value) : value;
48
+ result[key] = redactPii(cleaned);
49
+ } else result[key] = value;
14
50
  }
15
51
  return result;
16
52
  }
17
53
  export {
18
54
  redactAttributes,
19
- redactPii
55
+ redactPii,
56
+ redactSpanName,
57
+ redactUrl
20
58
  };
21
59
  //# sourceMappingURL=redact.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/facade/redact.ts"],
4
- "sourcesContent": ["import type { Attributes } from '../types'\n\n/**\n * Active redaction backstop for telemetry (Privacy section of the telemetry spec).\n *\n * Defense-in-depth over the don't-emit posture: callers are expected not to put\n * PII or secrets into errors/logs, but error messages and stack frames can still\n * pick them up a layer down (e.g. `Error: no user for jan.kowalski@example.com`,\n * or a dumped `Authorization: Bearer \u2026` header). This scrubs the highest-signal\n * identifiers \u2014 email addresses and auth tokens \u2014 from any text that ships to the\n * backend, without touching opaque UUIDs/ids (which we keep).\n *\n * Deliberately conservative (emails + auth tokens) to preserve debuggability;\n * extend the pattern set here if a new leak vector is found.\n */\n// Bound every component both to match the practical limits from RFC 5321 and\n// to keep scanning time linear for hostile strings with long runs of email\n// punctuation (CodeQL js/polynomial-redos).\nconst EMAIL_RE = /[A-Z0-9._%+-]{1,64}@[A-Z0-9.-]{1,253}\\.[A-Z]{2,63}/gi\n// `authorization: <value>` / `cookie: <value>` header dumps embedded in free text.\n// The value runs to the next separator (`;`/`,`/`}`) or newline, so it swallows a\n// `Bearer <token>` value in one pass (before the standalone-scheme rule below).\nconst SECRET_HEADER_RE = /\\b(authorization|proxy-authorization|cookie|set-cookie)(\\s*[:=]\\s*)([^\\n;,}]+)/gi\n// `Bearer <token>` / `Basic <base64>` / `ApiKey <key>` standing alone in free text (message or stack).\nconst AUTH_SCHEME_RE = /\\b(Bearer|Basic|ApiKey)\\s+[A-Za-z0-9._~+/=-]+/gi\n\nexport function redactPii(text: string): string {\n return text\n .replace(EMAIL_RE, '[redacted-email]')\n .replace(SECRET_HEADER_RE, (_match, name: string, separator: string) => `${name}${separator}[redacted]`)\n .replace(AUTH_SCHEME_RE, (_match, scheme: string) => `${scheme} [redacted]`)\n}\n\n// Attribute KEYS whose value is a secret regardless of content. Intentionally\n// specific enough not to clobber benign fields like `token_count`, while\n// still masking the exact key `token`.\nconst SECRET_KEY_RE =\n /(authorization|cookie|password|passwd|\\bpwd\\b|secret|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|^token$|\\bbearer\\b|private[-_]?key|credential)/i\n\n/**\n * Redact a telemetry attribute bag before it ships: a value under a secret-looking\n * KEY (`authorization`, `set-cookie`, `client_secret`, `x-api-key`, \u2026) is masked\n * wholesale; other string values still pass through `redactPii` so an inline email\n * or auth token is caught too. Non-string values are left as-is.\n */\nexport function redactAttributes(attributes: Attributes): Attributes {\n const result: Attributes = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (SECRET_KEY_RE.test(key)) result[key] = '[redacted]'\n else if (typeof value === 'string') result[key] = redactPii(value)\n else result[key] = value\n }\n return result\n}\n"],
5
- "mappings": "AAkBA,MAAM,WAAW;AAIjB,MAAM,mBAAmB;AAEzB,MAAM,iBAAiB;AAEhB,SAAS,UAAU,MAAsB;AAC9C,SAAO,KACJ,QAAQ,UAAU,kBAAkB,EACpC,QAAQ,kBAAkB,CAAC,QAAQ,MAAc,cAAsB,GAAG,IAAI,GAAG,SAAS,YAAY,EACtG,QAAQ,gBAAgB,CAAC,QAAQ,WAAmB,GAAG,MAAM,aAAa;AAC/E;AAKA,MAAM,gBACJ;AAQK,SAAS,iBAAiB,YAAoC;AACnE,QAAM,SAAqB,CAAC;AAC5B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrD,QAAI,cAAc,KAAK,GAAG,EAAG,QAAO,GAAG,IAAI;AAAA,aAClC,OAAO,UAAU,SAAU,QAAO,GAAG,IAAI,UAAU,KAAK;AAAA,QAC5D,QAAO,GAAG,IAAI;AAAA,EACrB;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import type { Attributes } from '../types'\n\n/**\n * Active redaction backstop for telemetry (Privacy section of the telemetry spec).\n *\n * Defense-in-depth over the don't-emit posture: callers are expected not to put\n * PII or secrets into errors/logs, but error messages and stack frames can still\n * pick them up a layer down (e.g. `Error: no user for jan.kowalski@example.com`,\n * or a dumped `Authorization: Bearer \u2026` header). This scrubs the highest-signal\n * identifiers \u2014 email addresses and auth tokens \u2014 from any text that ships to the\n * backend, without touching opaque UUIDs/ids (which we keep).\n *\n * Deliberately conservative (emails + auth tokens) to preserve debuggability;\n * extend the pattern set here if a new leak vector is found.\n */\n// Bound every component both to match the practical limits from RFC 5321 and\n// to keep scanning time linear for hostile strings with long runs of email\n// punctuation (CodeQL js/polynomial-redos).\nconst EMAIL_RE = /[A-Z0-9._%+-]{1,64}@[A-Z0-9.-]{1,253}\\.[A-Z]{2,63}/gi\n// `authorization: <value>` / `cookie: <value>` header dumps embedded in free text.\n// The value runs to the next separator (`;`/`,`/`}`) or newline, so it swallows a\n// `Bearer <token>` value in one pass (before the standalone-scheme rule below).\nconst SECRET_HEADER_RE = /\\b(authorization|proxy-authorization|cookie|set-cookie)(\\s*[:=]\\s*)([^\\n;,}]+)/gi\n// `Bearer <token>` / `Basic <base64>` / `ApiKey <key>` standing alone in free text (message or stack).\nconst AUTH_SCHEME_RE = /\\b(Bearer|Basic|ApiKey)\\s+[A-Za-z0-9._~+/=-]+/gi\n\nexport function redactPii(text: string): string {\n return text\n .replace(EMAIL_RE, '[redacted-email]')\n .replace(SECRET_HEADER_RE, (_match, name: string, separator: string) => `${name}${separator}[redacted]`)\n .replace(AUTH_SCHEME_RE, (_match, scheme: string) => `${scheme} [redacted]`)\n}\n\nconst UUID_PATH_SEGMENT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\nconst URL_ATTRIBUTE_KEYS = new Set(['http.target', 'http.url', 'url.full', 'url.path'])\n\nfunction redactQuery(query: string): string {\n return query.split('&').map((parameter) => {\n const separator = parameter.indexOf('=')\n return separator < 0 ? parameter : `${parameter.slice(0, separator)}=[redacted]`\n }).join('&')\n}\n\nfunction redactPathSegment(segment: string): string {\n if (/%(?![0-9a-f]{2})/i.test(segment)) return '[redacted]'\n const decoded = segment.replace(/%([0-9a-f]{2})/gi, (_match, hex: string) =>\n String.fromCharCode(Number.parseInt(hex, 16)),\n )\n return /^[A-Za-z0-9_-]{32,}$/.test(decoded) && !UUID_PATH_SEGMENT_RE.test(decoded)\n ? '[redacted]'\n : segment\n}\n\nexport function redactUrl(url: string): string {\n const fragmentIndex = url.indexOf('#')\n const withoutFragment = fragmentIndex < 0 ? url : url.slice(0, fragmentIndex)\n const queryIndex = withoutFragment.indexOf('?')\n const path = queryIndex < 0 ? withoutFragment : withoutFragment.slice(0, queryIndex)\n const authority = /^(?:[a-z][a-z0-9+.-]*:)?\\/\\/[^/]*/i.exec(path)?.[0] ?? ''\n const userInfoEnd = authority.lastIndexOf('@')\n const redactedAuthority = userInfoEnd < 0\n ? authority\n : `${authority.slice(0, authority.indexOf('//') + 2)}${authority.slice(userInfoEnd + 1)}`\n const redactedPath = path.slice(authority.length).split('/').map(redactPathSegment).join('/')\n const query = queryIndex < 0 ? '' : `?${redactQuery(withoutFragment.slice(queryIndex + 1))}`\n const fragment = fragmentIndex < 0 ? '' : '#[redacted]'\n return `${redactedAuthority}${redactedPath}${query}${fragment}`\n}\n\nexport function redactSpanName(name: string): string {\n return redactPii(name.split(/(\\s+)/).map((part) =>\n part.startsWith('/') || /^[a-z][a-z0-9+.-]{0,31}:\\/\\//i.test(part) ? redactUrl(part) : part,\n ).join(''))\n}\n\n// Attribute KEYS whose value is a secret regardless of content. Intentionally\n// specific enough not to clobber benign fields like `token_count`, while\n// still masking the exact key `token`.\nconst SECRET_KEY_RE =\n /(authorization|cookie|password|passwd|\\bpwd\\b|secret|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|^token$|\\bbearer\\b|private[-_]?key|credential)/i\n\n/**\n * Redact a telemetry attribute bag before it ships: a value under a secret-looking\n * KEY (`authorization`, `set-cookie`, `client_secret`, `x-api-key`, \u2026) is masked\n * wholesale; other string values still pass through `redactPii` so an inline email\n * or auth token is caught too. Non-string values are left as-is.\n */\nexport function redactAttributes(attributes: Attributes): Attributes {\n const result: Attributes = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (SECRET_KEY_RE.test(key)) result[key] = '[redacted]'\n else if (typeof value === 'string') {\n const cleaned = key === 'next.span_name'\n ? redactSpanName(value)\n : key === 'url.query' ? redactQuery(value) : URL_ATTRIBUTE_KEYS.has(key) ? redactUrl(value) : value\n result[key] = redactPii(cleaned)\n }\n else result[key] = value\n }\n return result\n}\n"],
5
+ "mappings": "AAkBA,MAAM,WAAW;AAIjB,MAAM,mBAAmB;AAEzB,MAAM,iBAAiB;AAEhB,SAAS,UAAU,MAAsB;AAC9C,SAAO,KACJ,QAAQ,UAAU,kBAAkB,EACpC,QAAQ,kBAAkB,CAAC,QAAQ,MAAc,cAAsB,GAAG,IAAI,GAAG,SAAS,YAAY,EACtG,QAAQ,gBAAgB,CAAC,QAAQ,WAAmB,GAAG,MAAM,aAAa;AAC/E;AAEA,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB,oBAAI,IAAI,CAAC,eAAe,YAAY,YAAY,UAAU,CAAC;AAEtF,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,cAAc;AACzC,UAAM,YAAY,UAAU,QAAQ,GAAG;AACvC,WAAO,YAAY,IAAI,YAAY,GAAG,UAAU,MAAM,GAAG,SAAS,CAAC;AAAA,EACrE,CAAC,EAAE,KAAK,GAAG;AACb;AAEA,SAAS,kBAAkB,SAAyB;AAClD,MAAI,oBAAoB,KAAK,OAAO,EAA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C;AACnE,QAAM,SAAqB,CAAC;AAC5B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrD,QAAI,cAAc,KAAK,GAAG,EAAG,QAAO,GAAG,IAAI;AAAA,aAClC,OAAO,UAAU,UAAU;AAClC,YAAM,UAAU,QAAQ,mBACpB,eAAe,KAAK,IACpB,QAAQ,cAAc,YAAY,KAAK,IAAI,mBAAmB,IAAI,GAAG,IAAI,UAAU,KAAK,IAAI;AAChG,aAAO,GAAG,IAAI,UAAU,OAAO;AAAA,IACjC,MACK,QAAO,GAAG,IAAI;AAAA,EACrB;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,93 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { login } from "@open-mercato/core/helpers/integration/auth";
3
+ for (const locale of ["en", "pl"]) {
4
+ test(`TC-TELEMETRY-003: ${locale} browser exports redact credential URLs and preserve UUIDs`, async ({ page, baseURL }, testInfo) => {
5
+ test.skip(process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== "opt-in", "Browser telemetry opt-in is not configured.");
6
+ const origin = new URL(baseURL ?? "http://localhost:3000").origin;
7
+ await page.context().addCookies([
8
+ { name: "om_test_browser_telemetry", value: "on", url: origin },
9
+ { name: "locale", value: locale, url: origin }
10
+ ]);
11
+ if (locale === "pl") await page.setViewportSize({ width: 390, height: 844 });
12
+ const batches = [];
13
+ const apiUrls = [];
14
+ page.on("request", (request) => {
15
+ if (request.method() === "POST" && new URL(request.url()).pathname === "/api/telemetry/browser-traces") {
16
+ batches.push(request.postData() ?? "");
17
+ }
18
+ });
19
+ page.on("response", (response) => {
20
+ const url = new URL(response.url());
21
+ if (response.status() === 200 && response.request().method() === "GET" && url.pathname.startsWith("/api/") && response.headers()["content-type"]?.includes("application/json")) {
22
+ apiUrls.push(response.url());
23
+ }
24
+ });
25
+ await login(page, "admin");
26
+ await page.context().addCookies([{ name: "locale", value: locale, url: origin }]);
27
+ await page.goto("/backend");
28
+ await expect(page.locator("html")).toHaveAttribute("lang", locale);
29
+ await expect.poll(() => apiUrls.length).toBeGreaterThan(0);
30
+ await expect.poll(() => page.evaluate(() => Object.getOwnPropertySymbols(globalThis).some((symbol) => symbol.toString().includes("opentelemetry.js.api")))).toBe(true);
31
+ const sentinels = ["synthetic-user", "synthetic-password", "synthetic-oauth-code", "synthetic-query-value", "s".repeat(64)];
32
+ const uuid = "3f2504e0-4f89-41d3-9a0c-0305e82c3301";
33
+ const replayKeys = ["window_fetch_replay", "instrumented_fetch_replay"];
34
+ const statuses = await page.evaluate(async ({ replayUrl, sentinels: sentinels2, uuid: uuid2, replayKeys: replayKeys2 }) => {
35
+ const symbol = Object.getOwnPropertySymbols(globalThis).find((candidate) => candidate.toString().includes("opentelemetry.js.api"));
36
+ if (!symbol) throw new Error("[internal] Browser trace runtime is unavailable");
37
+ const registry = globalThis[symbol];
38
+ const tracer = registry.trace?.getTracer("telemetry-url-regression");
39
+ if (!tracer) throw new Error("[internal] Browser tracer is unavailable");
40
+ const instrumentedFetch = window.__omOriginalFetch;
41
+ if (!instrumentedFetch) throw new Error("[internal] Instrumented API fetch is unavailable");
42
+ const url = new URL(replayUrl);
43
+ url.searchParams.set("token", sentinels2[4]);
44
+ url.searchParams.set("code", sentinels2[2]);
45
+ url.searchParams.set("search", sentinels2[3]);
46
+ const windowReplayUrl = new URL(url.href);
47
+ windowReplayUrl.searchParams.set(replayKeys2[0], sentinels2[3]);
48
+ const instrumentedReplayUrl = new URL(url.href);
49
+ instrumentedReplayUrl.searchParams.set(replayKeys2[1], sentinels2[3]);
50
+ const statuses2 = [];
51
+ for (let attempt = 0; attempt < 10; attempt += 1) {
52
+ statuses2.push((await window.fetch(windowReplayUrl.href)).status);
53
+ statuses2.push((await instrumentedFetch(instrumentedReplayUrl.href)).status);
54
+ }
55
+ for (const target of [
56
+ `https://${sentinels2[0]}:${sentinels2[1]}@example.test/reset/${sentinels2[4]}?code=${sentinels2[2]}`,
57
+ `//${sentinels2[0]}:${sentinels2[1]}@[2001:db8::1]/portal?token=${sentinels2[4]}`,
58
+ `/reset/${sentinels2[4]}?token=${sentinels2[4]}`,
59
+ `/records/${uuid2}?search=${sentinels2[3]}`
60
+ ]) {
61
+ const name = `fetch GET ${target}`;
62
+ const span = tracer.startSpan(name);
63
+ span.setAttribute("http.url", target);
64
+ span.setAttribute("url.full", target);
65
+ span.setAttribute("next.span_name", name);
66
+ span.end();
67
+ }
68
+ Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });
69
+ document.dispatchEvent(new Event("visibilitychange"));
70
+ return statuses2;
71
+ }, { replayUrl: apiUrls[0], sentinels, uuid, replayKeys });
72
+ expect(statuses).toHaveLength(20);
73
+ expect(statuses.every((status) => status === 200)).toBe(true);
74
+ await expect.poll(() => batches.flatMap((body) => {
75
+ const batch = JSON.parse(body);
76
+ return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? []).flatMap((scope) => scope.spans ?? []));
77
+ }).filter((span) => span.name.startsWith("fetch GET ")).length).toBeGreaterThanOrEqual(4);
78
+ for (const replayKey of replayKeys) {
79
+ await expect.poll(() => batches.flatMap((body) => {
80
+ const batch = JSON.parse(body);
81
+ return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? []).filter((scope) => scope.scope?.name === "@opentelemetry/instrumentation-fetch").flatMap((scope) => scope.spans ?? []));
82
+ }).some((span) => (span.attributes ?? []).some((attribute) => (attribute.key === "http.url" || attribute.key === "url.full") && typeof attribute.value?.stringValue === "string" && new URL(attribute.value.stringValue, origin).searchParams.get(replayKey) === "[redacted]"))).toBe(true);
83
+ }
84
+ const payload = batches.join("\n");
85
+ for (const sentinel of sentinels) expect(payload).not.toContain(sentinel);
86
+ expect(payload).toContain(uuid);
87
+ expect(payload).toContain("[redacted]");
88
+ expect(payload).toContain("next.span_name");
89
+ await page.screenshot({ path: testInfo.outputPath(`telemetry-${locale}.png`), fullPage: true });
90
+ await testInfo.attach(`telemetry-${locale}`, { path: testInfo.outputPath(`telemetry-${locale}.png`), contentType: "image/png" });
91
+ });
92
+ }
93
+ //# sourceMappingURL=TC-TELEMETRY-003-credential-url-redaction.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/telemetry/__integration__/TC-TELEMETRY-003-credential-url-redaction.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { login } from '@open-mercato/core/helpers/integration/auth'\n\ntype ExportedSpan = {\n name: string\n attributes?: Array<{ key: string; value?: { stringValue?: string } }>\n}\n\ntype TraceBatch = {\n resourceSpans?: Array<{ scopeSpans?: Array<{ scope?: { name?: string }; spans?: ExportedSpan[] }> }>\n}\n\nfor (const locale of ['en', 'pl']) {\n test(`TC-TELEMETRY-003: ${locale} browser exports redact credential URLs and preserve UUIDs`, async ({ page, baseURL }, testInfo) => {\n test.skip(process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== 'opt-in', 'Browser telemetry opt-in is not configured.')\n const origin = new URL(baseURL ?? 'http://localhost:3000').origin\n await page.context().addCookies([\n { name: 'om_test_browser_telemetry', value: 'on', url: origin },\n { name: 'locale', value: locale, url: origin },\n ])\n if (locale === 'pl') await page.setViewportSize({ width: 390, height: 844 })\n const batches: string[] = []\n const apiUrls: string[] = []\n page.on('request', (request) => {\n if (request.method() === 'POST' && new URL(request.url()).pathname === '/api/telemetry/browser-traces') {\n batches.push(request.postData() ?? '')\n }\n })\n page.on('response', (response) => {\n const url = new URL(response.url())\n if (response.status() === 200\n && response.request().method() === 'GET'\n && url.pathname.startsWith('/api/')\n && response.headers()['content-type']?.includes('application/json')) {\n apiUrls.push(response.url())\n }\n })\n await login(page, 'admin')\n await page.context().addCookies([{ name: 'locale', value: locale, url: origin }])\n await page.goto('/backend')\n await expect(page.locator('html')).toHaveAttribute('lang', locale)\n await expect.poll(() => apiUrls.length).toBeGreaterThan(0)\n await expect.poll(() => page.evaluate(() => Object.getOwnPropertySymbols(globalThis)\n .some((symbol) => symbol.toString().includes('opentelemetry.js.api')))).toBe(true)\n\n const sentinels = ['synthetic-user', 'synthetic-password', 'synthetic-oauth-code', 'synthetic-query-value', 's'.repeat(64)]\n const uuid = '3f2504e0-4f89-41d3-9a0c-0305e82c3301'\n const replayKeys = ['window_fetch_replay', 'instrumented_fetch_replay']\n const statuses = await page.evaluate(async ({ replayUrl, sentinels, uuid, replayKeys }) => {\n type BrowserSpan = { setAttribute: (key: string, value: string) => void; end: () => void }\n type RuntimeRegistry = { trace?: { getTracer: (name: string) => { startSpan: (name: string) => BrowserSpan } } }\n const symbol = Object.getOwnPropertySymbols(globalThis).find((candidate) => candidate.toString().includes('opentelemetry.js.api'))\n if (!symbol) throw new Error('[internal] Browser trace runtime is unavailable')\n const registry = (globalThis as unknown as Record<symbol, RuntimeRegistry>)[symbol]\n const tracer = registry.trace?.getTracer('telemetry-url-regression')\n if (!tracer) throw new Error('[internal] Browser tracer is unavailable')\n const instrumentedFetch = (window as Window & { __omOriginalFetch?: typeof window.fetch }).__omOriginalFetch\n if (!instrumentedFetch) throw new Error('[internal] Instrumented API fetch is unavailable')\n const url = new URL(replayUrl)\n url.searchParams.set('token', sentinels[4])\n url.searchParams.set('code', sentinels[2])\n url.searchParams.set('search', sentinels[3])\n const windowReplayUrl = new URL(url.href)\n windowReplayUrl.searchParams.set(replayKeys[0], sentinels[3])\n const instrumentedReplayUrl = new URL(url.href)\n instrumentedReplayUrl.searchParams.set(replayKeys[1], sentinels[3])\n const statuses: number[] = []\n for (let attempt = 0; attempt < 10; attempt += 1) {\n statuses.push((await window.fetch(windowReplayUrl.href)).status)\n statuses.push((await instrumentedFetch(instrumentedReplayUrl.href)).status)\n }\n for (const target of [\n `https://${sentinels[0]}:${sentinels[1]}@example.test/reset/${sentinels[4]}?code=${sentinels[2]}`,\n `//${sentinels[0]}:${sentinels[1]}@[2001:db8::1]/portal?token=${sentinels[4]}`,\n `/reset/${sentinels[4]}?token=${sentinels[4]}`,\n `/records/${uuid}?search=${sentinels[3]}`,\n ]) {\n const name = `fetch GET ${target}`\n const span = tracer.startSpan(name)\n span.setAttribute('http.url', target)\n span.setAttribute('url.full', target)\n span.setAttribute('next.span_name', name)\n span.end()\n }\n Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })\n document.dispatchEvent(new Event('visibilitychange'))\n return statuses\n }, { replayUrl: apiUrls[0], sentinels, uuid, replayKeys })\n expect(statuses).toHaveLength(20)\n expect(statuses.every((status) => status === 200)).toBe(true)\n await expect.poll(() => batches.flatMap((body) => {\n const batch = JSON.parse(body) as TraceBatch\n return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? []).flatMap((scope) => scope.spans ?? []))\n }).filter((span) => span.name.startsWith('fetch GET ')).length).toBeGreaterThanOrEqual(4)\n for (const replayKey of replayKeys) {\n await expect.poll(() => batches.flatMap((body) => {\n const batch = JSON.parse(body) as TraceBatch\n return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? [])\n .filter((scope) => scope.scope?.name === '@opentelemetry/instrumentation-fetch')\n .flatMap((scope) => scope.spans ?? []))\n }).some((span) => (span.attributes ?? []).some((attribute) =>\n (attribute.key === 'http.url' || attribute.key === 'url.full')\n && typeof attribute.value?.stringValue === 'string'\n && new URL(attribute.value.stringValue, origin).searchParams.get(replayKey) === '[redacted]'))).toBe(true)\n }\n const payload = batches.join('\\n')\n for (const sentinel of sentinels) expect(payload).not.toContain(sentinel)\n expect(payload).toContain(uuid)\n expect(payload).toContain('[redacted]')\n expect(payload).toContain('next.span_name')\n await page.screenshot({ path: testInfo.outputPath(`telemetry-${locale}.png`), fullPage: true })\n await testInfo.attach(`telemetry-${locale}`, { path: testInfo.outputPath(`telemetry-${locale}.png`), contentType: 'image/png' })\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,aAAa;AAWtB,WAAW,UAAU,CAAC,MAAM,IAAI,GAAG;AACjC,OAAK,qBAAqB,MAAM,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 import { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from "../trace-he
32
32
  import { redactAttributes, redactPii } from "../facade/redact.js";
33
33
  import { serializeError } from "../facade/serialize.js";
34
34
  import { runSpan } from "./run-span.js";
35
+ import { createRedactingSpanProcessor } from "./redacting-span-processor.js";
35
36
  const TRACER_NAME = "open-mercato";
36
37
  const queuePropagator = new W3CTraceContextPropagator();
37
38
  const W3C_TRACEPARENT = "traceparent";
@@ -174,7 +175,7 @@ class OtlpProvider {
174
175
  // Parent-based so child spans follow the trace's sampling decision; root
175
176
  // spans sample at the configured ratio.
176
177
  sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),
177
- spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],
178
+ spanProcessors: (this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())]).map(createRedactingSpanProcessor),
178
179
  logRecordProcessors: this.options.logRecordProcessors ?? [
179
180
  new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() })
180
181
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/otlp-provider.ts"],
4
- "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n type MetricOptions,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:\n * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).\n */\nexport const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config. Two layers, both asserted by regression tests:\n *\n * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array\n * off the span. This must never be flipped on.\n * - `requestHook` rewrites the statement text with every literal replaced by\n * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so\n * without this the statement itself carries record content and ids. When the\n * text cannot be tokenized the hook fails closed with a fixed marker.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = {\n enhancedDatabaseReporting: false,\n requestHook: (span, { query }) => {\n if (typeof query.text !== 'string' || query.text.length === 0) return\n const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT\n for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)\n },\n} as const satisfies PgInstrumentationConfig\n\n/**\n * Bucket boundaries for every histogram recorded in seconds. Without explicit\n * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 \u2026 10000),\n * which puts every realistic latency in the first bucket and leaves percentiles\n * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms\n * bucket for sub-millisecond pool acquisitions.\n */\nexport const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [\n 0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,\n]\n\nfunction histogramOptions(unit: string | undefined): MetricOptions | undefined {\n if (unit !== 's') return unit ? { unit } : undefined\n return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }\n}\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, histogramOptions(point.unit))\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
- "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,OASP;AACP,SAAS,iCAAiC;AAC1C,SAAS,MAAM,sBAAsB;AACrC,SAAS,eAAe;AAExB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,+BAAwD;AACjE,SAAS,qCAAyD;AAClE,SAAS,yBAAuD;AAChE,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB,4BAA4B;AAe7D,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,gCAAgC;AACpE,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AAExB,MAAM,cAAc;AAMpB,MAAM,kBAAkB,IAAI,0BAA0B;A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O,MAAM;AAAA,QACxE,CAAC,WAAiC,OAAO,MAAM,OAAO,MAAM;AAAA,EACnE;AAAA,EAEQ,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,IAAI,CAAC,IAC9D,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n type MetricOptions,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\nimport { createRedactingSpanProcessor } from './redacting-span-processor'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:\n * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).\n */\nexport const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config. Two layers, both asserted by regression tests:\n *\n * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array\n * off the span. This must never be flipped on.\n * - `requestHook` rewrites the statement text with every literal replaced by\n * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so\n * without this the statement itself carries record content and ids. When the\n * text cannot be tokenized the hook fails closed with a fixed marker.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = {\n enhancedDatabaseReporting: false,\n requestHook: (span, { query }) => {\n if (typeof query.text !== 'string' || query.text.length === 0) return\n const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT\n for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)\n },\n} as const satisfies PgInstrumentationConfig\n\n/**\n * Bucket boundaries for every histogram recorded in seconds. Without explicit\n * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 \u2026 10000),\n * which puts every realistic latency in the first bucket and leaves percentiles\n * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms\n * bucket for sub-millisecond pool acquisitions.\n */\nexport const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [\n 0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,\n]\n\nfunction histogramOptions(unit: string | undefined): MetricOptions | undefined {\n if (unit !== 's') return unit ? { unit } : undefined\n return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }\n}\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: (this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())])\n .map(createRedactingSpanProcessor),\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, histogramOptions(point.unit))\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
+ "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,OASP;AACP,SAAS,iCAAiC;AAC1C,SAAS,MAAM,sBAAsB;AACrC,SAAS,eAAe;AAExB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,+BAAwD;AACjE,SAAS,qCAAyD;AAClE,SAAS,yBAAuD;AAChE,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB,4BAA4B;AAe7D,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,gCAAgC;AACpE,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AACxB,SAAS,oCAAoC;AAE7C,MAAM,cAAc;AAMpB,MAAM,kBAAkB,IAAI,0BAA0B;AAEtD,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AAEvB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAsB1B,MAAM,yBA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,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,IAAI,CAAC,IAC9D,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,38 @@
1
+ import { redactAttributes, redactSpanName } from "../facade/redact.js";
2
+ function createRedactingSpanProcessor(processor) {
3
+ return {
4
+ onStart: (span, parentContext) => processor.onStart(span, parentContext),
5
+ onEnding: (span) => processor.onEnding?.(span),
6
+ onEnd(span) {
7
+ const attributes = {};
8
+ for (const [key, value] of Object.entries(span.attributes)) {
9
+ attributes[key] = typeof value === "string" ? redactAttributes({ [key]: value })[key] : Array.isArray(value) ? value.map((entry) => typeof entry === "string" ? String(redactAttributes({ [key]: entry })[key]) : entry) : value;
10
+ }
11
+ processor.onEnd({
12
+ name: redactSpanName(span.name),
13
+ attributes,
14
+ spanContext: () => span.spanContext(),
15
+ kind: span.kind,
16
+ parentSpanContext: span.parentSpanContext,
17
+ startTime: span.startTime,
18
+ endTime: span.endTime,
19
+ status: span.status,
20
+ links: span.links,
21
+ events: span.events,
22
+ resource: span.resource,
23
+ instrumentationScope: span.instrumentationScope,
24
+ duration: span.duration,
25
+ ended: span.ended,
26
+ droppedAttributesCount: span.droppedAttributesCount,
27
+ droppedEventsCount: span.droppedEventsCount,
28
+ droppedLinksCount: span.droppedLinksCount
29
+ });
30
+ },
31
+ forceFlush: () => processor.forceFlush(),
32
+ shutdown: () => processor.shutdown()
33
+ };
34
+ }
35
+ export {
36
+ createRedactingSpanProcessor
37
+ };
38
+ //# sourceMappingURL=redacting-span-processor.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/provider/redacting-span-processor.ts"],
4
+ "sourcesContent": ["import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'\nimport { redactAttributes, redactSpanName } from '../facade/redact'\n\nexport function createRedactingSpanProcessor(processor: SpanProcessor): SpanProcessor {\n return {\n onStart: (span, parentContext) => processor.onStart(span, parentContext),\n onEnding: (span) => processor.onEnding?.(span),\n onEnd(span) {\n const attributes: ReadableSpan['attributes'] = {}\n for (const [key, value] of Object.entries(span.attributes)) {\n attributes[key] = typeof value === 'string'\n ? redactAttributes({ [key]: value })[key]\n : Array.isArray(value)\n ? value.map((entry) => typeof entry === 'string'\n ? String(redactAttributes({ [key]: entry })[key])\n : entry) as typeof value\n : value\n }\n processor.onEnd({\n name: redactSpanName(span.name),\n attributes,\n spanContext: () => span.spanContext(),\n kind: span.kind,\n parentSpanContext: span.parentSpanContext,\n startTime: span.startTime,\n endTime: span.endTime,\n status: span.status,\n links: span.links,\n events: span.events,\n resource: span.resource,\n instrumentationScope: span.instrumentationScope,\n duration: span.duration,\n ended: span.ended,\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n })\n },\n forceFlush: () => processor.forceFlush(),\n shutdown: () => processor.shutdown(),\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,kBAAkB,sBAAsB;AAE1C,SAAS,6BAA6B,WAAyC;AACpF,SAAO;AAAA,IACL,SAAS,CAAC,MAAM,kBAAkB,UAAU,QAAQ,MAAM,aAAa;AAAA,IACvE,UAAU,CAAC,SAAS,UAAU,WAAW,IAAI;AAAA,IAC7C,MAAM,MAAM;AACV,YAAM,aAAyC,CAAC;AAChD,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,GAAG;AAC1D,mBAAW,GAAG,IAAI,OAAO,UAAU,WAC/B,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,IACtC,MAAM,QAAQ,KAAK,IACjB,MAAM,IAAI,CAAC,UAAU,OAAO,UAAU,WACpC,OAAO,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,IAC9C,KAAK,IACP;AAAA,MACR;AACA,gBAAU,MAAM;AAAA,QACd,MAAM,eAAe,KAAK,IAAI;AAAA,QAC9B;AAAA,QACA,aAAa,MAAM,KAAK,YAAY;AAAA,QACpC,MAAM,KAAK;AAAA,QACX,mBAAmB,KAAK;AAAA,QACxB,WAAW,KAAK;AAAA,QAChB,SAAS,KAAK;AAAA,QACd,QAAQ,KAAK;AAAA,QACb,OAAO,KAAK;AAAA,QACZ,QAAQ,KAAK;AAAA,QACb,UAAU,KAAK;AAAA,QACf,sBAAsB,KAAK;AAAA,QAC3B,UAAU,KAAK;AAAA,QACf,OAAO,KAAK;AAAA,QACZ,wBAAwB,KAAK;AAAA,QAC7B,oBAAoB,KAAK;AAAA,QACzB,mBAAmB,KAAK;AAAA,MAC1B,CAAC;AAAA,IACH;AAAA,IACA,YAAY,MAAM,UAAU,WAAW;AAAA,IACvC,UAAU,MAAM,UAAU,SAAS;AAAA,EACrC;AACF;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.11.1-develop.8347.1.c2e2f21d36",
3
+ "version": "0.11.1-develop.8350.1.e377eb9f50",
4
4
  "license": "MIT",
5
5
  "description": "Vendor-neutral spans, metrics, and error reporting backed by a pluggable OTLP provider. Off by default; the telemetry runtime is loaded only when explicitly enabled.",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@open-mercato/shared": "0.11.1-develop.8347.1.c2e2f21d36"
41
+ "@open-mercato/shared": "0.11.1-develop.8350.1.e377eb9f50"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
+ import { build } from 'esbuild'
3
4
  import { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'
4
5
 
5
6
  const repoRoot = path.resolve(__dirname, '../../../..')
@@ -55,4 +56,30 @@ describe('default-unloaded host wiring', () => {
55
56
  expect(source).not.toContain("from '@open-mercato/telemetry/nextjs'")
56
57
  }
57
58
  })
59
+
60
+ it('keeps span redaction out of the initial browser entry bundle', async () => {
61
+ const entryPoint = 'packages/telemetry/src/browser/index.ts'
62
+ const processorPath = 'packages/telemetry/src/provider/redacting-span-processor.ts'
63
+ const redactionPath = 'packages/telemetry/src/facade/redact.ts'
64
+ const result = await build({
65
+ absWorkingDir: repoRoot,
66
+ entryPoints: [entryPoint],
67
+ bundle: true,
68
+ packages: 'external',
69
+ platform: 'browser',
70
+ format: 'esm',
71
+ splitting: true,
72
+ write: false,
73
+ outdir: 'telemetry-browser-test',
74
+ metafile: true,
75
+ })
76
+ const outputs = Object.values(result.metafile.outputs)
77
+ const browserEntry = outputs.find((output) => output.entryPoint === entryPoint)
78
+
79
+ expect(browserEntry).toBeDefined()
80
+ expect(Object.keys(browserEntry!.inputs)).not.toContain(processorPath)
81
+ expect(Object.keys(browserEntry!.inputs)).not.toContain(redactionPath)
82
+ expect(outputs.some((output) => processorPath in output.inputs)).toBe(true)
83
+ expect(outputs.some((output) => redactionPath in output.inputs)).toBe(true)
84
+ })
58
85
  })
@@ -22,7 +22,7 @@ function otelSpecifiersInSource(): string[] {
22
22
  const specifiers = new Set<string>()
23
23
  const visit = (dir: string) => {
24
24
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
25
- if (entry.name === '__tests__') continue
25
+ if (entry.name === '__tests__' || entry.name === '__integration__') continue
26
26
  const full = path.join(dir, entry.name)
27
27
  if (entry.isDirectory()) {
28
28
  visit(full)
@@ -315,6 +315,77 @@ describe('OtlpProvider (in-memory exporters)', () => {
315
315
  expect(span?.attributes.token_count).toBe(12)
316
316
  })
317
317
 
318
+ it('redacts raw instrumentation spans before injected processors export them', () => {
319
+ const token = 'a'.repeat(64)
320
+ const rawSpan = trace.getTracer('next-js-regression').startSpan(
321
+ `fetch GET https://example.com/reset/${token}?code=one-time-code`,
322
+ )
323
+ rawSpan.setAttributes({
324
+ 'http.target': `/reset/${token}?token=one-time-token`,
325
+ 'http.url': 'https://example.com/portal?token=magic-link',
326
+ 'url.full': 'https://example.com/callback?code=oauth-code',
327
+ 'url.path': `/reset/${token}`,
328
+ 'url.query': 'search=private&page=2',
329
+ 'om.tenant_id': '3f2504e0-4f89-41d3-9a0c-0305e82c3301',
330
+ })
331
+ rawSpan.end()
332
+
333
+ const exported = spanExporter.getFinishedSpans()[0]
334
+ expect(exported.name).toBe('fetch GET https://example.com/reset/[redacted]?code=[redacted]')
335
+ expect(exported.attributes).toMatchObject({
336
+ 'http.target': '/reset/[redacted]?token=[redacted]',
337
+ 'http.url': 'https://example.com/portal?token=[redacted]',
338
+ 'url.full': 'https://example.com/callback?code=[redacted]',
339
+ 'url.path': '/reset/[redacted]',
340
+ 'url.query': 'search=[redacted]&page=[redacted]',
341
+ 'om.tenant_id': '3f2504e0-4f89-41d3-9a0c-0305e82c3301',
342
+ })
343
+ expect(exported.spanContext().traceId).toMatch(/^[0-9a-f]{32}$/)
344
+ expect(exported.ended).toBe(true)
345
+ expect(exported.duration).toHaveLength(2)
346
+ })
347
+
348
+ it('removes embedded URL credentials before raw spans reach the exporter', () => {
349
+ const url = 'https://synthetic-user:synthetic-password@example.com/callback?code=synthetic-code'
350
+ const rawSpan = trace.getTracer('authority-regression').startSpan(`fetch GET ${url}`)
351
+ rawSpan.setAttributes({ 'http.url': url, 'url.full': url })
352
+ rawSpan.end()
353
+
354
+ const exported = spanExporter.getFinishedSpans()[0]
355
+ expect(exported.name).toBe('fetch GET https://example.com/callback?code=[redacted]')
356
+ expect(exported.attributes['http.url']).toBe('https://example.com/callback?code=[redacted]')
357
+ expect(exported.attributes['url.full']).toBe('https://example.com/callback?code=[redacted]')
358
+ })
359
+
360
+ it('cleans the original fetch name mirrored by the Next.js tracer', () => {
361
+ const token = 's'.repeat(64)
362
+ const url = `https://synthetic-user:synthetic-password@example.com/reset/${token}?code=synthetic-code`
363
+ const name = `fetch GET ${url}`
364
+ const rawSpan = trace.getTracer('next-js-metadata-regression').startSpan(name)
365
+ rawSpan.setAttributes({
366
+ 'next.span_category': 'nextjs',
367
+ 'next.span_name': name,
368
+ 'next.span_type': 'AppRender.fetch',
369
+ 'http.method': 'GET',
370
+ 'http.url': url,
371
+ })
372
+ rawSpan.end()
373
+
374
+ const exported = spanExporter.getFinishedSpans()[0]
375
+ expect(exported.name).toBe('fetch GET https://example.com/reset/[redacted]?code=[redacted]')
376
+ expect(exported.attributes).toEqual({
377
+ 'next.span_category': 'nextjs',
378
+ 'next.span_name': exported.name,
379
+ 'next.span_type': 'AppRender.fetch',
380
+ 'http.method': 'GET',
381
+ 'http.url': 'https://example.com/reset/[redacted]?code=[redacted]',
382
+ })
383
+ const payload = JSON.stringify({ name: exported.name, attributes: exported.attributes })
384
+ for (const secret of [token, 'synthetic-user', 'synthetic-password', 'synthetic-code']) {
385
+ expect(payload).not.toContain(secret)
386
+ }
387
+ })
388
+
318
389
  it('emits structured logs and error exceptions through reportError', () => {
319
390
  logger.info('hello', { k: 1 })
320
391
  reportError(new Error('explode'), { module: 'orders' })
@@ -1,4 +1,4 @@
1
- import { redactPii, redactAttributes } from '../facade/redact'
1
+ import { redactPii, redactAttributes, redactUrl, redactSpanName } from '../facade/redact'
2
2
 
3
3
  describe('redactPii', () => {
4
4
  it('masks email addresses', () => {
@@ -90,3 +90,72 @@ describe('redactAttributes', () => {
90
90
  })
91
91
  })
92
92
  })
93
+
94
+
95
+ describe('URL redaction', () => {
96
+ const token = 'a'.repeat(64)
97
+ const uuid = '3f2504e0-4f89-41d3-9a0c-0305e82c3301'
98
+
99
+ it.each(['token', 'code', 'search'])('masks every %s query value and preserves keys', (key) => {
100
+ expect(redactUrl(`/callback?${key}=one-time-secret&page=2&${key}=again`)).toBe(
101
+ `/callback?${key}=[redacted]&page=[redacted]&${key}=[redacted]`,
102
+ )
103
+ })
104
+
105
+ it('masks reset tokens and preserves UUID path segments', () => {
106
+ expect(redactUrl(`/reset/${token}`)).toBe('/reset/[redacted]')
107
+ expect(redactUrl(`/records/${uuid}`)).toBe(`/records/${uuid}`)
108
+ expect(redactUrl(`/reset/${'A_-b'.repeat(8)}`)).toBe('/reset/[redacted]')
109
+ expect(redactUrl(`/reset/${'a'.repeat(31)}`)).toBe(`/reset/${'a'.repeat(31)}`)
110
+ })
111
+
112
+ it('handles absolute, relative, encoded and malformed URLs without retaining values', () => {
113
+ expect(redactUrl(`https://example.com/reset/${token}?token=a%26b&flag#secret`)).toBe(
114
+ 'https://example.com/reset/[redacted]?token=[redacted]&flag#[redacted]',
115
+ )
116
+ expect(redactUrl(`/reset/${'%61'.repeat(32)}`)).toBe('/reset/[redacted]')
117
+ expect(redactUrl('/reset/%broken?token=secret')).toBe('/reset/[redacted]?token=[redacted]')
118
+ expect(redactUrl('/api/customers')).toBe('/api/customers')
119
+ expect(redactUrl('')).toBe('')
120
+ })
121
+
122
+ it.each([
123
+ ['https://synthetic-user:synthetic-password@example.com/reset?token=secret', 'https://example.com/reset?token=[redacted]'],
124
+ ['//synthetic-user:synthetic-password@example.com:8443/path', '//example.com:8443/path'],
125
+ ['https://synthetic-user@example.com/path', 'https://example.com/path'],
126
+ ['https://synthetic%40user:synthetic%3Apassword@example.com/path', 'https://example.com/path'],
127
+ ['https://synthetic@user:synthetic@password@example.com/path', 'https://example.com/path'],
128
+ ['https://synthetic-user:synthetic-password@[2001:db8::1]:8443/path', 'https://[2001:db8::1]:8443/path'],
129
+ ])('removes embedded credentials from URL authority %s', (url, expected) => {
130
+ expect(redactUrl(url)).toBe(expected)
131
+ expect(redactAttributes({ 'http.url': url, 'url.full': url })).toEqual({
132
+ 'http.url': expected,
133
+ 'url.full': expected,
134
+ })
135
+ expect(redactSpanName(`fetch GET ${url}`)).toBe(`fetch GET ${expected}`)
136
+ })
137
+
138
+ it('cleans URL-bearing span names while preserving operation names', () => {
139
+ expect(redactSpanName(`fetch GET https://example.com/reset/${token}?code=secret`)).toBe(
140
+ 'fetch GET https://example.com/reset/[redacted]?code=[redacted]',
141
+ )
142
+ expect(redactSpanName(`GET /reset/${token}?token=secret`)).toBe('GET /reset/[redacted]?token=[redacted]')
143
+ expect(redactSpanName('customers.person.updated')).toBe('customers.person.updated')
144
+ })
145
+
146
+ it('cleans each URL attribute including the standalone query convention', () => {
147
+ expect(redactAttributes({
148
+ 'http.target': `/reset/${token}?token=secret`,
149
+ 'http.url': 'https://example.com/callback?code=secret',
150
+ 'url.full': 'https://example.com/portal?token=secret',
151
+ 'url.path': `/reset/${token}`,
152
+ 'url.query': 'token=secret&search=private&page=2',
153
+ })).toEqual({
154
+ 'http.target': '/reset/[redacted]?token=[redacted]',
155
+ 'http.url': 'https://example.com/callback?code=[redacted]',
156
+ 'url.full': 'https://example.com/portal?token=[redacted]',
157
+ 'url.path': '/reset/[redacted]',
158
+ 'url.query': 'token=[redacted]&search=[redacted]&page=[redacted]',
159
+ })
160
+ })
161
+ })
@@ -0,0 +1,78 @@
1
+ import { ROOT_CONTEXT } from '@opentelemetry/api'
2
+ import { BasicTracerProvider, type ReadableSpan, type SpanProcessor } from '@opentelemetry/sdk-trace-base'
3
+ import { createRedactingSpanProcessor } from '../provider/redacting-span-processor'
4
+
5
+ function recordingProcessor() {
6
+ return {
7
+ onStart: jest.fn(),
8
+ onEnding: jest.fn(),
9
+ onEnd: jest.fn<void, [ReadableSpan]>(),
10
+ forceFlush: jest.fn(async () => {}),
11
+ shutdown: jest.fn(async () => {}),
12
+ } satisfies SpanProcessor
13
+ }
14
+
15
+ describe('redacting span processor', () => {
16
+ it('preserves the lifecycle, readable metadata, and original span across multiple processors', async () => {
17
+ const first = recordingProcessor()
18
+ const second = recordingProcessor()
19
+ const provider = new BasicTracerProvider({
20
+ spanProcessors: [first, second].map(createRedactingSpanProcessor),
21
+ })
22
+ try {
23
+ const span = provider.getTracer('url-regression').startSpan('GET /portal?token=private', {}, ROOT_CONTEXT)
24
+ span.setAttributes({ 'http.target': '/portal?token=private', 'http.response.status_code': 200 })
25
+ span.addEvent('request.finished')
26
+ span.end()
27
+
28
+ for (const processor of [first, second]) {
29
+ expect(processor.onStart).toHaveBeenCalledWith(span, ROOT_CONTEXT)
30
+ expect(processor.onEnding).toHaveBeenCalledWith(span)
31
+ const cleaned = processor.onEnd.mock.calls[0][0]
32
+ expect(cleaned.name).toBe('GET /portal?token=[redacted]')
33
+ expect(cleaned.attributes).toEqual({
34
+ 'http.target': '/portal?token=[redacted]',
35
+ 'http.response.status_code': 200,
36
+ })
37
+ expect(cleaned.spanContext()).toEqual(span.spanContext())
38
+ expect(cleaned).toMatchObject({
39
+ ended: true,
40
+ droppedAttributesCount: 0,
41
+ droppedEventsCount: 0,
42
+ droppedLinksCount: 0,
43
+ instrumentationScope: { name: 'url-regression' },
44
+ events: [expect.objectContaining({ name: 'request.finished' })],
45
+ })
46
+ expect(cleaned.duration).toHaveLength(2)
47
+ expect(cleaned.resource).toBeDefined()
48
+ const original = processor.onStart.mock.calls[0][0] as ReadableSpan
49
+ expect(original.name).toBe('GET /portal?token=private')
50
+ expect(original.attributes['http.target']).toBe('/portal?token=private')
51
+ }
52
+ await provider.forceFlush()
53
+ expect(first.forceFlush).toHaveBeenCalledTimes(1)
54
+ expect(second.forceFlush).toHaveBeenCalledTimes(1)
55
+ } finally {
56
+ await provider.shutdown()
57
+ }
58
+ expect(first.shutdown).toHaveBeenCalledTimes(1)
59
+ expect(second.shutdown).toHaveBeenCalledTimes(1)
60
+ })
61
+
62
+ it('cleans string URL attribute arrays and supports processors without onEnding', async () => {
63
+ const processor = recordingProcessor()
64
+ const wrapper = createRedactingSpanProcessor({ ...processor, onEnding: undefined })
65
+ const provider = new BasicTracerProvider({ spanProcessors: [wrapper] })
66
+ try {
67
+ const span = provider.getTracer('array-regression').startSpan('request')
68
+ span.setAttributes({ 'url.full': ['https://example.com?code=private', null], 'retry.delays': [1, 2] })
69
+ span.end()
70
+ expect(processor.onEnd.mock.calls[0][0].attributes).toEqual({
71
+ 'url.full': ['https://example.com?code=[redacted]', null],
72
+ 'retry.delays': [1, 2],
73
+ })
74
+ } finally {
75
+ await provider.shutdown()
76
+ }
77
+ })
78
+ })
@@ -26,8 +26,6 @@
26
26
  import * as React from 'react'
27
27
  import { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
28
28
  import { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'
29
- import { serializeError } from '../facade/serialize'
30
- import { redactAttributes } from '../facade/redact'
31
29
  import type { BrowserTelemetryConfig } from './config'
32
30
  import { createBackupHeaderPropagator } from './propagator'
33
31
 
@@ -56,6 +54,9 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<Te
56
54
  { FetchInstrumentation },
57
55
  { W3CTraceContextPropagator },
58
56
  { defaultTextMapSetter, SpanStatusCode },
57
+ { createRedactingSpanProcessor },
58
+ { serializeError },
59
+ { redactAttributes },
59
60
  ] = await Promise.all([
60
61
  import('@opentelemetry/sdk-trace-web'),
61
62
  import('@opentelemetry/sdk-trace-base'),
@@ -66,6 +67,9 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<Te
66
67
  import('@opentelemetry/instrumentation-fetch'),
67
68
  import('@opentelemetry/core'),
68
69
  import('@opentelemetry/api'),
70
+ import('../provider/redacting-span-processor'),
71
+ import('../facade/serialize'),
72
+ import('../facade/redact'),
69
73
  ])
70
74
 
71
75
  const provider = new WebTracerProvider({
@@ -80,12 +84,12 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<Te
80
84
  root: new TraceIdRatioBasedSampler(config.samplingRatio),
81
85
  }),
82
86
  spanProcessors: [
83
- new BatchSpanProcessor(
87
+ createRedactingSpanProcessor(new BatchSpanProcessor(
84
88
  new OTLPTraceExporter({ url: config.endpoint }),
85
89
  // The interesting spans arrive in bursts around a navigation; a short delay keeps them
86
90
  // close together in the trace view without one request per span.
87
91
  { scheduledDelayMillis: 3_000, maxQueueSize: 512 },
88
- ),
92
+ )),
89
93
  ],
90
94
  })
91
95
 
@@ -13,10 +13,12 @@ import { act, render } from '@testing-library/react'
13
13
  import { BrowserTelemetry, resetBrowserTelemetryBootstrap } from '../BrowserTelemetry'
14
14
  import { BROWSER_TRACES_PATH, type BrowserTelemetryConfig } from '../config'
15
15
  import { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../../trace-headers'
16
+ import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-base'
16
17
  import type { TextMapPropagator } from '@opentelemetry/api'
17
18
 
18
19
  /** Which SDK modules were dynamically imported — the "zero client cost while off" claim. */
19
20
  const mockLoadedModules: string[] = []
21
+ const mockBatchOnEnd = jest.fn()
20
22
  const mockProviderInstances: Array<{
21
23
  options: Record<string, unknown>
22
24
  register: jest.Mock
@@ -54,7 +56,7 @@ jest.mock('@opentelemetry/sdk-trace-web', () =>
54
56
 
55
57
  jest.mock('@opentelemetry/sdk-trace-base', () =>
56
58
  record('@opentelemetry/sdk-trace-base', {
57
- BatchSpanProcessor: class {},
59
+ BatchSpanProcessor: class { onEnd = mockBatchOnEnd },
58
60
  ParentBasedSampler: class {},
59
61
  TraceIdRatioBasedSampler: class {},
60
62
  }),
@@ -167,6 +169,7 @@ describe('BrowserTelemetry', () => {
167
169
  mockFetchInstrumentationConfigs.length = 0
168
170
  mockExporterConfigs.length = 0
169
171
  mockRegisterInstrumentations.mockClear()
172
+ mockBatchOnEnd.mockClear()
170
173
  mockFetchInstrumentationFailure.next = null
171
174
  window.fetch = nativeFetch
172
175
  delete (window as { __omOriginalFetch?: unknown }).__omOriginalFetch
@@ -208,6 +211,37 @@ describe('BrowserTelemetry', () => {
208
211
  expect(ignoreUrls.some((pattern) => pattern.test('http://localhost/api/customers'))).toBe(false)
209
212
  })
210
213
 
214
+ it('redacts browser page and fetch URLs before the batch processor sees a span', async () => {
215
+ await renderAndSettle(<BrowserTelemetry config={CONFIG} />)
216
+ const processors = mockProviderInstances[0].options.spanProcessors as SpanProcessor[]
217
+ const token = 'b'.repeat(64)
218
+ const original = Object.freeze({
219
+ name: `fetch GET https://synthetic-user:synthetic-password@example.com/reset/${token}?token=magic-link`,
220
+ attributes: Object.freeze({
221
+ 'http.url': 'https://synthetic-user:synthetic-password@example.com/portal?token=invite',
222
+ 'url.full': 'https://example.com/callback?code=oauth-code',
223
+ 'url.path': `/reset/${token}`,
224
+ 'url.query': 'search=private',
225
+ 'next.span_name': `fetch GET https://synthetic-user:synthetic-password@example.com/reset/${token}?token=magic-link`,
226
+ }),
227
+ spanContext: () => ({ traceId: '1'.repeat(32), spanId: '2'.repeat(16), traceFlags: 1 }),
228
+ }) as ReadableSpan
229
+ processors[0].onEnd(original)
230
+
231
+ const sanitized = mockBatchOnEnd.mock.calls[0][0] as ReadableSpan
232
+ expect(sanitized.name).toBe('fetch GET https://example.com/reset/[redacted]?token=[redacted]')
233
+ expect(sanitized.attributes).toEqual({
234
+ 'http.url': 'https://example.com/portal?token=[redacted]',
235
+ 'url.full': 'https://example.com/callback?code=[redacted]',
236
+ 'url.path': '/reset/[redacted]',
237
+ 'url.query': 'search=[redacted]',
238
+ 'next.span_name': 'fetch GET https://example.com/reset/[redacted]?token=[redacted]',
239
+ })
240
+ expect(sanitized.spanContext()).toEqual(original.spanContext())
241
+ expect(original.name).toContain(token)
242
+ expect(original.attributes['url.query']).toBe('search=private')
243
+ })
244
+
211
245
  it('never loads the user-interaction instrumentation — it cannot see a React click and would emit nothing', async () => {
212
246
  await renderAndSettle(<BrowserTelemetry config={CONFIG} />)
213
247
 
@@ -31,6 +31,48 @@ export function redactPii(text: string): string {
31
31
  .replace(AUTH_SCHEME_RE, (_match, scheme: string) => `${scheme} [redacted]`)
32
32
  }
33
33
 
34
+ const UUID_PATH_SEGMENT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
35
+ const URL_ATTRIBUTE_KEYS = new Set(['http.target', 'http.url', 'url.full', 'url.path'])
36
+
37
+ function redactQuery(query: string): string {
38
+ return query.split('&').map((parameter) => {
39
+ const separator = parameter.indexOf('=')
40
+ return separator < 0 ? parameter : `${parameter.slice(0, separator)}=[redacted]`
41
+ }).join('&')
42
+ }
43
+
44
+ function redactPathSegment(segment: string): string {
45
+ if (/%(?![0-9a-f]{2})/i.test(segment)) return '[redacted]'
46
+ const decoded = segment.replace(/%([0-9a-f]{2})/gi, (_match, hex: string) =>
47
+ String.fromCharCode(Number.parseInt(hex, 16)),
48
+ )
49
+ return /^[A-Za-z0-9_-]{32,}$/.test(decoded) && !UUID_PATH_SEGMENT_RE.test(decoded)
50
+ ? '[redacted]'
51
+ : segment
52
+ }
53
+
54
+ export function redactUrl(url: string): string {
55
+ const fragmentIndex = url.indexOf('#')
56
+ const withoutFragment = fragmentIndex < 0 ? url : url.slice(0, fragmentIndex)
57
+ const queryIndex = withoutFragment.indexOf('?')
58
+ const path = queryIndex < 0 ? withoutFragment : withoutFragment.slice(0, queryIndex)
59
+ const authority = /^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/]*/i.exec(path)?.[0] ?? ''
60
+ const userInfoEnd = authority.lastIndexOf('@')
61
+ const redactedAuthority = userInfoEnd < 0
62
+ ? authority
63
+ : `${authority.slice(0, authority.indexOf('//') + 2)}${authority.slice(userInfoEnd + 1)}`
64
+ const redactedPath = path.slice(authority.length).split('/').map(redactPathSegment).join('/')
65
+ const query = queryIndex < 0 ? '' : `?${redactQuery(withoutFragment.slice(queryIndex + 1))}`
66
+ const fragment = fragmentIndex < 0 ? '' : '#[redacted]'
67
+ return `${redactedAuthority}${redactedPath}${query}${fragment}`
68
+ }
69
+
70
+ export function redactSpanName(name: string): string {
71
+ return redactPii(name.split(/(\s+)/).map((part) =>
72
+ part.startsWith('/') || /^[a-z][a-z0-9+.-]{0,31}:\/\//i.test(part) ? redactUrl(part) : part,
73
+ ).join(''))
74
+ }
75
+
34
76
  // Attribute KEYS whose value is a secret regardless of content. Intentionally
35
77
  // specific enough not to clobber benign fields like `token_count`, while
36
78
  // still masking the exact key `token`.
@@ -47,7 +89,12 @@ export function redactAttributes(attributes: Attributes): Attributes {
47
89
  const result: Attributes = {}
48
90
  for (const [key, value] of Object.entries(attributes)) {
49
91
  if (SECRET_KEY_RE.test(key)) result[key] = '[redacted]'
50
- else if (typeof value === 'string') result[key] = redactPii(value)
92
+ else if (typeof value === 'string') {
93
+ const cleaned = key === 'next.span_name'
94
+ ? redactSpanName(value)
95
+ : key === 'url.query' ? redactQuery(value) : URL_ATTRIBUTE_KEYS.has(key) ? redactUrl(value) : value
96
+ result[key] = redactPii(cleaned)
97
+ }
51
98
  else result[key] = value
52
99
  }
53
100
  return result
@@ -0,0 +1,114 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { login } from '@open-mercato/core/helpers/integration/auth'
3
+
4
+ type ExportedSpan = {
5
+ name: string
6
+ attributes?: Array<{ key: string; value?: { stringValue?: string } }>
7
+ }
8
+
9
+ type TraceBatch = {
10
+ resourceSpans?: Array<{ scopeSpans?: Array<{ scope?: { name?: string }; spans?: ExportedSpan[] }> }>
11
+ }
12
+
13
+ for (const locale of ['en', 'pl']) {
14
+ test(`TC-TELEMETRY-003: ${locale} browser exports redact credential URLs and preserve UUIDs`, async ({ page, baseURL }, testInfo) => {
15
+ test.skip(process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== 'opt-in', 'Browser telemetry opt-in is not configured.')
16
+ const origin = new URL(baseURL ?? 'http://localhost:3000').origin
17
+ await page.context().addCookies([
18
+ { name: 'om_test_browser_telemetry', value: 'on', url: origin },
19
+ { name: 'locale', value: locale, url: origin },
20
+ ])
21
+ if (locale === 'pl') await page.setViewportSize({ width: 390, height: 844 })
22
+ const batches: string[] = []
23
+ const apiUrls: string[] = []
24
+ page.on('request', (request) => {
25
+ if (request.method() === 'POST' && new URL(request.url()).pathname === '/api/telemetry/browser-traces') {
26
+ batches.push(request.postData() ?? '')
27
+ }
28
+ })
29
+ page.on('response', (response) => {
30
+ const url = new URL(response.url())
31
+ if (response.status() === 200
32
+ && response.request().method() === 'GET'
33
+ && url.pathname.startsWith('/api/')
34
+ && response.headers()['content-type']?.includes('application/json')) {
35
+ apiUrls.push(response.url())
36
+ }
37
+ })
38
+ await login(page, 'admin')
39
+ await page.context().addCookies([{ name: 'locale', value: locale, url: origin }])
40
+ await page.goto('/backend')
41
+ await expect(page.locator('html')).toHaveAttribute('lang', locale)
42
+ await expect.poll(() => apiUrls.length).toBeGreaterThan(0)
43
+ await expect.poll(() => page.evaluate(() => Object.getOwnPropertySymbols(globalThis)
44
+ .some((symbol) => symbol.toString().includes('opentelemetry.js.api')))).toBe(true)
45
+
46
+ const sentinels = ['synthetic-user', 'synthetic-password', 'synthetic-oauth-code', 'synthetic-query-value', 's'.repeat(64)]
47
+ const uuid = '3f2504e0-4f89-41d3-9a0c-0305e82c3301'
48
+ const replayKeys = ['window_fetch_replay', 'instrumented_fetch_replay']
49
+ const statuses = await page.evaluate(async ({ replayUrl, sentinels, uuid, replayKeys }) => {
50
+ type BrowserSpan = { setAttribute: (key: string, value: string) => void; end: () => void }
51
+ type RuntimeRegistry = { trace?: { getTracer: (name: string) => { startSpan: (name: string) => BrowserSpan } } }
52
+ const symbol = Object.getOwnPropertySymbols(globalThis).find((candidate) => candidate.toString().includes('opentelemetry.js.api'))
53
+ if (!symbol) throw new Error('[internal] Browser trace runtime is unavailable')
54
+ const registry = (globalThis as unknown as Record<symbol, RuntimeRegistry>)[symbol]
55
+ const tracer = registry.trace?.getTracer('telemetry-url-regression')
56
+ if (!tracer) throw new Error('[internal] Browser tracer is unavailable')
57
+ const instrumentedFetch = (window as Window & { __omOriginalFetch?: typeof window.fetch }).__omOriginalFetch
58
+ if (!instrumentedFetch) throw new Error('[internal] Instrumented API fetch is unavailable')
59
+ const url = new URL(replayUrl)
60
+ url.searchParams.set('token', sentinels[4])
61
+ url.searchParams.set('code', sentinels[2])
62
+ url.searchParams.set('search', sentinels[3])
63
+ const windowReplayUrl = new URL(url.href)
64
+ windowReplayUrl.searchParams.set(replayKeys[0], sentinels[3])
65
+ const instrumentedReplayUrl = new URL(url.href)
66
+ instrumentedReplayUrl.searchParams.set(replayKeys[1], sentinels[3])
67
+ const statuses: number[] = []
68
+ for (let attempt = 0; attempt < 10; attempt += 1) {
69
+ statuses.push((await window.fetch(windowReplayUrl.href)).status)
70
+ statuses.push((await instrumentedFetch(instrumentedReplayUrl.href)).status)
71
+ }
72
+ for (const target of [
73
+ `https://${sentinels[0]}:${sentinels[1]}@example.test/reset/${sentinels[4]}?code=${sentinels[2]}`,
74
+ `//${sentinels[0]}:${sentinels[1]}@[2001:db8::1]/portal?token=${sentinels[4]}`,
75
+ `/reset/${sentinels[4]}?token=${sentinels[4]}`,
76
+ `/records/${uuid}?search=${sentinels[3]}`,
77
+ ]) {
78
+ const name = `fetch GET ${target}`
79
+ const span = tracer.startSpan(name)
80
+ span.setAttribute('http.url', target)
81
+ span.setAttribute('url.full', target)
82
+ span.setAttribute('next.span_name', name)
83
+ span.end()
84
+ }
85
+ Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
86
+ document.dispatchEvent(new Event('visibilitychange'))
87
+ return statuses
88
+ }, { replayUrl: apiUrls[0], sentinels, uuid, replayKeys })
89
+ expect(statuses).toHaveLength(20)
90
+ expect(statuses.every((status) => status === 200)).toBe(true)
91
+ await expect.poll(() => batches.flatMap((body) => {
92
+ const batch = JSON.parse(body) as TraceBatch
93
+ return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? []).flatMap((scope) => scope.spans ?? []))
94
+ }).filter((span) => span.name.startsWith('fetch GET ')).length).toBeGreaterThanOrEqual(4)
95
+ for (const replayKey of replayKeys) {
96
+ await expect.poll(() => batches.flatMap((body) => {
97
+ const batch = JSON.parse(body) as TraceBatch
98
+ return (batch.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? [])
99
+ .filter((scope) => scope.scope?.name === '@opentelemetry/instrumentation-fetch')
100
+ .flatMap((scope) => scope.spans ?? []))
101
+ }).some((span) => (span.attributes ?? []).some((attribute) =>
102
+ (attribute.key === 'http.url' || attribute.key === 'url.full')
103
+ && typeof attribute.value?.stringValue === 'string'
104
+ && new URL(attribute.value.stringValue, origin).searchParams.get(replayKey) === '[redacted]'))).toBe(true)
105
+ }
106
+ const payload = batches.join('\n')
107
+ for (const sentinel of sentinels) expect(payload).not.toContain(sentinel)
108
+ expect(payload).toContain(uuid)
109
+ expect(payload).toContain('[redacted]')
110
+ expect(payload).toContain('next.span_name')
111
+ await page.screenshot({ path: testInfo.outputPath(`telemetry-${locale}.png`), fullPage: true })
112
+ await testInfo.attach(`telemetry-${locale}`, { path: testInfo.outputPath(`telemetry-${locale}.png`), contentType: 'image/png' })
113
+ })
114
+ }
@@ -65,6 +65,7 @@ import { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-he
65
65
  import { redactAttributes, redactPii } from '../facade/redact'
66
66
  import { serializeError } from '../facade/serialize'
67
67
  import { runSpan } from './run-span'
68
+ import { createRedactingSpanProcessor } from './redacting-span-processor'
68
69
 
69
70
  const TRACER_NAME = 'open-mercato'
70
71
 
@@ -289,7 +290,8 @@ export class OtlpProvider implements TelemetryProvider {
289
290
  // Parent-based so child spans follow the trace's sampling decision; root
290
291
  // spans sample at the configured ratio.
291
292
  sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),
292
- spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],
293
+ spanProcessors: (this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())])
294
+ .map(createRedactingSpanProcessor),
293
295
  logRecordProcessors: this.options.logRecordProcessors ?? [
294
296
  new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),
295
297
  ],
@@ -0,0 +1,42 @@
1
+ import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'
2
+ import { redactAttributes, redactSpanName } from '../facade/redact'
3
+
4
+ export function createRedactingSpanProcessor(processor: SpanProcessor): SpanProcessor {
5
+ return {
6
+ onStart: (span, parentContext) => processor.onStart(span, parentContext),
7
+ onEnding: (span) => processor.onEnding?.(span),
8
+ onEnd(span) {
9
+ const attributes: ReadableSpan['attributes'] = {}
10
+ for (const [key, value] of Object.entries(span.attributes)) {
11
+ attributes[key] = typeof value === 'string'
12
+ ? redactAttributes({ [key]: value })[key]
13
+ : Array.isArray(value)
14
+ ? value.map((entry) => typeof entry === 'string'
15
+ ? String(redactAttributes({ [key]: entry })[key])
16
+ : entry) as typeof value
17
+ : value
18
+ }
19
+ processor.onEnd({
20
+ name: redactSpanName(span.name),
21
+ attributes,
22
+ spanContext: () => span.spanContext(),
23
+ kind: span.kind,
24
+ parentSpanContext: span.parentSpanContext,
25
+ startTime: span.startTime,
26
+ endTime: span.endTime,
27
+ status: span.status,
28
+ links: span.links,
29
+ events: span.events,
30
+ resource: span.resource,
31
+ instrumentationScope: span.instrumentationScope,
32
+ duration: span.duration,
33
+ ended: span.ended,
34
+ droppedAttributesCount: span.droppedAttributesCount,
35
+ droppedEventsCount: span.droppedEventsCount,
36
+ droppedLinksCount: span.droppedLinksCount,
37
+ })
38
+ },
39
+ forceFlush: () => processor.forceFlush(),
40
+ shutdown: () => processor.shutdown(),
41
+ }
42
+ }