@absolutejs/beacon 0.3.16 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,8 +69,15 @@ beacon.captureMessage("checkout started", "info");
69
69
  - **Context** — `setTags`, `setUser`, per-call `tags`/`extra`, a per-session id.
70
70
  - **Cause chains** — preserves nested `Error.cause` stacks and diagnostic fields
71
71
  in `extra.errorCauses`, including database driver error codes and details.
72
- - **Sampling + redaction** — `sampleRate` and a `beforeSend(event)` hook
73
- (return `null` to drop).
72
+ - **Sampling + redaction** — `sampleRate`, a `beforeSend(event)` hook
73
+ (return `null` to drop), and default credential/context redaction after the
74
+ hook so host customization cannot accidentally reintroduce secrets. URL
75
+ query/hash values, secret-bearing fields, bearer/JWT values, and breadcrumb
76
+ text are sanitized. Set `redact: false` only when a trusted boundary replaces
77
+ it.
78
+ - **Noise filtering** — known browser-host/scanner failures such as CefSharp's
79
+ `Object Not Found Matching Id` rejection are dropped by default
80
+ (`filterKnownNoise: false` opts out).
74
81
  - **Resource policy** — `instrument.resourceErrors` accepts a predicate so
75
82
  expected failures such as optional cross-origin images can become grouped
76
83
  warnings while same-origin assets and critical scripts/styles remain errors.
package/dist/index.d.ts CHANGED
@@ -171,6 +171,17 @@ export type BeaconOptions = {
171
171
  sampleRate?: number;
172
172
  /** Mutate or drop (return null) each event before it's buffered. */
173
173
  beforeSend?: (event: BeaconEvent) => BeaconEvent | null;
174
+ /**
175
+ * Redact credentials, secret-bearing fields, and URL query/hash values after
176
+ * `beforeSend` and before buffering. Default true. Disable only when an
177
+ * equivalent trusted boundary owns redaction.
178
+ */
179
+ redact?: boolean;
180
+ /**
181
+ * Drop signatures known to come from browser hosts/scanners rather than the
182
+ * page, such as CefSharp's JavaScript bridge rejections. Default true.
183
+ */
184
+ filterKnownNoise?: boolean;
174
185
  /** Supply the active session-replay id (wired by @absolutejs/replay). */
175
186
  getReplayId?: () => string | undefined;
176
187
  /** Auto-instrumentation toggles (all default true). */
@@ -185,6 +196,10 @@ export type BeaconOptions = {
185
196
  };
186
197
  /** A finalized Core Web Vital measurement, tagged with the path it was seen on. */
187
198
  export type WebVital = {
199
+ /** Unix epoch milliseconds when the finalized metric was observed. */
200
+ at: number;
201
+ /** Optional deployment environment copied from the Beacon configuration. */
202
+ environment?: string;
188
203
  /** The 5 Core Web Vitals, plus TBT (Total Blocking Time — long-task overage). */
189
204
  name: "LCP" | "INP" | "CLS" | "FCP" | "TTFB" | "TBT";
190
205
  /** Metric value (ms for LCP/INP/FCP/TTFB; unitless for CLS). */
@@ -195,7 +210,15 @@ export type WebVital = {
195
210
  /** Stable per-page-load metric id (dedup). */
196
211
  id: string;
197
212
  navigationType: string;
213
+ /** Beacon project identifier, used by authenticated relays for tenant fencing. */
214
+ project: string;
215
+ /** Optional application release copied from the Beacon configuration. */
216
+ release?: string;
217
+ /** Optional privacy-masked replay correlation. */
218
+ replayId?: string;
198
219
  };
220
+ /** Override Web Vital delivery without changing collection semantics. */
221
+ export type BeaconVitalsTransport = (vital: WebVital) => void | Promise<void>;
199
222
  type WebVitalMetric = {
200
223
  name: string;
201
224
  value: number;
@@ -225,6 +248,8 @@ export type BeaconVitalsOptions = {
225
248
  webVitals?: WebVitalsModule;
226
249
  /** Also called for each finalized vital (in addition to the POST). */
227
250
  onVital?: (vital: WebVital) => void;
251
+ /** Override delivery (default: sendBeacon / fetch keepalive). */
252
+ transport?: BeaconVitalsTransport;
228
253
  };
229
254
  export type Beacon = {
230
255
  captureException: (error: unknown, context?: CaptureContext) => void;
@@ -246,6 +271,10 @@ export type Beacon = {
246
271
  /** Remove all listeners + do a final flush. */
247
272
  close: () => Promise<void>;
248
273
  };
274
+ /** Redact an event without mutating the caller's object. */
275
+ export declare const redactBeaconEvent: (event: BeaconEvent) => BeaconEvent;
276
+ /** Known browser-host/scanner failures that do not originate in page code. */
277
+ export declare const isKnownBeaconNoise: (event: Pick<BeaconEvent, "message" | "name">) => boolean;
249
278
  export declare const createBeacon: (options: BeaconOptions) => Beacon;
250
279
  /** Initialize the global beacon. Returns the instance. */
251
280
  export declare const initBeacon: (options: BeaconOptions) => Beacon;
package/dist/index.js CHANGED
@@ -1,17 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __returnValue = (v) => v;
3
- function __exportSetter(name, newValue) {
4
- this[name] = __returnValue.bind(null, newValue);
5
- }
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true,
11
- configurable: true,
12
- set: __exportSetter.bind(all, name)
13
- });
14
- };
15
1
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
16
2
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
17
3
  }) : x)(function(x) {
@@ -178,6 +164,89 @@ var safeStringify = (value) => {
178
164
  return String(value);
179
165
  }
180
166
  };
167
+ var REDACTED = "[REDACTED]";
168
+ var SENSITIVE_KEY_NAMES = new Set([
169
+ "accesstoken",
170
+ "apikey",
171
+ "authorization",
172
+ "clientsecret",
173
+ "cookie",
174
+ "csrftoken",
175
+ "idtoken",
176
+ "password",
177
+ "passwd",
178
+ "proxyauthorization",
179
+ "refreshtoken",
180
+ "secret",
181
+ "setcookie",
182
+ "token"
183
+ ]);
184
+ var URL_KEY_NAMES = new Set([
185
+ "endpoint",
186
+ "errorfilename",
187
+ "resourceurl",
188
+ "url"
189
+ ]);
190
+ var normalizeFieldName = (key) => key.replace(/[^a-z0-9]/gi, "").toLowerCase();
191
+ var isSensitiveField = (key) => SENSITIVE_KEY_NAMES.has(normalizeFieldName(key));
192
+ var isUrlField = (key) => URL_KEY_NAMES.has(normalizeFieldName(key));
193
+ var redactUrl = (value) => {
194
+ try {
195
+ const absolute = /^[a-z][a-z\d+.-]*:/i.test(value);
196
+ const url = new URL(value, "https://beacon.invalid");
197
+ url.search = "";
198
+ url.hash = "";
199
+ return absolute ? url.toString() : `${url.pathname}`;
200
+ } catch {
201
+ return value.replace(/[?#].*$/, "");
202
+ }
203
+ };
204
+ var redactString = (value) => value.replace(/\b(Bearer)\s+[A-Za-z0-9._~+/-]+=*/gi, (_match, scheme) => `${scheme} ${REDACTED}`).replace(/([?&](?:access_token|api_?key|authorization|code|id_token|password|refresh_token|secret|token)=)[^&#\s]*/gi, `$1${REDACTED}`).replace(/\b((?:access_?token|api_?key|authorization|client_?secret|cookie|id_?token|password|passwd|refresh_?token|secret|token)\s*[:=]\s*)(?!Bearer\b|\[REDACTED\])[^,\s;]+/gi, `$1${REDACTED}`).replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, REDACTED);
205
+ var redactValue = (value, key, seen, depth = 0) => {
206
+ if (key !== undefined && isSensitiveField(key))
207
+ return REDACTED;
208
+ if (typeof value === "string") {
209
+ return redactString(key !== undefined && isUrlField(key) ? redactUrl(value) : value);
210
+ }
211
+ if (value === null || typeof value === "number" || typeof value === "boolean") {
212
+ return value;
213
+ }
214
+ if (typeof value === "bigint")
215
+ return String(value);
216
+ if (typeof value !== "object")
217
+ return String(value);
218
+ if (depth >= 12)
219
+ return "[Truncated]";
220
+ if (seen.has(value))
221
+ return "[Circular]";
222
+ seen.add(value);
223
+ const redacted = Array.isArray(value) ? value.map((entry) => redactValue(entry, undefined, seen, depth + 1)) : Object.fromEntries(Object.entries(value).map(([field, entry]) => [
224
+ field,
225
+ redactValue(entry, field, seen, depth + 1)
226
+ ]));
227
+ seen.delete(value);
228
+ return redacted;
229
+ };
230
+ var redactBeaconEvent = (event) => {
231
+ const redacted = {
232
+ ...event,
233
+ message: redactString(event.message)
234
+ };
235
+ if (event.stack !== undefined)
236
+ redacted.stack = redactString(event.stack);
237
+ if (event.tags !== undefined) {
238
+ redacted.tags = Object.fromEntries(Object.entries(event.tags).map(([key, value]) => [
239
+ key,
240
+ redactValue(value, key, new Set)
241
+ ]));
242
+ }
243
+ if (event.extra !== undefined) {
244
+ redacted.extra = redactValue(event.extra, undefined, new Set);
245
+ }
246
+ return redacted;
247
+ };
248
+ var CEF_SHARP_REJECTION = /^Object Not Found Matching Id:\d+, MethodName:[A-Za-z_$][\w$]*, ParamCount:\d+$/;
249
+ var isKnownBeaconNoise = (event) => event.name === "UnhandledRejection" && CEF_SHARP_REJECTION.test(event.message);
181
250
  var errorWithStack = (name, message, location2) => {
182
251
  const error = new Error(message);
183
252
  error.name = name;
@@ -409,6 +478,8 @@ var createBeacon = (options) => {
409
478
  const flushIntervalMs = options.flushIntervalMs ?? 5000;
410
479
  const maxBreadcrumbs = options.maxBreadcrumbs ?? 30;
411
480
  const sampleRate = options.sampleRate ?? 1;
481
+ const redact = options.redact !== false;
482
+ const filterKnownNoise = options.filterKnownNoise !== false;
412
483
  const transport = options.transport ?? defaultTransport;
413
484
  const instrument = options.instrument ?? {};
414
485
  const sessionId = newId();
@@ -430,15 +501,25 @@ var createBeacon = (options) => {
430
501
  const reportVital = (metric) => {
431
502
  if (!isVitalName(metric.name))
432
503
  return;
504
+ const replayId = options.getReplayId?.();
433
505
  const vital = {
506
+ at: Date.now(),
507
+ ...options.environment === undefined ? {} : { environment: options.environment },
434
508
  id: metric.id,
435
509
  name: metric.name,
436
510
  navigationType: metric.navigationType,
437
511
  path: location.pathname,
512
+ project: options.project,
438
513
  rating: metric.rating === "good" || metric.rating === "needs-improvement" || metric.rating === "poor" ? metric.rating : "needs-improvement",
514
+ ...options.release === undefined ? {} : { release: options.release },
515
+ ...replayId === undefined ? {} : { replayId },
439
516
  value: metric.value
440
517
  };
441
518
  vitalsOptions.onVital?.(vital);
519
+ if (vitalsOptions.transport !== undefined) {
520
+ Promise.resolve(vitalsOptions.transport(vital)).catch(() => {});
521
+ return;
522
+ }
442
523
  const body = JSON.stringify(vital);
443
524
  if (typeof navigator.sendBeacon === "function") {
444
525
  navigator.sendBeacon(vitalsEndpoint, new Blob([body], { type: "application/json" }));
@@ -459,7 +540,7 @@ var createBeacon = (options) => {
459
540
  });
460
541
  }
461
542
  const navigationEntry = performance.getEntriesByType("navigation")[0];
462
- const navigationType = navigationEntry instanceof PerformanceNavigationTiming ? navigationEntry.type : "navigate";
543
+ const navigationType = typeof PerformanceNavigationTiming !== "undefined" && navigationEntry instanceof PerformanceNavigationTiming ? navigationEntry.type : "navigate";
463
544
  observeLongTasks(reportVital, navigationType);
464
545
  }
465
546
  const buffer = [];
@@ -513,9 +594,12 @@ var createBeacon = (options) => {
513
594
  if (user !== undefined)
514
595
  extra.user = user;
515
596
  enriched.extra = extra;
516
- return options.beforeSend !== undefined ? options.beforeSend(enriched) : enriched;
597
+ const customized = options.beforeSend !== undefined ? options.beforeSend(enriched) : enriched;
598
+ return customized === null || !redact ? customized : redactBeaconEvent(customized);
517
599
  };
518
600
  const push = (event) => {
601
+ if (filterKnownNoise && isKnownBeaconNoise(event))
602
+ return;
519
603
  const enriched = enrich(event);
520
604
  if (enriched === null)
521
605
  return;
@@ -767,9 +851,17 @@ var createBeacon = (options) => {
767
851
  captureException(reason, { level: "error" });
768
852
  return;
769
853
  }
770
- const error = new Error(typeof reason === "string" ? reason : safeStringify(reason));
771
- error.name = "UnhandledRejection";
772
- captureException(error, { level: "error" });
854
+ if (typeof reason === "object" && reason !== null && typeof reason.stack === "string") {
855
+ captureException(reason, { level: "error" });
856
+ return;
857
+ }
858
+ const message = typeof reason === "string" ? reason : safeStringify(reason);
859
+ captureException(errorWithoutStack("UnhandledRejection", message), {
860
+ extra: {
861
+ rejectionType: reason === null ? "null" : Array.isArray(reason) ? "array" : typeof reason
862
+ },
863
+ level: "error"
864
+ });
773
865
  };
774
866
  window.addEventListener("unhandledrejection", onRejection);
775
867
  cleanups.push(() => window.removeEventListener("unhandledrejection", onRejection));
@@ -1002,6 +1094,8 @@ var captureException = (error, context) => current?.captureException(error, cont
1002
1094
  var captureMessage = (message, level) => current?.captureMessage(message, level);
1003
1095
  var addBreadcrumb = (crumb) => current?.addBreadcrumb(crumb);
1004
1096
  export {
1097
+ redactBeaconEvent,
1098
+ isKnownBeaconNoise,
1005
1099
  initBeacon,
1006
1100
  getBeacon,
1007
1101
  createBeacon,
@@ -1013,5 +1107,5 @@ export {
1013
1107
  BEACON_ATTRIBUTE
1014
1108
  };
1015
1109
 
1016
- //# debugId=512F86ACF46BFFBC64756E2164756E21
1110
+ //# debugId=23C46CB4D98EBB6364756E2164756E21
1017
1111
  //# sourceMappingURL=index.js.map