@hanzo/event 0.3.1 → 0.3.3

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/dist/react.cjs CHANGED
@@ -72,6 +72,284 @@ function hasAttribution(a) {
72
72
  // src/events.ts
73
73
  var PAGEVIEW = "$pageview";
74
74
 
75
+ // src/scrub.ts
76
+ var REDACTED = "[redacted]";
77
+ var EMAIL_MARK = "[email]";
78
+ var IP_MARK = "[ip]";
79
+ var SECRET_PATTERNS = [
80
+ /-----BEGIN[ A-Z]*PRIVATE KEY-----[\s\S]*?-----END[ A-Z]*PRIVATE KEY-----/g,
81
+ /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,
82
+ // JWT
83
+ /\bbearer\s+[A-Za-z0-9._~+/-]{12,}=*/gi,
84
+ // bearer token
85
+ /\b(?:sk|pk|rk)-[A-Za-z0-9]{2,}-?[A-Za-z0-9]{12,}/g,
86
+ // openai-style
87
+ /\b(?:sk|pk)_(?:live|test)_[A-Za-z0-9]{16,}/g,
88
+ // stripe
89
+ /\bhk-[A-Za-z0-9]{16,}/g,
90
+ // hanzo key
91
+ /\bAKIA[0-9A-Z]{16}\b/g,
92
+ // aws access key id
93
+ /\bASIA[0-9A-Z]{16}\b/g,
94
+ // aws sts key id
95
+ /\bAIza[0-9A-Za-z_-]{20,}/g,
96
+ // google api key
97
+ /\bgh[posru]_[A-Za-z0-9]{20,}/g,
98
+ // github token
99
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
100
+ // slack token
101
+ // Creds in a URL/DSN. The repetition is BOUNDED on purpose: the unbounded form
102
+ // ([^\s:@/]+:[^\s@/]+@) backtracks quadratically on colon-rich text with no
103
+ // terminating '@' — an HTML error page pasted into an error message took 4.9s
104
+ // at 32KB and >60s at 128KB, freezing the main thread from inside captureError.
105
+ // Real userinfo is far below these caps, so bounding costs nothing.
106
+ /[a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s:@/]{1,256}:[^\s@/]{1,256}@/g
107
+ ];
108
+ var RE_PAN = /\b(?:\d[ -]?){13,19}\b/g;
109
+ function luhn(digits) {
110
+ let sum = 0;
111
+ let alt = false;
112
+ for (let i = digits.length - 1; i >= 0; i--) {
113
+ let d = digits.charCodeAt(i) - 48;
114
+ if (alt) {
115
+ d *= 2;
116
+ if (d > 9) d -= 9;
117
+ }
118
+ sum += d;
119
+ alt = !alt;
120
+ }
121
+ return sum % 10 === 0;
122
+ }
123
+ function redactPAN(s) {
124
+ return s.replace(RE_PAN, (m) => {
125
+ const digits = m.replace(/[ -]/g, "");
126
+ if (digits.length < 13 || digits.length > 19) return m;
127
+ return luhn(digits) ? REDACTED : m;
128
+ });
129
+ }
130
+ var RE_EMAIL = /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g;
131
+ var RE_IPV4 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
132
+ var RE_IPV6 = /\b(?:[0-9A-Fa-f]{1,4}:){2,7}[0-9A-Fa-f]{1,4}\b/g;
133
+ function redactSecrets(s) {
134
+ for (const re of SECRET_PATTERNS) s = s.replace(re, REDACTED);
135
+ return redactPAN(s);
136
+ }
137
+ function scrubPII(s) {
138
+ s = s.replace(RE_EMAIL, EMAIL_MARK);
139
+ s = s.replace(RE_IPV6, IP_MARK);
140
+ s = s.replace(RE_IPV4, IP_MARK);
141
+ return s;
142
+ }
143
+ var MAX_SCRUB_LEN = 8192;
144
+ function truncate(s, max = MAX_SCRUB_LEN) {
145
+ return s.length > max ? s.slice(0, max) + "\u2026 [truncated]" : s;
146
+ }
147
+ function scrubText(s, capturePII = false) {
148
+ if (!s) return s ?? "";
149
+ s = truncate(s);
150
+ s = redactSecrets(s);
151
+ if (!capturePII) s = scrubPII(s);
152
+ return s;
153
+ }
154
+
155
+ // src/version.ts
156
+ var VERSION = "0.3.3";
157
+
158
+ // src/sentry.ts
159
+ var MAX_FRAMES = 50;
160
+ var MAX_LINES = 500;
161
+ var MAX_LINE_LEN = 2048;
162
+ var MAX_TAG_LEN = 1024;
163
+ var MAX_TAGS = 50;
164
+ function eventId() {
165
+ const c = typeof crypto !== "undefined" ? crypto : void 0;
166
+ if (c && "randomUUID" in c) return c.randomUUID().replace(/-/g, "");
167
+ let s = "";
168
+ for (let i = 0; i < 32; i++) s += Math.floor(Math.random() * 16).toString(16);
169
+ return s;
170
+ }
171
+ function byteLen(s) {
172
+ if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(s).length;
173
+ if (typeof Buffer !== "undefined") return Buffer.byteLength(s, "utf8");
174
+ return s.length;
175
+ }
176
+ function parseDsn(dsn) {
177
+ if (!dsn) return null;
178
+ const m = /^(https?):\/\/([^@]+)@([^/]+)(\/.*)?$/.exec(dsn.trim());
179
+ if (!m) return null;
180
+ const scheme = m[1];
181
+ const publicKey = m[2];
182
+ const host = m[3];
183
+ const path = m[4] ?? "";
184
+ if (!publicKey || !host) return null;
185
+ const segs = path.split("/").filter(Boolean);
186
+ const projectId = segs.length > 0 ? segs[segs.length - 1] : "";
187
+ if (!projectId) return null;
188
+ const origin = `${scheme}://${host}`;
189
+ const ingestUrl = `${origin}/v1/sentry/${encodeURIComponent(projectId)}/envelope/?sentry_key=${encodeURIComponent(publicKey)}`;
190
+ return { publicKey, origin, projectId, ingestUrl };
191
+ }
192
+ var V8_FRAME = /^\s*at\s+(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+)|([^)]+))\)?\s*$/;
193
+ var MOZ_FRAME = /^\s*(?:(.*?)@)?(.+?):(\d+):(\d+)\s*$/;
194
+ function inApp(file) {
195
+ if (!file) return false;
196
+ return !(file.includes("node_modules") || file.startsWith("webpack-internal") || file.startsWith("webpack://") || file.startsWith("chrome-extension://") || file.startsWith("moz-extension://"));
197
+ }
198
+ function framesFromStack(stack) {
199
+ if (!stack) return [];
200
+ const lines = stack.split("\n", MAX_LINES);
201
+ const frames = [];
202
+ for (const raw of lines) {
203
+ if (raw.length > MAX_LINE_LEN) continue;
204
+ const line = raw.trimEnd();
205
+ if (!line) continue;
206
+ let fn;
207
+ let file = "";
208
+ let lineno = 0;
209
+ let colno = 0;
210
+ const v = V8_FRAME.exec(line);
211
+ if (v) {
212
+ fn = v[1];
213
+ if (v[2]) {
214
+ file = v[2];
215
+ lineno = Number(v[3]) || 0;
216
+ colno = Number(v[4]) || 0;
217
+ } else {
218
+ file = (v[5] || "").trim();
219
+ }
220
+ } else {
221
+ const f = MOZ_FRAME.exec(line);
222
+ if (!f) continue;
223
+ fn = f[1];
224
+ file = f[2];
225
+ lineno = Number(f[3]) || 0;
226
+ colno = Number(f[4]) || 0;
227
+ }
228
+ if (!file && !fn) continue;
229
+ frames.push({
230
+ function: fn || "<anonymous>",
231
+ filename: file,
232
+ abs_path: file,
233
+ lineno,
234
+ colno,
235
+ in_app: inApp(file)
236
+ });
237
+ }
238
+ frames.reverse();
239
+ if (frames.length > MAX_FRAMES) return frames.slice(frames.length - MAX_FRAMES);
240
+ return frames;
241
+ }
242
+ function normalizeError(err) {
243
+ if (err instanceof Error) {
244
+ const name = read(err, "name");
245
+ const message = read(err, "message");
246
+ const stack = read(err, "stack");
247
+ return {
248
+ name: typeof name === "string" && name ? name : "Error",
249
+ message: typeof message === "string" && message ? message : str(err),
250
+ stack: typeof stack === "string" ? stack : void 0
251
+ };
252
+ }
253
+ if (typeof err === "string") return { name: "Error", message: err };
254
+ try {
255
+ return { name: "Error", message: JSON.stringify(err) ?? str(err) };
256
+ } catch {
257
+ return { name: "Error", message: str(err) };
258
+ }
259
+ }
260
+ function read(o, k) {
261
+ try {
262
+ return o[k];
263
+ } catch {
264
+ return void 0;
265
+ }
266
+ }
267
+ function str(v) {
268
+ try {
269
+ return String(v);
270
+ } catch {
271
+ return "[unstringifiable]";
272
+ }
273
+ }
274
+ function coerceTag(v) {
275
+ const s = typeof v === "string" ? v : (() => {
276
+ try {
277
+ return JSON.stringify(v) ?? String(v);
278
+ } catch {
279
+ try {
280
+ return String(v);
281
+ } catch {
282
+ return "[unstringifiable]";
283
+ }
284
+ }
285
+ })();
286
+ return s.length > MAX_TAG_LEN ? s.slice(0, MAX_TAG_LEN) : s;
287
+ }
288
+ function buildSentryEvent(input) {
289
+ const { error, options = {}, identity, capturePII = false } = input;
290
+ const norm = normalizeError(error);
291
+ const handled = options.handled !== false;
292
+ const level = options.level ?? (handled ? "error" : "fatal");
293
+ const tags = { handled: String(handled) };
294
+ if (identity.product) tags.product = identity.product;
295
+ if (identity.sessionId) tags.session = identity.sessionId;
296
+ try {
297
+ const props = options.properties ?? {};
298
+ let n = 0;
299
+ for (const k of Object.keys(props)) {
300
+ if (n >= MAX_TAGS) break;
301
+ try {
302
+ const val = props[k];
303
+ if (val === void 0 || val === null) continue;
304
+ tags[k] = scrubText(coerceTag(val), capturePII);
305
+ n++;
306
+ } catch {
307
+ continue;
308
+ }
309
+ }
310
+ } catch {
311
+ }
312
+ const event = {
313
+ event_id: input.id ?? eventId(),
314
+ timestamp: (input.now ?? Date.now()) / 1e3,
315
+ platform: "javascript",
316
+ level,
317
+ logger: identity.product,
318
+ environment: identity.environment,
319
+ release: identity.release,
320
+ exception: {
321
+ values: [
322
+ {
323
+ type: norm.name,
324
+ value: scrubText(norm.message, capturePII),
325
+ stacktrace: { frames: framesFromStack(norm.stack) }
326
+ }
327
+ ]
328
+ },
329
+ tags,
330
+ sdk: { name: "@hanzo/event", version: VERSION }
331
+ };
332
+ if (identity.userId) event.user = { id: identity.userId };
333
+ return event;
334
+ }
335
+ function buildEnvelope(event, dsn, sentAt) {
336
+ const payload = JSON.stringify(event);
337
+ const header = JSON.stringify({
338
+ event_id: event.event_id,
339
+ dsn: `${dsn.origin}/v1/sentry/${dsn.projectId}`,
340
+ sent_at: (/* @__PURE__ */ new Date()).toISOString()
341
+ });
342
+ const itemHeader = JSON.stringify({
343
+ type: "event",
344
+ content_type: "application/json",
345
+ length: byteLen(payload)
346
+ });
347
+ return `${header}
348
+ ${itemHeader}
349
+ ${payload}
350
+ `;
351
+ }
352
+
75
353
  // src/storage.ts
76
354
  var KEY = {
77
355
  anon: "hz_anon_id",
@@ -160,9 +438,25 @@ function mergeCohort(patch) {
160
438
  }
161
439
 
162
440
  // src/core.ts
163
- var VERSION = "0.3.0";
164
441
  var EVENT_PATH = "/v1/event";
165
442
  var DEFAULT_HOST = "https://api.hanzo.ai";
443
+ var ENVELOPE_CONTENT_TYPE = "application/x-sentry-envelope";
444
+ function readEnvDsn() {
445
+ try {
446
+ if (typeof process !== "undefined" && process.env) {
447
+ return process.env.NEXT_PUBLIC_HANZO_EVENT_DSN || process.env.HANZO_EVENT_DSN || void 0;
448
+ }
449
+ } catch {
450
+ }
451
+ return void 0;
452
+ }
453
+ function readEnv(name) {
454
+ try {
455
+ if (typeof process !== "undefined" && process.env) return process.env[name] || void 0;
456
+ } catch {
457
+ }
458
+ return void 0;
459
+ }
166
460
  function appendQuery(url, key, value) {
167
461
  return url + (url.includes("?") ? "&" : "?") + key + "=" + encodeURIComponent(value);
168
462
  }
@@ -171,30 +465,42 @@ function uid2() {
171
465
  if (c && "randomUUID" in c) return c.randomUUID();
172
466
  return "m-" + Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
173
467
  }
174
- function normalizeError(err) {
175
- if (err instanceof Error) {
176
- return { type: err.name, message: err.message, stack: err.stack };
177
- }
178
- if (typeof err === "string") return { message: err };
468
+ function normalizeError2(err) {
469
+ const n = normalizeError(err);
470
+ return { type: n.name, message: n.message, stack: n.stack };
471
+ }
472
+ var isBrowser = () => typeof window !== "undefined";
473
+ function serializeBatch(batch) {
179
474
  try {
180
- return { message: JSON.stringify(err) };
475
+ return JSON.stringify({ batch });
181
476
  } catch {
182
- return { message: String(err) };
183
477
  }
478
+ const parts = [];
479
+ for (const e of batch) {
480
+ try {
481
+ parts.push(JSON.stringify(e));
482
+ } catch {
483
+ try {
484
+ parts.push(JSON.stringify({ ...e, properties: { $unserializable: true } }));
485
+ } catch {
486
+ }
487
+ }
488
+ }
489
+ return parts.length > 0 ? '{"batch":[' + parts.join(",") + "]}" : null;
184
490
  }
185
- var isBrowser = () => typeof window !== "undefined";
186
491
  var DefaultTransport = class {
187
492
  send(url, body, opts) {
493
+ const contentType = opts.contentType ?? "application/json";
188
494
  if (opts.beacon && isBrowser() && typeof navigator.sendBeacon === "function") {
189
495
  const beaconUrl = opts.ingestKey ? appendQuery(url, "ingest_key", opts.ingestKey) : url;
190
496
  try {
191
- navigator.sendBeacon(beaconUrl, new Blob([body], { type: "application/json" }));
497
+ navigator.sendBeacon(beaconUrl, new Blob([body], { type: contentType }));
192
498
  return;
193
499
  } catch {
194
500
  }
195
501
  }
196
502
  if (typeof fetch !== "function") return;
197
- const headers = { "Content-Type": "application/json" };
503
+ const headers = { "Content-Type": contentType };
198
504
  const bearer = opts.ingestKey ?? opts.token;
199
505
  if (bearer) headers.Authorization = `Bearer ${bearer}`;
200
506
  void fetch(url, {
@@ -203,7 +509,12 @@ var DefaultTransport = class {
203
509
  body,
204
510
  keepalive: true,
205
511
  credentials: "include"
206
- }).catch(() => {
512
+ }).then((res) => {
513
+ if (!res.ok && opts.debug) {
514
+ console.warn("[event] ingest rejected", res.status, url.split("?")[0]);
515
+ }
516
+ }).catch((e) => {
517
+ if (opts.debug) console.warn("[event] ingest failed", url.split("?")[0], e);
207
518
  });
208
519
  }
209
520
  };
@@ -214,6 +525,8 @@ var Analytics = class {
214
525
  this.attribution = { utm: {} };
215
526
  this.cohort = {};
216
527
  this.started = false;
528
+ /** Guards against an error thrown *inside* the error path re-entering it. */
529
+ this.reentrant = false;
217
530
  /** track is an alias of capture (Segment familiarity). */
218
531
  this.track = this.capture.bind(this);
219
532
  /** captureException — @sentry-familiar alias of captureError. */
@@ -227,6 +540,19 @@ var Analytics = class {
227
540
  ...config
228
541
  };
229
542
  this.transport = config.transport ?? new DefaultTransport();
543
+ this.dsn = parseDsn(config.dsn ?? readEnvDsn());
544
+ }
545
+ /** errorPlaneEnabled reports whether captured exceptions can actually reach the
546
+ * error host. False means a DSN was never configured — the documented
547
+ * fail-safe. Exposed so an app (or a test) can assert its wiring instead of
548
+ * discovering months later that nothing was ever reported. */
549
+ get errorPlaneEnabled() {
550
+ return this.dsn !== null;
551
+ }
552
+ /** errorIngestUrl is the fully-derived envelope endpoint, or undefined when the
553
+ * plane is inert. Diagnostics only. */
554
+ get errorIngestUrl() {
555
+ return this.dsn?.ingestUrl;
230
556
  }
231
557
  /** init is idempotent and browser-only for its side effects: capture first-touch
232
558
  * attribution, hydrate cohort, register the unload flush, and (unless opted out)
@@ -277,18 +603,38 @@ var Analytics = class {
277
603
  capture(event, properties, commerce) {
278
604
  this.enqueue("event", event, { properties, ...commerce });
279
605
  }
280
- /** captureError records an exception as a first-class error event the ONE
281
- * error path (subsumes @sentry). A caught error, an unhandled rejection, a
282
- * React render error, or a manual report all become a type:'error' event on the
283
- * same stream; Cloud folds the exception into properties.$exception and stamps
284
- * event_type='error', so it surfaces in the error-tracking lens. Never throws
285
- * back into the app; errors are higher-signal than pageviews, so it flushes
286
- * promptly (a crash may unload the page moments later). */
606
+ /** captureError reports a caught error, an unhandled rejection, a React render
607
+ * error, or a manual report to BOTH planes, from one call:
608
+ *
609
+ * - the ERROR PLANE — a real Sentry envelope to the DSN host. This is the one
610
+ * that produces an issue in sentry.hanzo.ai (grouping, stack frames, AST).
611
+ * Inert when no DSN is configured.
612
+ * - the EVENT STREAM — a `type:'error'` row in the cloud event warehouse, so
613
+ * an error stays correlated with the session's pageviews for product
614
+ * analysis (readable via GET /v1/errors).
615
+ *
616
+ * Both carry the SAME session and subject id, so an error and the pageview
617
+ * before it join up. Never throws back into the app; errors are higher-signal
618
+ * than pageviews, so both planes flush promptly (a crash may unload the page
619
+ * moments later). */
287
620
  captureError(err, context) {
288
- const ex = normalizeError(err);
289
- ex.handled = context?.handled ?? true;
290
- this.enqueue("error", ex.message, { error: ex, properties: context?.properties });
291
- this.flush();
621
+ if (this.reentrant) return;
622
+ this.reentrant = true;
623
+ try {
624
+ try {
625
+ this.sendError(err, context);
626
+ } catch {
627
+ }
628
+ try {
629
+ const ex = normalizeError2(err);
630
+ ex.handled = context?.handled ?? true;
631
+ this.enqueue("error", ex.message, { error: ex, properties: context?.properties });
632
+ this.flush();
633
+ } catch {
634
+ }
635
+ } finally {
636
+ this.reentrant = false;
637
+ }
292
638
  }
293
639
  /** setCohort persists cohort dimensions (e.g. signupWeek at signup) so they ride
294
640
  * every subsequent event. */
@@ -314,11 +660,53 @@ var Analytics = class {
314
660
  const key = this.cfg.ingestKey?.trim() || void 0;
315
661
  const token = key ? void 0 : this.cfg.getToken?.() ?? void 0;
316
662
  const useBeacon = beacon && !token;
317
- const body = JSON.stringify({ batch });
663
+ const body = serializeBatch(batch);
664
+ if (body === null) {
665
+ if (this.cfg.debug) console.debug("[event] flush \u2192 dropped, batch unserializable");
666
+ return;
667
+ }
318
668
  if (this.cfg.debug) console.debug("[event] flush \u2192", EVENT_PATH, batch.length);
319
- this.transport.send(this.cfg.host + EVENT_PATH, body, { beacon: useBeacon, token, ingestKey: key });
669
+ this.transport.send(this.cfg.host + EVENT_PATH, body, {
670
+ beacon: useBeacon,
671
+ token,
672
+ ingestKey: key,
673
+ debug: this.cfg.debug
674
+ });
320
675
  }
321
676
  // ── internals ────────────────────────────────────────────────────────────
677
+ /** sendError frames one exception as a Sentry envelope and posts it to the DSN's
678
+ * ingest URL. The DSN's own key rides ?sentry_key= (the credential channel the
679
+ * server trusts, and the only one a headerless beacon can carry), so NO bearer
680
+ * or publishable key is attached here — the two planes authenticate
681
+ * independently. Errors are sent one envelope per event, immediately: batching
682
+ * a crash report is how you lose it. */
683
+ sendError(err, options) {
684
+ if (!this.cfg.enabled || !this.dsn) return;
685
+ const event = buildSentryEvent({
686
+ error: err,
687
+ options,
688
+ identity: this.errorIdentity(),
689
+ capturePII: this.cfg.capturePII ?? false
690
+ });
691
+ const body = buildEnvelope(event, this.dsn);
692
+ if (this.cfg.debug) console.debug("[event] error \u2192", this.dsn.ingestUrl, event.event_id);
693
+ this.transport.send(this.dsn.ingestUrl, body, {
694
+ beacon: false,
695
+ contentType: ENVELOPE_CONTENT_TYPE,
696
+ debug: this.cfg.debug
697
+ });
698
+ }
699
+ /** errorIdentity is the SAME identity the event stream stamps — the OIDC subject
700
+ * once identify() has run, else the anon id. Never email/PII. */
701
+ errorIdentity() {
702
+ return {
703
+ userId: this.personId ?? anonId(),
704
+ sessionId: sessionId(),
705
+ product: this.cfg.product,
706
+ release: this.cfg.release ?? readEnv("NEXT_PUBLIC_HANZO_RELEASE"),
707
+ environment: this.cfg.environment ?? readEnv("NODE_ENV")
708
+ };
709
+ }
322
710
  enqueue(kind, event, extra) {
323
711
  if (!this.cfg.enabled) return;
324
712
  if (!this.started) this.init();