zeno.id 0.6.0 → 0.7.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.
@@ -114,8 +114,8 @@ type RawDeviceAttributes = {
114
114
  math?: string;
115
115
  keyboard?: string;
116
116
  };
117
- /** What an event turned out to be, as your backend reports it. */
118
- type Outcome = 'fraud' | 'legitimate';
117
+ /** What an event turned out to be, as your backend reports it: legitimate, or the type of fraud it was. */
118
+ type Outcome = 'legitimate' | 'payment-fraud' | 'account-takeover' | 'fake-account' | 'promotion-abuse' | 'multi-accounting' | 'platform-abuse' | 'content-abuse' | 'other-fraud';
119
119
  /** What kind of bot an event was. */
120
120
  type BotType = 'automation' | 'replayed' | 'forged-request' | 'fake-crawler' | 'crawler' | 'ai-agent';
121
121
  /** The bot verdict, and what's known of the bot. */
@@ -177,12 +177,12 @@ type EventIp = {
177
177
  /** A managed service's exit, like `private-relay` for iCloud Private Relay. */
178
178
  exitServiceType?: 'private-relay' | 'secure-web-gateway' | 'satellite' | 'dns-resolver' | 'email-gateway';
179
179
  exitServiceProvider?: string;
180
- mobileNetwork: boolean;
181
- satelliteNetwork: boolean;
180
+ mobileNetwork?: boolean;
181
+ satelliteNetwork?: boolean;
182
182
  /** A crawler the lookup knows, like Googlebot's addresses. */
183
- knownCrawler: boolean;
183
+ knownCrawler?: boolean;
184
184
  /** A private or reserved address that no one on the internet has. */
185
- reservedAddress: boolean;
185
+ reservedAddress?: boolean;
186
186
  };
187
187
  /** The browser, parsed on the server from the user agent and client hints. */
188
188
  type EventBrowser = {
@@ -336,6 +336,13 @@ type Event = {
336
336
  residentialIp: string[];
337
337
  broadVisitorId: string[];
338
338
  };
339
+ /**
340
+ * The group of the event's user: one ID that every user tied to it through a shared strong value answers too (a
341
+ * visitor ID with the default weights), directly or through other users. Without an external ID, the group its
342
+ * 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.
344
+ */
345
+ groupId?: string | null;
339
346
  } & GlobalFields;
340
347
  /** A list filter takes one value, or several to match any of. */
341
348
  type AnyOf<T> = T | T[];
@@ -393,96 +400,153 @@ type Page<T> = {
393
400
  type SearchResult = Page<SearchEvent> & {
394
401
  found?: number;
395
402
  };
396
- /**
397
- * A visitor: `externalIds` the latest 10 external ids seen with it, newest first, and `externalIdCount` how many there
398
- * are in all; `signals` holds every signal any of its events detected, as `{ detected: true }`, and `recentEvents` its
399
- * 20 latest events, newest first, each with its detected signals the same way and `ip.country` when known.
400
- */
401
- type Visitor = {
402
- visitorId: string;
403
- externalIds: string[];
404
- externalIdCount: number;
405
- signals: { [S in Signal]?: {
406
- detected: true;
407
- }; };
408
- eventCount: number;
409
- firstSeenAt: string;
410
- lastSeenAt: string;
411
- recentEvents: (Pick<SearchEvent, 'requestId' | 'externalId' | 'createdAt' | 'signals'> & {
412
- ip: Pick<EventIp, 'address' | 'country'>;
413
- })[];
414
- };
415
403
  /**
416
404
  * What relates two users: the built-in `visitor-id` (a browser), `broad-visitor-id` (its hardware), `residential-ip`
417
405
  * (an ip of an internet provider, not a VPN, proxy or mobile network), all three from events only, and `ip`, or a type
418
- * of your own like `phone` or `referral` (a lowercase letter, then up to 31 lowercase letters, digits, `_` or `-`).
406
+ * of your own like `payment-card` (a lowercase letter, then up to 31 lowercase letters, digits, `_` or `-`).
419
407
  */
420
408
  type RelatedType = 'visitor-id' | 'broad-visitor-id' | 'ip' | 'residential-ip' | (string & {});
421
- /**
422
- * `identifier`, a value several users can share (a visitor id, a phone number); `relation`, a direct tie between two
423
- * users (a referral, an invite). A type of your own keeps the kind its first relation gave it.
424
- */
425
- type RelatedKind = 'identifier' | 'relation';
426
409
  type ValueDetails = {
427
410
  type: RelatedType;
428
411
  /** The type's weight, 0 to 1: how much sharing it says two users are one person. */
429
412
  weight: number;
430
- /** Your own word for what happened, like `checkout` or `signup`, when it was added by hand with one. */
413
+ /** Your own word for what happened, like `checkout` or `signup`, when it was added as a relation with one. */
431
414
  action?: string;
432
- /** When it happened: the `at` of one added by hand (its latest call's), or when the first event brought it. */
415
+ /** When it happened: the `at` of a relation (its latest call's), or when the first event brought it. */
433
416
  at: string;
434
417
  createdAt: string;
435
418
  };
436
- /** One of a user's values: a value they have, or the other user of a relation. */
437
- type RelatedValue = (ValueDetails & {
438
- kind: 'identifier';
419
+ /** One of the project's types with its weight and its Match within: a built-in, or one of your own. */
420
+ type RelatedWeight = {
421
+ type: RelatedType;
422
+ /** The weight in force, 0 to 1: the one you set, else the default. */
423
+ weight: number;
424
+ /** The weight the type has until you set one. */
425
+ defaultWeight: number;
426
+ /**
427
+ * Match within: how many days apart two users may have been seen with a value of the type and still share it. The
428
+ * days you set, else the default. `null` is any time apart.
429
+ */
430
+ matchWithinDays: number | null;
431
+ /** The days the type has until you set them: `null` for a type of your own. */
432
+ defaultMatchWithinDays: number | null;
433
+ /** One of Zeno's own types (`visitor-id`, `ip`, ...), not one of yours. */
434
+ builtIn: boolean;
435
+ };
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;
439
+ /** The same for every user in the group. `null` for a user Zeno has no values of. */
440
+ groupId: string | null;
441
+ /**
442
+ * How many users the group has, the asked one included, up to 10,000: a larger group is answered as the 10,000
443
+ * users nearest the asked one. 0 without a group ID.
444
+ */
445
+ size: number;
446
+ /** A page of the group's users, the asked one among them: no weights, no depth. Empty without a group ID. */
447
+ externalIds: string[];
448
+ /** Pass it back for the next page; none on the last page. */
449
+ cursor?: string;
450
+ };
451
+ /** A group by its ID: every user tied through shared strong values, directly or through other users. */
452
+ type Group = {
453
+ /** The ID you asked for. */
454
+ groupId: string;
455
+ /** How many users the group has, up to 10,000: a larger group is answered as 10,000 of its users. */
456
+ size: number;
457
+ /** A page of the group's users: no weights, no depth. */
458
+ externalIds: string[];
459
+ /** Pass it back for the next page; none on the last page. */
460
+ cursor?: string;
461
+ };
462
+ /** One of a user's values, like a visitor ID, an ip or a card's fingerprint. */
463
+ type RelatedValue = ValueDetails & {
439
464
  value: string;
440
- }) | (ValueDetails & {
441
- kind: 'relation';
442
- relatedExternalId: string;
443
- });
465
+ };
444
466
  type RelatedValues = {
445
467
  externalId: string;
446
468
  /**
447
- * Shares one value weighing 0.5 or more with another user: a visitor id does, a shared ip never. Lesser ties never
448
- * add up to one, and a relation (a referral) never makes one.
469
+ * 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
+ * 10,000 users, which has no ID.
471
+ */
472
+ groupId: string | null;
473
+ /**
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.
449
476
  */
450
477
  duplicate: boolean;
451
478
  /** Was ever identified in a browser; treat a user who wasn't as unverified. */
452
479
  identified: boolean;
480
+ /** A page of the user's values, by type name and value. */
453
481
  values: RelatedValue[];
454
- /** More values than the 500 answered. */
455
- truncated: boolean;
482
+ /** Pass it back for the next page; none on the last page. */
483
+ cursor?: string;
456
484
  };
457
- /**
458
- * Another user (`externalId`) who has a value the asked one has, or the other user of a relation (`relatedExternalId`),
459
- * which needs no value.
460
- */
461
- type Connection = (ValueDetails & {
462
- kind: 'identifier';
485
+ /** Another user (`externalId`) who shares a `value` with the asked one. */
486
+ type Connection = ValueDetails & {
463
487
  externalId: string;
464
488
  value: string;
465
- }) | (ValueDetails & {
466
- kind: 'relation';
467
- relatedExternalId: string;
468
- });
489
+ };
490
+ /** A value two or more of the users found share, with each of the users who share it and when they got it. */
491
+ type SharedValue = {
492
+ type: RelatedType;
493
+ /** The type's weight, 0 to 1. */
494
+ weight: number;
495
+ value: string;
496
+ externalIds: {
497
+ externalId: string;
498
+ at: string;
499
+ createdAt: string;
500
+ }[];
501
+ };
502
+ /**
503
+ * Two of the related users who share values: `a` and `b` are their indexes in `externalIds` (`a` the lower), and
504
+ * `values` the indexes in `sharedValues` of what the two share, ascending.
505
+ */
506
+ type RelatedPair = [a: number, b: number, values: number[]];
469
507
  type Related = {
470
508
  externalId: string;
471
509
  /** The type asked for; none when every type was walked. */
472
510
  type?: RelatedType;
473
511
  /**
474
512
  * Every other user reached, heaviest first, each with its `weight` to the asked one: what the two share combined
475
- * (`1 - Π(1 - weight)`, so with the default weights two shared ips make 0.44 and a browser and an ip 0.93),
476
- * multiplied along the strongest path for a user further away. With the users each shares a value with or is
477
- * related to.
513
+ * (`1 - Π(1 - weight)`, so with the default weights two shared ips make 0.44 and a visitor id and an ip 0.96),
514
+ * multiplied along the strongest path for a user further away.
478
515
  */
479
516
  externalIds: {
480
517
  externalId: string;
481
518
  weight: number;
482
- connections: Connection[];
483
519
  }[];
484
- /** The users the asked one shares a value with or is related to. */
520
+ /** What the asked user shares with others: one entry per other user and shared value. */
485
521
  connections: Connection[];
522
+ /**
523
+ * Every value two or more of the users found share (the asked one included), each once with the users who share it.
524
+ * A value listing three users doesn't say every two of them share it: two users share a value only when both were
525
+ * seen with it within the type's Match within. `connections` and `pairs` say who shares it with whom.
526
+ */
527
+ sharedValues: SharedValue[];
528
+ /**
529
+ * Which two of the users in `externalIds` share which of the `sharedValues`. The asked user is in no pair: what it
530
+ * shares is in `connections`. With `connections` this is the whole graph to draw.
531
+ */
532
+ pairs: RelatedPair[];
533
+ /** The search may have left something unread: see `widelyShared` and `stoppedAt`. */
534
+ truncated: boolean;
535
+ /**
536
+ * The values more users share than the search read (it reads 50 users of a value), each with how many users have it
537
+ * (`users`). Page through all of a value's users with `lookupRelated`.
538
+ */
539
+ widelyShared: {
540
+ type: RelatedType;
541
+ value: string;
542
+ users?: number;
543
+ }[];
544
+ /**
545
+ * The users the search stopped at: found, but not all of their values were read or followed. Call `getRelated` with
546
+ * one to continue the search from that user. The asked user is in the list when it has more values than one search
547
+ * follows: pass a `type`, or page its values with `getRelatedValues`.
548
+ */
549
+ stoppedAt: string[];
486
550
  };
487
551
  /** One of your users who has a value, and since when. */
488
552
  type RelatedUser = {
@@ -490,43 +554,27 @@ type RelatedUser = {
490
554
  createdAt: string;
491
555
  };
492
556
  /**
493
- * A relation added by hand: an ip seen by another system (`type: 'ip'`), a value of a type of your own (`{ type:
494
- * 'phone', value }`), or a tie between two of your users (`{ type: 'referral', relatedExternalId }`). Its weight isn't
495
- * part of it: the project's settings hold each type's weight, applied when relations are read.
557
+ * A relation: an ip seen by another system (`type: 'ip'`) or a value of a type of your own (`{ type: 'payment-card',
558
+ * value }`). Its weight isn't part of it: the project holds each type's weight, applied when related users are read.
496
559
  */
497
560
  type RelationTarget = {
498
561
  externalId: string;
499
562
  type: RelatedType;
500
563
  value: string;
501
- } | {
502
- externalId: string;
503
- type: RelatedType;
504
- relatedExternalId: string;
505
564
  };
506
565
  type RelationInput = RelationTarget & {
507
566
  /** When it happened (a Date, an ISO string or epoch milliseconds), now by default; never in the future. */
508
567
  at?: Date | string | number;
509
568
  };
510
- /**
511
- * A relation to take back: the value or the other user you added it with (`{ type: 'phone', value }` or `{ type:
512
- * 'referral', relatedExternalId }`).
513
- */
514
- type RelationRemoval = {
515
- externalId: string;
516
- type: RelatedType;
517
- value: string;
518
- } | {
519
- externalId: string;
520
- type: RelatedType;
521
- relatedExternalId: string;
522
- };
523
- /** The relation as the api stored it: what you sent, with `at` as an ISO string. */
569
+ /** A value to take back, named as you added it. */
570
+ type RelationRemoval = RelationTarget;
571
+ /** The value as the api stored it: what you sent, with `at` as an ISO string. */
524
572
  type Relation = RelationTarget & {
525
573
  at?: string;
526
574
  };
527
- /** A relation as added: `linkWrite` says whether this call made a new link, the billed unit (a link added before isn't). */
575
+ /** A value as added: `created` says whether this call made it (false for one that was there already). */
528
576
  type AddedRelation = Relation & {
529
- linkWrite: boolean;
577
+ created: boolean;
530
578
  };
531
579
  /** A link to one user's Related view for your admin panel to frame, and when it stops working (ISO). */
532
580
  type Embed = {
@@ -535,22 +583,21 @@ type Embed = {
535
583
  };
536
584
  type ClientOptions = ApiOptions;
537
585
  /**
538
- * The api's error codes, any other string for one added later. `not_found` (`404`): no such event or visitor in the
539
- * project. `spend_limit_reached` (`402`): a spend limit you set for the project, its organization or the key stopped a
540
- * relation added by hand. `account_closed` (`402`): Zeno closed the organization's account, as for unpaid invoices, and
541
- * every call is refused until it's reopened; contact support. `search_unavailable` (`503`): search is briefly
542
- * unavailable; the SDK searches again after its `Retry-After`.
586
+ * The api's error codes, any other string for one added later. `not_found` (`404`): no such event, visitor or group in
587
+ * the project. `account_closed` (`402`): Zeno closed the organization's account, as for unpaid invoices, and every call
588
+ * is refused until it's reopened; contact support. `search_unavailable` (`503`): search is briefly unavailable; the SDK
589
+ * searches again after its `Retry-After`.
543
590
  *
544
591
  * The SDK's own: `request_failed` for an error answer without a code, or a success answer that isn't what the call
545
- * returns; `network_error` (status `0`) when the api couldn't be reached or didn't answer within 10 seconds;
546
- * `invalid_request` with status `0` for an empty id, refused before anything is sent.
592
+ * returns; `network_error` (status `0`) when the api couldn't be reached or didn't answer within 10 seconds (`verify`
593
+ * within 10 seconds in all, its retries included); `invalid_request` with status `0` for an empty id, refused before
594
+ * anything is sent.
547
595
  */
548
- type ZenoErrorCode = 'invalid_request' | 'invalid_api_key' | 'spend_limit_reached' | 'account_closed' | 'not_found' | 'method_not_allowed' | 'rate_limited' | 'search_unavailable' | 'server_error' | 'request_failed' | 'network_error' | (string & {});
596
+ type ZenoErrorCode = 'invalid_request' | 'invalid_api_key' | 'account_closed' | 'not_found' | 'method_not_allowed' | 'rate_limited' | 'relation_limit_reached' | 'search_unavailable' | 'server_error' | 'request_failed' | 'network_error' | (string & {});
549
597
  /**
550
598
  * An error answer of the api, with its status and error code like `not_found`, and for a `429 rate_limited` or `503
551
- * search_unavailable` the seconds to wait from its `Retry-After`. A relation added by hand and refused because a spend
552
- * limit you set (the project's, its organization's or the key's) is reached is a `402` `spend_limit_reached`. Any call
553
- * while the organization's account is closed is a `402` `account_closed`: contact support to reopen it.
599
+ * search_unavailable` the seconds to wait from its `Retry-After`. Any call while the organization's account is closed
600
+ * is a `402` `account_closed`: contact support to reopen it.
554
601
  */
555
602
  declare class ZenoError extends Error {
556
603
  readonly status: number;
@@ -620,18 +667,17 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
620
667
  * seconds (`too-old`, 5 minutes by default) or belongs to another user than `externalId`
621
668
  * (`external-id-mismatch`); otherwise it answers the event's verdict. Call it after the action succeeded (the
622
669
  * password matched, the account exists), with the user's ID: `externalId` is attached to an event without one.
623
- * It writes nothing else. A lost answer (a network error or a 5xx) is sent again twice with the same
624
- * idempotency key, which answers the first result rather than `already-used`. Other api errors throw.
670
+ * It writes nothing else. A lost answer (a network error or a 5xx) is sent again, twice at most, with the same
671
+ * idempotency key, which answers the first result rather than `already-used`. It answers or throws within 10
672
+ * seconds, those retries included. Other api errors throw.
625
673
  */
626
674
  verify: (requestId: string | undefined | null, options?: VerifyOptions) => Promise<VerifyResult>;
627
675
  getEvent: (requestId: string) => Promise<Event>;
628
676
  /** Events matching every filter, newest first; pass the cursor back for the next page. */
629
677
  searchEvents: (filters?: SearchFilters) => Promise<SearchResult>;
630
- /** A visitor (a browser) with every external id seen with it. */
631
- getVisitor: (visitorId: string) => Promise<Visitor>;
632
678
  /**
633
- * Reports what an event turned out to be, like after a chargeback or a review. The latest report counts, and it
634
- * never changes the event's score.
679
+ * Reports what an event turned out to be: `legitimate`, or the type of fraud it was, like `payment-fraud` after
680
+ * a chargeback. The latest report counts, and it never changes the event's score.
635
681
  */
636
682
  reportOutcome: (requestId: string, outcome: Outcome) => Promise<{
637
683
  requestId: string;
@@ -647,51 +693,93 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
647
693
  deletedEvents: number;
648
694
  }>;
649
695
  /**
650
- * Relates one of your users by hand: to an ip seen by another system, a value of a type of your own (a phone
651
- * number, your own device id) or another of your users (a referral). Visitor ids only come from events with an
652
- * external id, so `identified` means the user was seen in a browser.
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.
653
700
  *
654
- * A new link is billed like an identification (`linkWrite: true`); sending one again is free. Once a spend
655
- * limit you set is reached it throws a `402` `spend_limit_reached` and adds nothing; only a `429` is sent
656
- * again.
701
+ * Free, like reads. `created` says whether the call added the value; sending one again only brings it up to
702
+ * date.
657
703
  */
658
704
  addRelation: ({ at, ...relation }: RelationInput) => Promise<AddedRelation>;
659
705
  /**
660
- * Takes back a relation added with `addRelation`: a value, or a relation between two users (both sides go,
661
- * whichever side you name). What events related (a visitor id, an ip seen with an event) stays. Free.
706
+ * Takes back a value added with `addRelation`. What events added (a visitor id, an ip seen with an event)
707
+ * stays. Free.
662
708
  *
663
- * Answers `{ removed: false }` when there was nothing added by hand to take back, so it's safe to repeat.
709
+ * Answers `{ removed: false }` when there was no relation to take back, so it's safe to repeat.
664
710
  */
665
711
  removeRelation: (relation: RelationRemoval) => Promise<{
666
712
  removed: boolean;
667
713
  }>;
668
714
  /**
669
- * One of your users' values and relations, of one `type` or every type, each with its weight, and whether they
670
- * share one value weighing 0.5 or more with another user (`duplicate`). At most 500 (`truncated` past them).
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.
671
718
  */
672
- getRelatedValues: (externalId: string, { type }?: {
719
+ getRelatedValues: (externalId: string, { type, ...page }?: {
673
720
  type?: RelatedType;
721
+ limit?: number;
722
+ cursor?: string;
674
723
  }) => Promise<RelatedValues>;
675
724
  /**
676
- * Your users who have one value, like everyone with one phone number, 20 a page by default (`limit` up to 100);
677
- * pass the cursor back for the next page.
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.
678
727
  */
679
728
  lookupRelated: (type: RelatedType, value: string, page?: {
680
729
  limit?: number;
681
730
  cursor?: string;
682
731
  }) => Promise<Page<RelatedUser>>;
683
732
  /**
684
- * Your users related to one through shared values or relations of every type, or of one `type`, up to `depth`
685
- * (1 to 5, 1 by default) hops away, heaviest first, each with its weight.
733
+ * 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.
686
735
  */
687
736
  getRelated: (externalId: string, { type, depth }?: {
688
737
  type?: RelatedType;
689
738
  depth?: number;
690
739
  }) => Promise<Related>;
740
+ /**
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.
746
+ */
747
+ getRelatedGroup: (externalId: string, page?: {
748
+ limit?: number;
749
+ cursor?: string;
750
+ }) => Promise<RelatedGroup>;
751
+ /**
752
+ * A group by its ID, with its `size` and its users, 500 a page by default (`limit` up to 500; pass the cursor
753
+ * back for the next page): for an event without a user, whose `groupId` is its visitor ID's group. An ID that
754
+ * names no group any more throws `not_found`: when two groups join, the bigger one's ID stays and the other ID
755
+ * stops naming a group. A group past 10,000 users is answered as 10,000 of its users.
756
+ */
757
+ getGroup: (groupId: string, page?: {
758
+ limit?: number;
759
+ cursor?: string;
760
+ }) => Promise<Group>;
761
+ /**
762
+ * Every type of the project, the built-ins and your own, each with its weight, its Match within and their
763
+ * defaults. A type weighing 0.75 or more makes duplicates and ties groups.
764
+ */
765
+ getRelatedWeights: () => Promise<{
766
+ items: RelatedWeight[];
767
+ }>;
768
+ /**
769
+ * Sets one type's settings for the project, either or both in one call: its `weight` (0 to 1) and its
770
+ * `matchWithinDays` (how many days apart two users may have been seen with a value and still share it, 1 to
771
+ * 3650), each `null` to go back to the default. Both apply when related users are read, so the change counts
772
+ * for the values you have already; taking a type across 0.75 or changing a strong type's days can change group
773
+ * IDs. Answers the type.
774
+ */
775
+ setRelatedType: (type: RelatedType, settings: {
776
+ weight?: number | null;
777
+ matchWithinDays?: number | null;
778
+ }) => Promise<RelatedWeight>;
691
779
  /**
692
780
  * A link to one user's Related view (their values, related users and recent events) for your admin panel at
693
- * `origin` to frame, working for `ttl` minutes (5 to 60, 15 by default). Make one per page view and never hand
694
- * the API key to the browser.
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.
695
783
  */
696
784
  createEmbed: (embed: {
697
785
  externalId: string;
@@ -706,8 +794,8 @@ type WebhookEvent = Omit<Event, 'broadVisitorId' | 'proximity' | 'rawDeviceAttri
706
794
  /**
707
795
  * Checks a webhook delivery's Zeno-Signature header against the project's webhook secret, and that it was signed in the
708
796
  * last `tolerance` seconds, so a captured delivery can't be replayed later. Pass the raw body. Resolves to the event
709
- * when it matched, else to undefined; rejects with a TypeError when the secret is missing, and with an Error for a
710
- * signed body that isn't an event.
797
+ * when it matched, else to undefined; rejects with a TypeError when the secret is missing or the body isn't text (a
798
+ * parsed one), and with an Error for a signed body that isn't an event.
711
799
  */
712
800
  declare const verifyWebhook: (body: string, header: string | null | undefined, secret: string | undefined, { tolerance }?: {
713
801
  tolerance?: number | undefined;
@@ -739,6 +827,6 @@ type UnsealOptions = {
739
827
  * allows each request ID once. Rejects with a TypeError for a missing or malformed key. The format: base64(version |
740
828
  * iv(12) | ciphertext | tag(16)), AES-256-GCM.
741
829
  */
742
- declare const unsealResult: (sealed: string | undefined | null, options: UnsealOptions) => Promise<VerifyResult>;
830
+ declare const unsealResult: (sealedResult: string | undefined | null, options: UnsealOptions) => Promise<VerifyResult>;
743
831
  //#endregion
744
- export { AddedRelation, type ApiOptions, Bot, BotType, Client, ClientOptions, Confidence, Connection, Contradiction, Embed, Event, EventBot, EventBrowser, EventIp, ForgedPayloadIndicator, GlobalFields, Metadata, NetworkOwnerType, Outcome, Page, type ProxyHandler, type ProxyOptions, RawDeviceAttributes, Related, RelatedKind, RelatedType, RelatedUser, RelatedValue, RelatedValues, Relation, RelationInput, RelationRemoval, SIGNALS, SearchEvent, SearchFilters, SearchResult, Signal, SignalDetails, SignalReason, SignalResult, Signals, UnsealOptions, Velocity, Verdict, VerdictAction, VerdictReason, VerifyCheck, VerifyOptions, VerifyResult, VirtualMachineIndicator, Visitor, WebhookEvent, ZenoError, ZenoErrorCode, createClient, createProxy, unsealResult, verifyWebhook };
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 };
@@ -1,2 +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{failed:k()};if(r.status!==304&&!r.ok)return{failed: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}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed: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.failed)return n.failed;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.failed)return e.failed;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 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 u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},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`],k=1e4;var A=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 j=(e,t)=>{if(!e)throw TypeError(t);return e},M=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},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} 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);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);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 A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},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`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),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}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(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},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),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`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.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?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(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},ae=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{}}},oe=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(ie);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=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.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,A as ZenoError,J as createClient,D as createProxy,oe as unsealResult,re as verifyWebhook};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zeno.id",
3
- "version": "0.6.0",
3
+ "version": "0.7.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": [