zeno.id 0.7.0 → 0.8.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.
@@ -1,4 +1,70 @@
1
- import { a as ApiOptions, i as ApiKey, n as ProxyOptions, r as createProxy, t as ProxyHandler } from "./proxy-CUZ-Jwgy.js";
1
+ //#region src/server/util.d.ts
2
+ /** The project's API key, `sk_...`, from your server's environment: `process.env.ZENO_API_KEY`. */
3
+ type ApiKey = string | undefined;
4
+ /** Options both createClient and createProxyResponse take. */
5
+ type ApiOptions = {
6
+ /** The Zeno API's http(s) origin, for staging or a local Zeno. Zeno's own API by default. */
7
+ apiUrl?: string | undefined;
8
+ };
9
+ //#endregion
10
+ //#region src/server/proxy.d.ts
11
+ /** What `createProxyResponse` takes: the browser's request to your route, the IP it came from and your API key. */
12
+ type ProxyRequest = ApiOptions & {
13
+ /** The browser's request to your proxy route, a web `Request`. */
14
+ request: Request;
15
+ /**
16
+ * The IP address the request came from, your framework's client IP; behind a proxy of your own, turn on your
17
+ * framework's trust-proxy setting so it's the visitor's. Zeno refuses an identification without it (`400`).
18
+ */
19
+ ip: string | null | undefined;
20
+ /** Your API key, from your server's environment: `process.env.ZENO_API_KEY`. */
21
+ apiKey: ApiKey;
22
+ };
23
+ /**
24
+ * Your proxy route's answer: a route on your own site between the browser SDK and the Zeno API. It forwards the
25
+ * browser's request to Zeno with your API key and the visitor's IP, and returns Zeno's answer: the script, or an
26
+ * identification's request ID with the visitor ID in a first-party cookie. Call it for every request on one path of
27
+ * your choice (the browser SDK's `path`, like `/zeno`); Zeno decides what each gets. The `apiKey` (undefined accepted)
28
+ * is checked on each call, so a module that reads it at load builds without the environment (as Next.js does when it
29
+ * collects page data); a request without it answers `500` and logs it. On Node's `(req, res)`, use `nodeHandler` from
30
+ * `zeno.id/server`.
31
+ */
32
+ declare const createProxyResponse: (options: ProxyRequest) => Promise<Response>;
33
+ type NodeRequest = AsyncIterable<Uint8Array | string> & {
34
+ method?: string;
35
+ url?: string;
36
+ headers: {
37
+ host?: string;
38
+ };
39
+ rawHeaders: string[];
40
+ readableEnded: boolean;
41
+ socket: {
42
+ remoteAddress?: string;
43
+ encrypted?: boolean;
44
+ };
45
+ };
46
+ type NodeResponse = {
47
+ statusCode: number;
48
+ headersSent: boolean;
49
+ setHeader(name: string, value: string | string[]): unknown;
50
+ end(body?: Uint8Array | string): unknown;
51
+ };
52
+ type FastifyRequest = {
53
+ raw: NodeRequest;
54
+ ip?: unknown;
55
+ };
56
+ type FastifyReply = {
57
+ raw: NodeResponse;
58
+ hijack(): unknown;
59
+ };
60
+ /**
61
+ * Your proxy route on Node's `(req, res)`: Express, Fastify or `http.createServer`. `app.all('/zeno', nodeHandler({
62
+ * apiKey: process.env.ZENO_API_KEY }))`. It passes `createProxyResponse` the request and the IP address it came from:
63
+ * Express's and Fastify's `req.ip` (behind a proxy of your own, set their trust proxy so it's the visitor's), else the
64
+ * socket's address. Mount it before any body parser (`express.json()`): it forwards the body as it came.
65
+ */
66
+ declare const nodeHandler: (options: Omit<ProxyRequest, 'request' | 'ip'>) => (request: NodeRequest | FastifyRequest, response: NodeResponse | FastifyReply) => Promise<void>;
67
+ //#endregion
2
68
  //#region src/server/index.d.ts
3
69
  /** Every signal an event checks, the keys of its `signals`. */
4
70
  declare const SIGNALS: readonly ['automation', 'headless', 'software-renderer', 'tampering', 'timezone-mismatch', 'privacy-settings', 'vpn', 'proxy', 'tor', 'datacenter', 'abusive-ip', 'incognito', 'virtual-machine', 'developer-tools', 'ai-agent', 'privacy-browser', 'high-activity', 'replayed', 'residential-proxy', 'private-relay', 'forged-payload', 'stored-id-rejected', 'storage-cleared'];
@@ -286,6 +352,8 @@ type Event = {
286
352
  */
287
353
  returning?: boolean;
288
354
  externalId?: string;
355
+ /** The external ID's scope, when your server set one (`verify`). */
356
+ scope?: string;
289
357
  /** What the visitor was doing, as the browser's `identify({ action })` named it, like `login`. */
290
358
  action?: string;
291
359
  /** Your own key-values from the browser's `identify({ metadata })`. Not in search results. */
@@ -299,7 +367,7 @@ type Event = {
299
367
  */
300
368
  updatedAt?: string;
301
369
  origin?: string;
302
- /** The page as origin and path, or only its origin; left out when the project keeps no page urls (`pageUrls`). */
370
+ /** The page as origin and path, never its query string or fragment. */
303
371
  url?: string;
304
372
  referrer?: string;
305
373
  browser: EventBrowser;
@@ -322,25 +390,25 @@ type Event = {
322
390
  radius: number;
323
391
  confidence: number;
324
392
  };
325
- /** Only on getEvent and verify, not in webhooks or sealed results. */
393
+ /** Only on getEvent and verify, not in webhooks. */
326
394
  rawDeviceAttributes?: RawDeviceAttributes;
327
- /** Only on getEvent and verify, not in webhooks or sealed results. */
395
+ /** Only on getEvent and verify, not in webhooks. */
328
396
  velocity?: Record<'5m' | '1h' | '24h', Velocity>;
329
397
  /**
330
- * Your other users this event ties to, by external id: those sharing its `visitorId`, its residential IP
398
+ * Your other users this event ties to, by external ID and scope: those sharing its `visitorId`, its residential IP
331
399
  * (`residentialIp`), and both its `broadVisitorId` and its IP (`broadVisitorId`, as a broad visitor ID isn't strong
332
- * enough on its own). Up to 25 of each. Only on getEvent and verify, not in webhooks or sealed results.
400
+ * enough on its own). Up to 25 of each. Only on getEvent and verify, not in webhooks.
333
401
  */
334
402
  related?: {
335
- visitorId: string[];
336
- residentialIp: string[];
337
- broadVisitorId: string[];
403
+ visitorId: ExternalIdRef[];
404
+ residentialIp: ExternalIdRef[];
405
+ broadVisitorId: ExternalIdRef[];
338
406
  };
339
407
  /**
340
408
  * The group of the event's user: one ID that every user tied to it through a shared strong value answers too (a
341
409
  * visitor ID with the default weights), directly or through other users. Without an external ID, the group its
342
410
  * visitor ID ties. `null` when there is none. It can change when groups join or come apart, so key a counter on it
343
- * and keep what must last on your own user. Only on getEvent and verify, not in webhooks or sealed results.
411
+ * and keep what must last on your own user. Only on getEvent and verify, not in webhooks.
344
412
  */
345
413
  groupId?: string | null;
346
414
  } & GlobalFields;
@@ -350,6 +418,8 @@ type SearchFilters = {
350
418
  apiKeyId?: AnyOf<string>;
351
419
  visitorId?: string;
352
420
  externalId?: string;
421
+ /** The `externalId`'s scope; without one, the user without a scope. */
422
+ scope?: string;
353
423
  ip?: string;
354
424
  requestId?: string;
355
425
  country?: AnyOf<string>;
@@ -381,7 +451,7 @@ type SearchFilters = {
381
451
  * version, and its `ip` the address with the country, city, asn and company, each left out when the event has none of
382
452
  * them.
383
453
  */
384
- type SearchEvent = Pick<Event, 'requestId' | 'visitorId' | 'verdict' | 'riskScore' | 'bot' | 'outcome' | 'confidence' | 'externalId' | 'action' | 'apiKeyId' | 'createdAt' | 'origin'> & {
454
+ type SearchEvent = Pick<Event, 'requestId' | 'visitorId' | 'verdict' | 'riskScore' | 'bot' | 'outcome' | 'confidence' | 'externalId' | 'scope' | 'action' | 'apiKeyId' | 'createdAt' | 'origin'> & {
385
455
  signals: { [S in Signal]?: {
386
456
  detected: true;
387
457
  }; };
@@ -400,6 +470,19 @@ type Page<T> = {
400
470
  type SearchResult = Page<SearchEvent> & {
401
471
  found?: number;
402
472
  };
473
+ /**
474
+ * One of your users as Zeno names it in an answer: your external ID and, when you gave it one, its scope. `user-1042`
475
+ * in `tenant-1` and in `tenant-2` are two users.
476
+ */
477
+ type ExternalIdRef = {
478
+ externalId: string;
479
+ scope?: string;
480
+ };
481
+ /**
482
+ * The scopes a read covers: one, several, or `'*'` for every scope, as when it's left out. Users of two scopes are
483
+ * never related.
484
+ */
485
+ type Scopes = string | string[];
403
486
  /**
404
487
  * What relates two users: the built-in `visitor-id` (a browser), `broad-visitor-id` (its hardware), `residential-ip`
405
488
  * (an ip of an internet provider, not a VPN, proxy or mobile network), all three from events only, and `ip`, or a type
@@ -433,9 +516,11 @@ type RelatedWeight = {
433
516
  /** One of Zeno's own types (`visitor-id`, `ip`, ...), not one of yours. */
434
517
  builtIn: boolean;
435
518
  };
436
- /** A user's group: everyone tied to the user through shared strong values, directly or through other users. */
437
- type RelatedGroup = {
438
- externalId: string;
519
+ /**
520
+ * A user's group: everyone tied to the user through shared strong values, directly or through other users, all in the
521
+ * user's scope.
522
+ */
523
+ type RelatedGroup = ExternalIdRef & {
439
524
  /** The same for every user in the group. `null` for a user Zeno has no values of. */
440
525
  groupId: string | null;
441
526
  /**
@@ -444,7 +529,7 @@ type RelatedGroup = {
444
529
  */
445
530
  size: number;
446
531
  /** A page of the group's users, the asked one among them: no weights, no depth. Empty without a group ID. */
447
- externalIds: string[];
532
+ externalIds: ExternalIdRef[];
448
533
  /** Pass it back for the next page; none on the last page. */
449
534
  cursor?: string;
450
535
  };
@@ -455,7 +540,7 @@ type Group = {
455
540
  /** How many users the group has, up to 10,000: a larger group is answered as 10,000 of its users. */
456
541
  size: number;
457
542
  /** A page of the group's users: no weights, no depth. */
458
- externalIds: string[];
543
+ externalIds: ExternalIdRef[];
459
544
  /** Pass it back for the next page; none on the last page. */
460
545
  cursor?: string;
461
546
  };
@@ -463,16 +548,15 @@ type Group = {
463
548
  type RelatedValue = ValueDetails & {
464
549
  value: string;
465
550
  };
466
- type RelatedValues = {
467
- externalId: string;
551
+ type RelatedValues = ExternalIdRef & {
468
552
  /**
469
553
  * The user's group, the same on every page. `null` for a user Zeno has no values of, and for a group of more than
470
554
  * 10,000 users, which has no ID.
471
555
  */
472
556
  groupId: string | null;
473
557
  /**
474
- * Shares one value weighing 0.75 or more with another user: with the default weights a visitor id does, a
475
- * residential ip or a type of your own only once you weigh it that much. Lesser ties never add up to one.
558
+ * Shares one value weighing 0.75 or more with another user of its scope: with the default weights a visitor id
559
+ * does, a residential ip or a type of your own only once you weigh it that much. Lesser ties never add up to one.
476
560
  */
477
561
  duplicate: boolean;
478
562
  /** Was ever identified in a browser; treat a user who wasn't as unverified. */
@@ -482,9 +566,8 @@ type RelatedValues = {
482
566
  /** Pass it back for the next page; none on the last page. */
483
567
  cursor?: string;
484
568
  };
485
- /** Another user (`externalId`) who shares a `value` with the asked one. */
486
- type Connection = ValueDetails & {
487
- externalId: string;
569
+ /** Another user (`externalId` in `scope`) who shares a `value` with the asked one. */
570
+ type Connection = ValueDetails & ExternalIdRef & {
488
571
  value: string;
489
572
  };
490
573
  /** A value two or more of the users found share, with each of the users who share it and when they got it. */
@@ -493,11 +576,10 @@ type SharedValue = {
493
576
  /** The type's weight, 0 to 1. */
494
577
  weight: number;
495
578
  value: string;
496
- externalIds: {
497
- externalId: string;
579
+ externalIds: (ExternalIdRef & {
498
580
  at: string;
499
581
  createdAt: string;
500
- }[];
582
+ })[];
501
583
  };
502
584
  /**
503
585
  * Two of the related users who share values: `a` and `b` are their indexes in `externalIds` (`a` the lower), and
@@ -506,6 +588,8 @@ type SharedValue = {
506
588
  type RelatedPair = [a: number, b: number, values: number[]];
507
589
  type Related = {
508
590
  externalId: string;
591
+ /** The scopes asked for; none for every scope. */
592
+ scope?: Scopes;
509
593
  /** The type asked for; none when every type was walked. */
510
594
  type?: RelatedType;
511
595
  /**
@@ -513,10 +597,9 @@ type Related = {
513
597
  * (`1 - Π(1 - weight)`, so with the default weights two shared ips make 0.44 and a visitor id and an ip 0.96),
514
598
  * multiplied along the strongest path for a user further away.
515
599
  */
516
- externalIds: {
517
- externalId: string;
600
+ externalIds: (ExternalIdRef & {
518
601
  weight: number;
519
- }[];
602
+ })[];
520
603
  /** What the asked user shares with others: one entry per other user and shared value. */
521
604
  connections: Connection[];
522
605
  /**
@@ -546,19 +629,17 @@ type Related = {
546
629
  * one to continue the search from that user. The asked user is in the list when it has more values than one search
547
630
  * follows: pass a `type`, or page its values with `getRelatedValues`.
548
631
  */
549
- stoppedAt: string[];
632
+ stoppedAt: ExternalIdRef[];
550
633
  };
551
634
  /** One of your users who has a value, and since when. */
552
- type RelatedUser = {
553
- externalId: string;
635
+ type RelatedUser = ExternalIdRef & {
554
636
  createdAt: string;
555
637
  };
556
638
  /**
557
639
  * A relation: an ip seen by another system (`type: 'ip'`) or a value of a type of your own (`{ type: 'payment-card',
558
640
  * value }`). Its weight isn't part of it: the project holds each type's weight, applied when related users are read.
559
641
  */
560
- type RelationTarget = {
561
- externalId: string;
642
+ type RelationTarget = ExternalIdRef & {
562
643
  type: RelatedType;
563
644
  value: string;
564
645
  };
@@ -628,6 +709,11 @@ type VerifyOptions = {
628
709
  * succeeded (the password matched, the account exists), with the user's ID, so a failed login attaches nothing.
629
710
  */
630
711
  externalId?: string;
712
+ /**
713
+ * The scope the user is in, like `tenant-1`, when your users are in scopes: the same `externalId` in another scope
714
+ * is another user. Only with `externalId`.
715
+ */
716
+ scope?: string;
631
717
  /**
632
718
  * Makes sending the same verify again safe: a repeat with this key within 5 minutes answers what the first did,
633
719
  * instead of `already-used`. The SDK makes one per call and retries a lost answer with it itself; pass your own (8
@@ -644,8 +730,7 @@ type VerifyResult = {
644
730
  reasons: (VerifyCheck | VerdictReason)[];
645
731
  /**
646
732
  * The event, from `verify` with its velocity as `getEvent` has it (`event.velocity['24h'].distinctExternalId`, or
647
- * `sameAction` without external IDs), its velocity counted before verify attached your `externalId`. Only from
648
- * `verify`: `unsealResult` runs on your server and has no velocity.
733
+ * `sameAction` without external IDs), its velocity counted before verify attached your `externalId`.
649
734
  */
650
735
  event?: Event;
651
736
  };
@@ -687,16 +772,20 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
687
772
  visitorId: string;
688
773
  deletedEvents: number;
689
774
  }>;
690
- /** Deletes everything stored for one of your users: their events, and what relates them to devices and others. */
691
- deleteExternalId: (externalId: string) => Promise<{
692
- externalId: string;
775
+ /**
776
+ * Deletes everything stored for one of your users (in its `scope`, when it has one): their events, and what
777
+ * relates them to devices and others.
778
+ */
779
+ deleteExternalId: (externalId: string, { scope }?: {
780
+ scope?: string;
781
+ }) => Promise<ExternalIdRef & {
693
782
  deletedEvents: number;
694
783
  }>;
695
784
  /**
696
- * Adds a relation to one of your users: an ip seen by another system, or a value of a type of your own (a
697
- * card's fingerprint, your own device id). Users who have the same value are related; you never relate two
698
- * users yourself. Visitor ids only come from events with an external id, so `identified` means the user was
699
- * seen in a browser.
785
+ * Adds a relation to one of your users (in its `scope`, when it has one): an ip seen by another system, or a
786
+ * value of a type of your own (a card's fingerprint, your own device id). Users who have the same value are
787
+ * related, never across scopes; you never relate two users yourself. Visitor ids only come from events with an
788
+ * external id, so `identified` means the user was seen in a browser.
700
789
  *
701
790
  * Free, like reads. `created` says whether the call added the value; sending one again only brings it up to
702
791
  * date.
@@ -712,39 +801,46 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
712
801
  removed: boolean;
713
802
  }>;
714
803
  /**
715
- * One of your users' values, of one `type` or every type, each with its weight, whether they share one value
716
- * weighing 0.75 or more with another user (`duplicate`) and their group (`groupId`). 500 a page by default
717
- * (`limit` up to 500); pass the cursor back for the next page.
804
+ * One of your users' values (in its `scope`, when it has one), of one `type` or every type, each with its
805
+ * weight, whether they share one value weighing 0.75 or more with another user of the scope (`duplicate`) and
806
+ * their group (`groupId`). 500 a page by default (`limit` up to 500); pass the cursor back for the next page.
718
807
  */
719
- getRelatedValues: (externalId: string, { type, ...page }?: {
808
+ getRelatedValues: (externalId: string, { scope, type, ...page }?: {
809
+ scope?: string;
720
810
  type?: RelatedType;
721
811
  limit?: number;
722
812
  cursor?: string;
723
813
  }) => Promise<RelatedValues>;
724
814
  /**
725
- * Your users who have one value, like everyone who paid with one card, 20 a page by default (`limit` up to
726
- * 100); pass the cursor back for the next page.
815
+ * Your users who have one value, like everyone who paid with one card, in the `scope` you pass (several, or
816
+ * `'*'` for every scope, as without one), 20 a page by default (`limit` up to 100); pass the cursor back for
817
+ * the next page.
727
818
  */
728
- lookupRelated: (type: RelatedType, value: string, page?: {
819
+ lookupRelated: (type: RelatedType, value: string, { scope, ...page }?: {
820
+ scope?: Scopes;
729
821
  limit?: number;
730
822
  cursor?: string;
731
823
  }) => Promise<Page<RelatedUser>>;
732
824
  /**
733
825
  * Your users related to one through shared values of every type, or of one `type`, up to `depth` (1 or 2, 1 by
734
- * default) hops away, heaviest first, each with its weight. A deeper search reads more and takes longer.
826
+ * default) hops away, heaviest first, each with its weight. A deeper search reads more and takes longer. With
827
+ * `scope`, the user in that scope; with several, the user in each of them, related only to users of those
828
+ * scopes; `'*'`, or none, the user in every scope it has, related to users of any scope.
735
829
  */
736
- getRelated: (externalId: string, { type, depth }?: {
830
+ getRelated: (externalId: string, { scope, type, depth }?: {
831
+ scope?: Scopes;
737
832
  type?: RelatedType;
738
833
  depth?: number;
739
834
  }) => Promise<Related>;
740
835
  /**
741
- * One of your users' group: the ID every user tied to it through shared strong values answers (the event's
742
- * `groupId`), how many users it has (`size`) and its users, the asked one among them, 500 a page by default
743
- * (`limit` up to 500); pass the cursor back for the next page. Check a fact that must hold once per group, like
744
- * a reward, against these users in your own records. A group of more than 10,000 users is answered as the
745
- * 10,000 nearest the asked one.
836
+ * One of your users' group (in its `scope`, when it has one): the ID every user tied to it through shared
837
+ * strong values answers (the event's `groupId`), how many users it has (`size`) and its users, the asked one
838
+ * among them, 500 a page by default (`limit` up to 500); pass the cursor back for the next page. Check a fact
839
+ * that must hold once per group, like a reward, against these users in your own records. A group of more than
840
+ * 10,000 users is answered as the 10,000 nearest the asked one.
746
841
  */
747
- getRelatedGroup: (externalId: string, page?: {
842
+ getRelatedGroup: (externalId: string, { scope, ...page }?: {
843
+ scope?: string;
748
844
  limit?: number;
749
845
  cursor?: string;
750
846
  }) => Promise<RelatedGroup>;
@@ -777,12 +873,13 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
777
873
  matchWithinDays?: number | null;
778
874
  }) => Promise<RelatedWeight>;
779
875
  /**
780
- * A link to one user's Related view (their values, related users and recent events) for your admin panel at
781
- * `origin` to frame, working for `ttl` seconds (300 to 3600, 900 by default). Make one per page view and never
782
- * hand the API key to the browser.
876
+ * A link to one user's Related view (their values, related users and recent events; in its `scope`, when it has
877
+ * one) for your admin panel at `origin` to frame, working for `ttl` seconds (300 to 3600, 900 by default). Make
878
+ * one per page view and never hand the API key to the browser.
783
879
  */
784
880
  createEmbed: (embed: {
785
881
  externalId: string;
882
+ scope?: string;
786
883
  origin: string;
787
884
  ttl?: number;
788
885
  }) => Promise<Embed>;
@@ -800,33 +897,5 @@ type WebhookEvent = Omit<Event, 'broadVisitorId' | 'proximity' | 'rawDeviceAttri
800
897
  declare const verifyWebhook: (body: string, header: string | null | undefined, secret: string | undefined, { tolerance }?: {
801
898
  tolerance?: number | undefined;
802
899
  }) => Promise<WebhookEvent | undefined>;
803
- /** What `unsealResult` takes besides the sealed result. */
804
- type UnsealOptions = {
805
- /**
806
- * The project's encryption key, base64 (32 bytes), as the dashboard shows it: `process.env.ZENO_ENCRYPTION_KEY`; or
807
- * several, tried in order, while you rotate it: `[current, previous]`.
808
- */
809
- key: string | undefined | (string | undefined)[];
810
- /**
811
- * The IP address the request came from, as you pass it to `verify`: a sealed result from another ip blocks
812
- * (`ip-mismatch`, for IPv6 another /64); left out, or of the other family than the event's, there's no ip check.
813
- */
814
- ip?: string | null | undefined;
815
- /** Your own id for the user: an event with another user's blocks (`external-id-mismatch`); one with none is fine. */
816
- externalId?: string;
817
- /** Seconds a sealed result stays good for, 5 minutes (300) by default, as with `verify`; an older one blocks. */
818
- maxAge?: number;
819
- };
820
- /**
821
- * Opens a sealed result from the browser with the project's encryption key and says what to do, in `verify`'s shape: `{
822
- * action, reasons, event? }`. No sealed result (`undefined`, `null` or empty) is a `challenge` with `no-request-id`;
823
- * one that doesn't open with any `key` (changed, sealed with another project's key, or not one at all) is a `block`
824
- * with `not-found`. An opened one from another ip than `ip` blocks with `ip-mismatch`, compared as `verify` does, one
825
- * older than `maxAge` seconds with `too-old`, another user's than `externalId` with `external-id-mismatch`; otherwise
826
- * it answers the event's verdict. It can't tell a sealed result sent twice: where a repeat matters, use `verify`, which
827
- * allows each request ID once. Rejects with a TypeError for a missing or malformed key. The format: base64(version |
828
- * iv(12) | ciphertext | tag(16)), AES-256-GCM.
829
- */
830
- declare const unsealResult: (sealedResult: string | undefined | null, options: UnsealOptions) => Promise<VerifyResult>;
831
900
  //#endregion
832
- export { AddedRelation, type ApiOptions, Bot, BotType, Client, ClientOptions, Confidence, Connection, Contradiction, Embed, Event, EventBot, EventBrowser, EventIp, ForgedPayloadIndicator, GlobalFields, Group, Metadata, NetworkOwnerType, Outcome, Page, type ProxyHandler, type ProxyOptions, RawDeviceAttributes, Related, RelatedGroup, RelatedPair, RelatedType, RelatedUser, RelatedValue, RelatedValues, RelatedWeight, Relation, RelationInput, RelationRemoval, SIGNALS, SearchEvent, SearchFilters, SearchResult, SharedValue, Signal, SignalDetails, SignalReason, SignalResult, Signals, UnsealOptions, Velocity, Verdict, VerdictAction, VerdictReason, VerifyCheck, VerifyOptions, VerifyResult, VirtualMachineIndicator, WebhookEvent, ZenoError, ZenoErrorCode, createClient, createProxy, unsealResult, verifyWebhook };
901
+ export { AddedRelation, type ApiOptions, Bot, BotType, Client, ClientOptions, Confidence, Connection, Contradiction, Embed, Event, EventBot, EventBrowser, EventIp, ExternalIdRef, ForgedPayloadIndicator, GlobalFields, Group, Metadata, NetworkOwnerType, Outcome, Page, type ProxyRequest, RawDeviceAttributes, Related, RelatedGroup, RelatedPair, RelatedType, RelatedUser, RelatedValue, RelatedValues, RelatedWeight, Relation, RelationInput, RelationRemoval, SIGNALS, Scopes, SearchEvent, SearchFilters, SearchResult, SharedValue, Signal, SignalDetails, SignalReason, SignalResult, Signals, Velocity, Verdict, VerdictAction, VerdictReason, VerifyCheck, VerifyOptions, VerifyResult, VirtualMachineIndicator, WebhookEvent, ZenoError, ZenoErrorCode, createClient, createProxyResponse, nodeHandler, verifyWebhook };
@@ -1,2 +1 @@
1
- const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>{if(!e.includes(`:`))return e;let t=e.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);if(t)return t[1];let[n=``,r=``]=e.split(`::`),i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=Math.max(0,8-i.length-a.length),s=[...i,...Array.from({length:o},()=>`0`),...a].map(e=>e.toLowerCase().replace(/^0+(?=\w)/,``));if(s.slice(0,5).every(e=>e===`0`)&&s[5]===`ffff`){let[e=0,t=0]=s.slice(6).map(e=>parseInt(e,16));return[e>>8,e&255,t>>8,t&255].join(`.`)}return s.slice(0,4).join(`:`)},r=(e,t)=>{let r=t.trim();return e.includes(`:`)===r.includes(`:`)&&n(e)!==n(r)},i=(e,t)=>{let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`?i++:a===`"`&&(r=!1);else if(a===`"`)r=!0;else if(a===`{`||a===`[`){if(++n>t)return!0}else(a===`}`||a===`]`)&&n--}return!1},a=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),o=e=>{let t=e?.rawHeaders;return a(t)?t:void 0},s=`zeno_id`,c=1e4,l=(e,t,n={})=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`,...n}}),u=e=>l(400,{error:`invalid_request`,message:e}),d=(e,t=500)=>l(t,{error:`server_error`,message:e}),f=`Pass the IP address the request came from: zeno(request, ip)`,p=async(e,t)=>{if(Number(e.headers.get(`content-length`))>t)return;if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t){await n.cancel();return}r.push(a)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)},m=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===s)return t.slice(e+1).trim()}},h=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},g=/* @__PURE__ */ new Set([`user-agent`,`origin`,`signature-agent`,`signature-input`]),_=e=>e.map(([e,t])=>[e,g.has(e.toLowerCase())?t:``]),v=e=>{for(let[t,n]of e){let e=t.toLowerCase()===`cookie`?m(n):void 0;if(e!==void 0)return/^[A-Za-z0-9]{20}$/.test(e)?e:void 0}},y=e=>e?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i,`$1`)||void 0,b=(e,t,n,r=e.pathname)=>{let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||e.hostname.endsWith(`.localhost`),a=e.protocol===`http:`&&i?``:`; Secure`,o=r.replace(/[;,\s]/g,encodeURIComponent);return`${s}=${t}; Max-Age=${n}; Path=${o}; HttpOnly${a}; SameSite=Lax`},x=e=>(e.headers.get(`accept-encoding`)??``).split(`,`).some(e=>{let[t=``,...n]=e.split(`;`).map(e=>e.trim().toLowerCase()),r=n.find(e=>e.startsWith(`q=`));return(t===`gzip`||t===`*`)&&!(r&&Number(r.slice(2))===0)}),S=t=>e(t)?t.capped===!0||typeof t.requestId==`string`&&[`undefined`,`string`].includes(typeof t.visitorId)&&[`undefined`,`boolean`].includes(typeof t.returning)&&[`undefined`,`string`].includes(typeof t.sealedResult):!1,C=t=>{if(!e(t))return;let{value:n,maxAge:r}=t;return typeof n==`string`&&/^[A-Za-z0-9]{1,64}$/.test(n)&&typeof r==`number`&&Number.isInteger(r)&&r>=0?{value:n,maxAge:r}:void 0},w=e=>new Response(new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`))).arrayBuffer(),T=async(e,t,n)=>{let r={"content-type":`text/javascript; charset=utf-8`,"cache-control":n,vary:`accept-encoding`},i=typeof t==`string`?t:t.code;if(!x(e)||typeof CompressionStream!=`function`)return new Response(i,{headers:r});let a=typeof t==`string`?w(i):t.gzipped??=w(i);return new Response(await a,{headers:{...r,"content-encoding":`gzip`}})},E=(e,t)=>[`const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({v:e})}`)}, import.meta.url))`,`export const challengeToken = ${t}`,`const own = new URL(import.meta.url)`,`const refreshChallengeToken = () => import(new URL("?challenge=" + Date.now(), own)).then(module => module.challengeToken, () => undefined)`,`export const start = (path = own.pathname, options) => code.start(path, { challengeToken, refreshChallengeToken, ...options })`,``].join(`
2
- `),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{errorResponse:k()};if(r.status!==304&&!r.ok)return{errorResponse:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{errorResponse:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{errorResponse:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.errorResponse)return n.errorResponse;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.errorResponse)return e.errorResponse;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return e.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`?u(`Cross-site requests are refused`):new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let f=y(r);if(e.method===`POST`)return P(e,f,i);let p=await N(e,f);return e.method===`HEAD`?(await p.body?.cancel(),new Response(null,{status:p.status,headers:p.headers})):p}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`];var k=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const A=(e,t)=>{if(!e)throw TypeError(t);return e},j=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},M=e=>new Promise(t=>setTimeout(t,e*1e3)),N=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new k(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},P=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,F=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>P(t[e],n))}),I=F(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),L=F(`a page of events`,{items:`array`}),ee=F(`a reported outcome`,{requestId:`string`,outcome:`string`}),te=F(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),ne=F(`an erasure`,{externalId:`string`,deletedEvents:`number`}),R=F(`a relation`,{externalId:`string`,type:`string`,created:`boolean`}),z=F(`a removal`,{removed:`boolean`}),B=F(`a user's values`,{externalId:`string`,values:`array`}),V=F(`a page of users`,{items:`array`}),H=F(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`,sharedValues:`array`,pairs:`array`,truncated:`boolean`,widelyShared:`array`,stoppedAt:`array`}),U=F(`the weights`,{items:`array`}),W=F(`a weight`,{type:`string`,weight:`number`,defaultWeight:`number`}),G=F(`a user's group`,{externalId:`string`,size:`number`,externalIds:`array`}),K=F(`a group`,{groupId:`string`,size:`number`,externalIds:`array`}),q=F(`an embed`,{url:`string`,expiresAt:`string`}),J=F(`verify's answer`,{action:`string`,reasons:`array`}),Y=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async({apiKey:e,base:t},n,r,i,o)=>{try{let s=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...o?{"content-type":`application/json`}:{}},body:o,signal:AbortSignal.timeout(i)});return{response:s,text:await s.text()}}catch(e){throw new k(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${i} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c),f=l?Date.now()+1e4:void 0,p=()=>f===void 0?1e4:Math.round(Math.min(5e3,f-Date.now())),m=e=>f===void 0||f-Date.now()-e*1e3>=1e3;for(let t=0;;t++){let n;try{n=await o(u,r,a,p(),d)}catch(e){let n=.5+Math.random()*.25;if(l&&t<2&&m(n)){await M(n);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new k(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new k(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:h,message:g}=e(f)?f:{},_=typeof h==`string`?h:void 0,v=i.status===429||_===`search_unavailable`||l&&i.status>=500,y=v?j(i.headers.get(`retry-after`)):void 0,b=(y??1)*(1+Math.random()*.5);if(v&&t<2&&m(b))await M(b);else throw new k(i.status,_??`request_failed`,typeof g==`string`?g:void 0,y)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,J,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${N(`requestId`,e)}`,I),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,L)},reportOutcome:(e,t)=>s(`POST`,`/outcomes`,ee,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${N(`visitorId`,e)}`,te),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,ne)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,R,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,z)},getRelatedValues:(e,{type:t,...n}={})=>{let r=c(new URLSearchParams({externalId:e,...t?{type:t}:{}}),n);return s(`GET`,`/related/values?${r}`,B)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,V)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,H)},getRelatedGroup:(e,t={})=>{let n=c(new URLSearchParams({externalId:e}),t);return s(`GET`,`/related/group?${n}`,G)},getGroup:async(e,t={})=>{let n=c(new URLSearchParams,t).toString(),r=`/related/group/${N(`groupId`,e)}`;return s(`GET`,n?`${r}?${n}`:r,K)},getRelatedWeights:()=>s(`GET`,`/related/weights`,U),setRelatedType:(e,t)=>s(`POST`,`/related/weights`,W,{type:e,...t}),createEmbed:e=>s(`POST`,`/embeds`,q,e)}},X=new TextEncoder,Z=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},re=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ie=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},ae=async(e,t,n,{tolerance:r=300}={})=>{let i=A(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`);if(typeof e!=`string`)throw TypeError(`verifyWebhook needs the raw body as text, not a parsed one (in Express, express.text({ type: "application/json" }))`);let a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,X.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=X.encode(re(await crypto.subtle.sign(`HMAC`,c,X.encode(`${o}.${e}`))));if(!s.map(e=>ie(X.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!I.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,oe=e=>{let t=A(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?Z(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},se=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},ce=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(oe);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=Z(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await se(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!I.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};export{O as SIGNALS,k as ZenoError,Y as createClient,D as createProxy,ce as unsealResult,ae as verifyWebhook};
1
+ const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),r=e=>{let t=e.rawHeaders;return n(t)?t:void 0},i=1e4,a=[`user-agent`,`origin`,`signature-agent`,`signature-input`,`sec-fetch-site`],o=(e,t)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),s=(e,t=500)=>o(t,{error:`server_error`,message:e}),c=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===`zeno_id`)return t.slice(e+1).trim()}},l=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},u=e=>{let t={"zeno-visitor-header-names":e.map(([e])=>e.toLowerCase()).join(`, `)};for(let[n,r]of e){let e=n.toLowerCase(),i=e===`cookie`?c(r):void 0;i&&!t[`zeno-visitor-token`]&&(t[`zeno-visitor-token`]=i),a.includes(e)&&!t[`zeno-visitor-${e}`]&&(t[`zeno-visitor-${e}`]=r)}return t},d=async e=>{if(e.status===401||e.status===402){let t=await e.clone().text().catch(()=>``);console.error(`Zeno answered the proxy route ${e.status}: ${t}`)}let t=new Headers;return e.headers.forEach((e,n)=>{n.startsWith(`zeno-browser-`)&&n.length>13&&t.append(n.slice(13),e)}),new Response(e.body?await e.arrayBuffer():null,{status:e.status,headers:t})},f=async e=>{let{request:n,ip:a,apiKey:o,apiUrl:c,fetch:f=globalThis.fetch,...p}=e,m=t(`createProxyResponse`,o,c);if(m.problem!==void 0)return console.error(m.problem),s(`The proxy route isn't set up; its server log says what's missing`);let h=`${m.base}/proxy${new URL(n.url).search}`,g=n.method!==`GET`&&n.method!==`HEAD`;try{let e=await f(h,{method:n.method,headers:{"auth-api-key":m.apiKey,...a?{"zeno-visitor-ip":a}:{},...g?{"content-type":`application/json`}:{},...u(l(n,r(p)))},...g?{body:await n.arrayBuffer()}:{},signal:AbortSignal.timeout(i)});return await d(e)}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no answer within ${i} ms`:String(e);return console.error(`The proxy route couldn't reach Zeno at ${h}: ${t}`),s(`Zeno could not be reached`,502)}},p=1048576,m=async e=>{let t=[],n=0;for await(let r of e){let e=typeof r==`string`?new TextEncoder().encode(r):r;n+=e.byteLength,n<=p&&t.push(e)}if(n>p)return null;let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.byteLength;return r},h=(e,t)=>{let n=new Headers;for(let t=0;t+1<e.rawHeaders.length;t+=2){let r=e.rawHeaders[t];r.startsWith(`:`)||n.append(r,e.rawHeaders[t+1])}let r=e.socket.encrypted?`https`:`http`,i=e.originalUrl??e.url??`/`,a=new URL(i,`${r}://${e.headers.host??`localhost`}`);return new Request(a,{method:e.method,headers:n,...t?{body:t}:{}})},g=async(e,t)=>{t.statusCode=e.status,e.headers.forEach((e,n)=>{n!==`set-cookie`&&t.setHeader(n,e)});let n=e.headers.getSetCookie();n.length>0&&t.setHeader(`set-cookie`,n),t.end(e.body?new Uint8Array(await e.arrayBuffer()):void 0)},_=e=>async(t,n)=>{let r=`raw`in t?t.raw:t,i=t.ip,a=typeof i==`string`?i:r.socket.remoteAddress,o;`hijack`in n?(n.hijack(),o=n.raw):o=n;let s=(e,t,n)=>g(new Response(JSON.stringify({error:t,message:n}),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),o);try{let t=r.method!==`GET`&&r.method!==`HEAD`;if(t&&r.readableEnded){console.error(`The proxy route found its body already read: mount nodeHandler before any body parser`),await s(500,`server_error`,`The proxy route isn't set up; its server log says what's wrong`);return}let n=t?await m(r):void 0;if(n===null){await s(413,`invalid_request`,`The body is larger than 1 MB`);return}let i={...e,request:h(r,n),ip:a,rawHeaders:r.rawHeaders};await g(await f(i),o)}catch(e){console.error(`The proxy route failed: ${e instanceof Error?e.message:String(e)}`),o.headersSent||await s(500,`server_error`,`The proxy route failed; its server log says why`)}},v=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`];var y=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const b=(e,t)=>{if(!e)throw TypeError(t);return e},x=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},S=e=>new Promise(t=>setTimeout(t,e*1e3)),C=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new y(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},w=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,T=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>w(t[e],n))}),E=T(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),D=T(`a page of events`,{items:`array`}),O=T(`a reported outcome`,{requestId:`string`,outcome:`string`}),k=T(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),A=T(`an erasure`,{externalId:`string`,deletedEvents:`number`}),j=T(`a relation`,{externalId:`string`,type:`string`,created:`boolean`}),M=T(`a removal`,{removed:`boolean`}),N=T(`a user's values`,{externalId:`string`,values:`array`}),P=T(`a page of users`,{items:`array`}),F=T(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`,sharedValues:`array`,pairs:`array`,truncated:`boolean`,widelyShared:`array`,stoppedAt:`array`}),I=T(`the weights`,{items:`array`}),L=T(`a weight`,{type:`string`,weight:`number`,defaultWeight:`number`}),R=T(`a user's group`,{externalId:`string`,size:`number`,externalIds:`array`}),z=T(`a group`,{groupId:`string`,size:`number`,externalIds:`array`}),B=T(`an embed`,{url:`string`,expiresAt:`string`}),V=T(`verify's answer`,{action:`string`,reasons:`array`}),H=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async({apiKey:e,base:t},n,r,i,o)=>{try{let s=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...o?{"content-type":`application/json`}:{}},body:o,signal:AbortSignal.timeout(i)});return{response:s,text:await s.text()}}catch(e){throw new y(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${i} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c),f=l?Date.now()+1e4:void 0,p=()=>f===void 0?1e4:Math.round(Math.min(5e3,f-Date.now())),m=e=>f===void 0||f-Date.now()-e*1e3>=1e3;for(let t=0;;t++){let n;try{n=await o(u,r,a,p(),d)}catch(e){let n=.5+Math.random()*.25;if(l&&t<2&&m(n)){await S(n);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new y(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new y(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:h,message:g}=e(f)?f:{},_=typeof h==`string`?h:void 0,v=i.status===429||_===`search_unavailable`||l&&i.status>=500,b=v?x(i.headers.get(`retry-after`)):void 0,C=(b??1)*(1+Math.random()*.5);if(v&&t<2&&m(C))await S(C);else throw new y(i.status,_??`request_failed`,typeof g==`string`?g:void 0,b)}},c=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return t};return{verify:async(e,t={})=>{let{ip:n,externalId:r,scope:i,maxAge:a,idempotencyKey:o=crypto.randomUUID()}=t;return s(`POST`,`/verify`,V,{requestId:e??void 0,ip:n||void 0,externalId:r,scope:i,maxAge:a,idempotencyKey:o},!0)},getEvent:async e=>s(`GET`,`/events/${C(`requestId`,e)}`,E),searchEvents:(e={})=>s(`GET`,`/events?${c(e)}`,D),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,O,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${C(`visitorId`,e)}`,k),deleteExternalId:(e,{scope:t}={})=>s(`DELETE`,`/external-ids?${c({externalId:e,scope:t})}`,A),addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,j,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>s(`DELETE`,`/related?${c(e)}`,M),getRelatedValues:(e,{scope:t,type:n,...r}={})=>{let i=c({externalId:e,scope:t,type:n,...r});return s(`GET`,`/related/values?${i}`,N)},lookupRelated:(e,t,{scope:n,...r}={})=>{let i=c({type:e,value:t,scope:n,...r});return s(`GET`,`/related/lookup?${i}`,P)},getRelated:(e,{scope:t,type:n,depth:r=1}={})=>{let i=c({externalId:e,scope:t,type:n,depth:r});return s(`GET`,`/related?${i}`,F)},getRelatedGroup:(e,{scope:t,...n}={})=>{let r=c({externalId:e,scope:t,...n});return s(`GET`,`/related/group?${r}`,R)},getGroup:async(e,t={})=>{let n=c(t).toString(),r=`/related/group/${C(`groupId`,e)}`;return s(`GET`,n?`${r}?${n}`:r,z)},getRelatedWeights:()=>s(`GET`,`/related/weights`,I),setRelatedType:(e,t)=>s(`POST`,`/related/weights`,L,{type:e,...t}),createEmbed:e=>s(`POST`,`/embeds`,B,e)}},U=new TextEncoder,W=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),G=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},K=async(e,t,n,{tolerance:r=300}={})=>{let i=b(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`);if(typeof e!=`string`)throw TypeError(`verifyWebhook needs the raw body as text, not a parsed one (in Express, express.text({ type: "application/json" }))`);let a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,U.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=U.encode(W(await crypto.subtle.sign(`HMAC`,c,U.encode(`${o}.${e}`))));if(!s.map(e=>G(U.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!E.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u};export{v as SIGNALS,y as ZenoError,H as createClient,f as createProxyResponse,_ as nodeHandler,K as verifyWebhook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zeno.id",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Zeno's SDK for device identification: the browser SDK, and the proxy route and API client for your server",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -15,9 +15,6 @@
15
15
  "*": {
16
16
  "server": [
17
17
  "./dist/server/index.d.ts"
18
- ],
19
- "server/node": [
20
- "./dist/server/node.d.ts"
21
18
  ]
22
19
  }
23
20
  },
@@ -42,16 +39,6 @@
42
39
  "default": "./dist/server/index.cjs"
43
40
  }
44
41
  },
45
- "./server/node": {
46
- "import": {
47
- "types": "./dist/server/node.d.ts",
48
- "default": "./dist/server/node.js"
49
- },
50
- "require": {
51
- "types": "./dist/server/node.d.cts",
52
- "default": "./dist/server/node.cjs"
53
- }
54
- },
55
42
  "./package.json": "./package.json"
56
43
  },
57
44
  "publishConfig": {
@@ -1 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=131073,t=async(t,n)=>{if(t.method!==`POST`)return;if(t.readableEnded)return typeof n==`string`?n:n instanceof Uint8Array?new TextDecoder().decode(n):n===void 0?``:JSON.stringify(n);let r=[],i=0;for await(let n of t){let t=typeof n==`string`?new TextEncoder().encode(n):n;i<e&&r.push(t),i+=t.byteLength}let a=new Uint8Array(Math.min(i,e)),o=0;for(let e of r){let t=e.subarray(0,a.length-o);a.set(t,o),o+=t.byteLength}return new TextDecoder().decode(a)},n=async(e,n)=>{let r=new Headers;for(let t=0;t+1<e.rawHeaders.length;t+=2){let n=e.rawHeaders[t];n.startsWith(`:`)||r.append(n,e.rawHeaders[t+1])}let i=e.socket.encrypted?`https`:`http`,a=e.originalUrl??e.url??`/`,o=e.headers.host??e.headers[`:authority`]??`localhost`,s=await t(e,n);return new Request(new URL(a,`${i}://${String(o)}`),{method:e.method,headers:r,...s===void 0?{}:{body:s}})},r=async(e,t)=>{t.statusCode=e.status,e.headers.forEach((e,n)=>{n!==`set-cookie`&&t.setHeader(n,e)});let n=e.headers.getSetCookie();n.length>0&&t.setHeader(`set-cookie`,n),t.end(e.body?new Uint8Array(await e.arrayBuffer()):void 0)},i=e=>{let t=e;return async(e,i)=>{let a=`raw`in e?e.raw:e,o=e.ip,s=typeof o==`string`?o:a.socket.remoteAddress,c=(`raw`in e,e.body),l;`hijack`in i?(i.hijack(),l=i.raw):l=i;try{let e=await n(a,c),i=await t(e,s,{rawHeaders:a.rawHeaders});await r(i,l)}catch(e){console.error(`The proxy route failed: ${e instanceof Error?e.message:String(e)}`),l.headersSent||(l.statusCode=500,l.setHeader(`content-type`,`application/json; charset=utf-8`),l.end(JSON.stringify({error:`server_error`,message:`The proxy route failed; its server log says why`})))}}};exports.nodeHandler=i;
@@ -1,21 +0,0 @@
1
- import { t as ProxyHandler } from "./proxy-CUZ-Jwgy.cjs";
2
- import { IncomingMessage, ServerResponse } from "http";
3
- //#region src/server/node.d.ts
4
- type FastifyRequest = {
5
- raw: IncomingMessage;
6
- body?: unknown;
7
- ip?: unknown;
8
- };
9
- type FastifyReply = {
10
- raw: ServerResponse;
11
- hijack: () => unknown;
12
- };
13
- /**
14
- * Mounts the proxy route on Node's `(req, res)`: Express, Fastify or `http.createServer`. `app.all('/zeno',
15
- * nodeHandler(zeno))`, with `zeno` from `createProxy`. It passes the IP address the request came from: Express's and
16
- * Fastify's `req.ip` (behind a proxy of your own, set their trust proxy so it's the visitor's), else the socket's
17
- * address. A body parser in front (`express.json()`) is fine.
18
- */
19
- declare const nodeHandler: (handler: ProxyHandler) => (request: IncomingMessage | FastifyRequest, response: ServerResponse | FastifyReply) => Promise<void>;
20
- //#endregion
21
- export { nodeHandler };
@@ -1,21 +0,0 @@
1
- import { t as ProxyHandler } from "./proxy-CUZ-Jwgy.js";
2
- import { IncomingMessage, ServerResponse } from "http";
3
- //#region src/server/node.d.ts
4
- type FastifyRequest = {
5
- raw: IncomingMessage;
6
- body?: unknown;
7
- ip?: unknown;
8
- };
9
- type FastifyReply = {
10
- raw: ServerResponse;
11
- hijack: () => unknown;
12
- };
13
- /**
14
- * Mounts the proxy route on Node's `(req, res)`: Express, Fastify or `http.createServer`. `app.all('/zeno',
15
- * nodeHandler(zeno))`, with `zeno` from `createProxy`. It passes the IP address the request came from: Express's and
16
- * Fastify's `req.ip` (behind a proxy of your own, set their trust proxy so it's the visitor's), else the socket's
17
- * address. A body parser in front (`express.json()`) is fine.
18
- */
19
- declare const nodeHandler: (handler: ProxyHandler) => (request: IncomingMessage | FastifyRequest, response: ServerResponse | FastifyReply) => Promise<void>;
20
- //#endregion
21
- export { nodeHandler };
@@ -1 +0,0 @@
1
- const e=131073,t=async(t,n)=>{if(t.method!==`POST`)return;if(t.readableEnded)return typeof n==`string`?n:n instanceof Uint8Array?new TextDecoder().decode(n):n===void 0?``:JSON.stringify(n);let r=[],i=0;for await(let n of t){let t=typeof n==`string`?new TextEncoder().encode(n):n;i<e&&r.push(t),i+=t.byteLength}let a=new Uint8Array(Math.min(i,e)),o=0;for(let e of r){let t=e.subarray(0,a.length-o);a.set(t,o),o+=t.byteLength}return new TextDecoder().decode(a)},n=async(e,n)=>{let r=new Headers;for(let t=0;t+1<e.rawHeaders.length;t+=2){let n=e.rawHeaders[t];n.startsWith(`:`)||r.append(n,e.rawHeaders[t+1])}let i=e.socket.encrypted?`https`:`http`,a=e.originalUrl??e.url??`/`,o=e.headers.host??e.headers[`:authority`]??`localhost`,s=await t(e,n);return new Request(new URL(a,`${i}://${String(o)}`),{method:e.method,headers:r,...s===void 0?{}:{body:s}})},r=async(e,t)=>{t.statusCode=e.status,e.headers.forEach((e,n)=>{n!==`set-cookie`&&t.setHeader(n,e)});let n=e.headers.getSetCookie();n.length>0&&t.setHeader(`set-cookie`,n),t.end(e.body?new Uint8Array(await e.arrayBuffer()):void 0)},i=e=>{let t=e;return async(e,i)=>{let a=`raw`in e?e.raw:e,o=e.ip,s=typeof o==`string`?o:a.socket.remoteAddress,c=(`raw`in e,e.body),l;`hijack`in i?(i.hijack(),l=i.raw):l=i;try{let e=await n(a,c),i=await t(e,s,{rawHeaders:a.rawHeaders});await r(i,l)}catch(e){console.error(`The proxy route failed: ${e instanceof Error?e.message:String(e)}`),l.headersSent||(l.statusCode=500,l.setHeader(`content-type`,`application/json; charset=utf-8`),l.end(JSON.stringify({error:`server_error`,message:`The proxy route failed; its server log says why`})))}}};export{i as nodeHandler};
@@ -1,36 +0,0 @@
1
- //#region src/server/util.d.ts
2
- /** The project's API key, `sk_...`, from your server's environment: `process.env.ZENO_API_KEY`. */
3
- type ApiKey = string | undefined;
4
- /** Options both createClient and createProxy take. */
5
- type ApiOptions = {
6
- /** The Zeno API's http(s) origin, for staging or a local Zeno. Zeno's own API by default. */
7
- apiUrl?: string | undefined;
8
- };
9
- //#endregion
10
- //#region src/server/proxy.d.ts
11
- type ProxyOptions = ApiOptions & {
12
- /**
13
- * The visitor id cookie's path: the path the browser calls the route on, by default the request's own. Set it when
14
- * something in front of the handler rewrites the path (the site's `/zeno` handled at `/api/proxy`), else the
15
- * browser keeps the cookie for a path it never calls and every visit is a new one.
16
- */
17
- cookiePath?: string | undefined;
18
- };
19
- /**
20
- * The route's handler, `zeno(request, ip)`: a web `Request` in, a `Response` out. `ip` is the IP address the request
21
- * came from, your framework's client IP; behind a proxy of your own, turn on your framework's trust-proxy setting so
22
- * it's the visitor's. An identification without it answers `500`. Answer `GET` and `POST` on one path with it.
23
- */
24
- type ProxyHandler = (request: Request, ip: string | null | undefined) => Promise<Response>;
25
- /**
26
- * The proxy route: a route on your own site between the browser SDK and the Zeno API. It serves the script's code,
27
- * forwards its identifications with your API key and the visitor's ip, and keeps the visitor id in a first-party
28
- * HttpOnly cookie. Answer `GET` and `POST` on one path of your choice (the one the browser's `start()` takes, `/zeno`
29
- * by default) with what it returns, `zeno(request, ip)` with the IP address the request came from (`nodeHandler(zeno)`
30
- * from `zeno.id/server/node` on Node's `(req, res)`). The `apiKey` (from your server's environment, undefined accepted)
31
- * is checked on each request, so a module that makes it at load builds without the environment (as Next.js does when it
32
- * collects page data); a request without it answers `500` and logs it.
33
- */
34
- declare const createProxy: (apiKey: ApiKey, options?: ProxyOptions) => ProxyHandler;
35
- //#endregion
36
- export { ApiOptions as a, ApiKey as i, ProxyOptions as n, createProxy as r, ProxyHandler as t };