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