@sekyro/node 1.0.0-rc.19 → 1.0.0-rc.21

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.
@@ -56,23 +56,26 @@ interface SessionDecidingStep {
56
56
  service: string;
57
57
  }
58
58
  /**
59
- * What a finished session proved: `1` a live, real person (human), `2` that
60
- * person's identity (document, chip, registry or supplied data bound to the
61
- * face), `3` an identity corroborated by an independent source. `0` on a
62
- * rejected session.
59
+ * What a finished session proved: `1` Contact (a contact, a device check or
60
+ * identity data with no live person), `2` Human (a live, real person), `3`
61
+ * Identity (who the person is). `0` when nothing was proven.
63
62
  * @public
64
63
  */
65
64
  type VerificationLevel = 0 | 1 | 2 | 3;
66
65
  /**
67
- * How a session's {@link VerificationLevel} was proved: `live_only` (liveness
68
- * only), `live_unique` (liveness plus a duplicate search), and the
69
- * `*_biometric` values, where a face match bound the person to a document,
70
- * its chip, the registry record or partner-supplied identity data, and
71
- * `eid_authenticated`, where the person signed in with a national digital
72
- * identity (level 3 without a Sekyro selfie).
66
+ * How a session's {@link VerificationLevel} was proved. Level 1:
67
+ * `device_only` (a device and network check), `contact_email`,
68
+ * `contact_phone` (a verified contact), `unbound_identity` (identity data
69
+ * with no live face matched to it). Level 2: `live_only` (liveness only),
70
+ * `live_unique` (liveness plus a duplicate search). Level 3: the
71
+ * `*_biometric` values, where a face match bound the person to
72
+ * partner-supplied identity data, a document, its chip or the registry
73
+ * record, and `eid_authenticated`, where the person signed in with a
74
+ * national digital identity. To require a particular proof, gate on a list
75
+ * of these values, for example `["registry_biometric"]`.
73
76
  * @public
74
77
  */
75
- type VerificationAssurance = "live_only" | "live_unique" | "document_biometric" | "chip_biometric" | "registry_biometric" | "supplied_biometric" | "eid_authenticated";
78
+ type VerificationAssurance = "device_only" | "contact_email" | "contact_phone" | "unbound_identity" | "live_only" | "live_unique" | "supplied_biometric" | "document_biometric" | "eid_authenticated" | "chip_biometric" | "registry_biometric";
76
79
  /** The one billing unit a finished session consumed. @public */
77
80
  type VerificationUnit = "human_verification" | "identity_verification";
78
81
  /** The lowest and highest {@link VerificationLevel} the session's flow can reach. @public */
@@ -285,7 +288,7 @@ interface SignalEventData {
285
288
  /**
286
289
  * How a `person.reuse` session runs: `recheck` verifies the same person
287
290
  * again (liveness and face match against the stored photo), `step_up` raises
288
- * the subject to identity level with a flow that proves level 2 on every path.
291
+ * the subject to identity level with a flow that proves Identity (level 3) on every path.
289
292
  * @public
290
293
  */
291
294
  type SubjectReuseMode = "recheck" | "step_up";
@@ -308,7 +311,7 @@ interface SessionLinkInput {
308
311
  */
309
312
  type IdentityMethod = "national_number" | "document_photo" | "document_chip" | "national_eid";
310
313
  /** The verification checks a flow may contain. @public */
311
- type CheckType = "liveness" | "face_match" | "doc_ocr" | "population_registry" | "phone_otp" | "nfc_chip" | "email_otp" | "portrait_icao" | "eid_auth" | "aml_screening";
314
+ type CheckType = "liveness" | "face_match" | "doc_ocr" | "population_registry" | "phone_otp" | "nfc_chip" | "email_otp" | "portrait_icao" | "eid_auth" | "aml_screening" | "poa";
312
315
  /** Per-check execution state within a session. @public */
313
316
  type CheckState = "pending" | "input_required" | "processing" | "passed" | "failed" | "review" | "skipped";
314
317
  /**
@@ -637,7 +640,7 @@ interface DeliverOptions {
637
640
  * @public
638
641
  */
639
642
  interface SubjectIdNumber {
640
- type: "national_id" | "passport" | "residence_permit";
643
+ type: "national_id" | "passport" | "residence_permit" | "drivers_license";
641
644
  issuingCountry: string;
642
645
  number: string;
643
646
  }
@@ -671,10 +674,24 @@ interface PersonBirthPlaceInput {
671
674
  * @public
672
675
  */
673
676
  interface PersonDocumentInput {
674
- type: "national_id" | "passport" | "residence_permit";
677
+ type: "national_id" | "passport" | "residence_permit" | "drivers_license";
675
678
  issuingCountry: string;
676
679
  number: string;
677
680
  }
681
+ /**
682
+ * The person's address ({@link SessionPersonInput.address}).
683
+ * @public
684
+ */
685
+ interface PersonAddressInput {
686
+ /** ISO 3166-1 alpha-2. */
687
+ country: string;
688
+ /** 1 to 80 characters. */
689
+ city: string;
690
+ /** Street lines, 1 to 4, each 1 to 120 characters. */
691
+ lines: string[];
692
+ /** 1 to 16 characters. */
693
+ postcode?: string;
694
+ }
678
695
  /**
679
696
  * What you already know about the person (`person` at session create). A
680
697
  * closed object: unknown keys are refused (`400`). Every field is optional;
@@ -713,6 +730,12 @@ interface SessionPersonInput {
713
730
  nationalities?: string[];
714
731
  /** The person's identity document ({@link PersonDocumentInput}). */
715
732
  document?: PersonDocumentInput;
733
+ /**
734
+ * The address you hold for the person ({@link PersonAddressInput}). A proof of
735
+ * address step compares the address it reads with it and fails
736
+ * `address_mismatch` on another country, city or street.
737
+ */
738
+ address?: PersonAddressInput;
716
739
  /**
717
740
  * Base64 JPEG or PNG (optional data-URL prefix, at most 1 MB decoded): the
718
741
  * face-match reference of a reference record. Refused in a flow that uses the
@@ -763,7 +786,7 @@ type SubjectReuseTarget = ({
763
786
  }) & {
764
787
  /**
765
788
  * `recheck` (default) or `step_up` ({@link SubjectReuseMode}). `step_up` on
766
- * a flow that does not prove level 2 on every path answers
789
+ * a flow that does not prove Identity (level 3) on every path answers
767
790
  * `400 step_up_flow_too_weak`.
768
791
  */
769
792
  mode?: SubjectReuseMode;
@@ -771,13 +794,21 @@ type SubjectReuseTarget = ({
771
794
  /** A document type the backend reads (kyc-docs-v2 vocabulary; `carte_identite` = identity card of any issuer). @public */
772
795
  type ProfileDocumentType = "carte_identite" | "passport" | "residence_permit";
773
796
  /**
774
- * The services a Sekyro flow is built from. A session's steps
775
- * ({@link SessionStep.service}) and {@link FlowOverrides.services} use these
776
- * ids; one service may run several checks (e.g. `liveness` with an ICAO
777
- * portrait).
797
+ * The services of a session's steps ({@link SessionStep.service}); one service
798
+ * may run several checks (e.g. `liveness` with an ICAO portrait).
799
+ * `summary_confirm` is the confirmation of details, which a flow turns on with
800
+ * its `confirmDetails` setting (see {@link OverridableServiceId}).
778
801
  * @public
779
802
  */
780
- type ServiceId = "device_network" | "phone_otp" | "email_otp" | "national_eid" | "document" | "nfc" | "population_registry" | "supplied_identity" | "summary_confirm" | "liveness" | "portrait" | "face_match" | "aml_screening" | "face_dedup" | "age_estimation";
803
+ type ServiceId = "device_network" | "phone_otp" | "email_otp" | "national_eid" | "document" | "nfc" | "proof_of_address" | "population_registry" | "supplied_identity" | "summary_confirm" | "liveness" | "portrait" | "face_match" | "aml_screening" | "face_dedup" | "age_estimation";
804
+ /**
805
+ * The services a Sekyro flow is built from, as {@link FlowOverrides.services}
806
+ * names them: every {@link ServiceId} except `summary_confirm` (the
807
+ * confirmation of details is the `confirmDetails` setting,
808
+ * {@link FlowOverridableSettings.confirmDetails}).
809
+ * @public
810
+ */
811
+ type OverridableServiceId = Exclude<ServiceId, "summary_confirm">;
781
812
  /**
782
813
  * The general settings of a flow that a session may override (the flow's
783
814
  * `link`, `language` and override policy are not overridable). Country codes
@@ -828,6 +859,15 @@ interface FlowOverridableSettings {
828
859
  };
829
860
  authenticity: "standard" | "off";
830
861
  };
862
+ /**
863
+ * Ask the person to confirm the identity data read from them (`enabled`),
864
+ * and let them retake the identity step from there (`retake`). Turning it on
865
+ * narrows the flow, turning it off widens it; allowing a retake widens it.
866
+ */
867
+ confirmDetails?: {
868
+ enabled: boolean;
869
+ retake: boolean;
870
+ };
831
871
  }
832
872
  /**
833
873
  * Document substitution: the portrait a `document` or `nfc` step produces is
@@ -842,7 +882,7 @@ interface DocumentSubstitutionSettings {
842
882
  failBelow?: number;
843
883
  }
844
884
  /**
845
- * The per-service settings a session may override, by {@link ServiceId}.
885
+ * The per-service settings a session may override, by {@link OverridableServiceId}.
846
886
  * `attempts` limits are per step (absent = the platform default).
847
887
  * @public
848
888
  */
@@ -916,6 +956,21 @@ interface FlowServiceSettings {
916
956
  /** Compare the chip photo with the registry photo (absent = the platform default). */
917
957
  documentSubstitution?: DocumentSubstitutionSettings;
918
958
  };
959
+ /**
960
+ * Proof of address. `rules` absent = `{ default: 'presets' }`; `nameMatch` absent =
961
+ * `exact_person`; `addressMatch` absent = `when_supplied`; `source` absent = `choice`.
962
+ */
963
+ proof_of_address: {
964
+ /** The accepted kinds, each with its max age in days (30 to 730), by default and per ISO2 country. */
965
+ rules?: PoaRules;
966
+ nameMatch?: "exact_person" | "family_name" | "third_party_letter";
967
+ addressMatch?: "when_supplied" | "off";
968
+ /** A driver's license read earlier in the session that carries an address passes the step. */
969
+ acceptLicenceAddress?: boolean;
970
+ source?: "camera" | "upload" | "choice";
971
+ attempts?: number;
972
+ strictness?: "relaxed" | "standard" | "strict";
973
+ };
919
974
  population_registry: {
920
975
  /** `'org'` (every registry the org can use, resolved at session create) or registry ids. */
921
976
  sources: "org" | Array<"MR.anrpts">;
@@ -930,10 +985,6 @@ interface FlowServiceSettings {
930
985
  attempts?: number;
931
986
  };
932
987
  supplied_identity: Record<string, never>;
933
- summary_confirm: {
934
- /** Offer « Reprendre » (re-open the identity source). */
935
- retake: boolean;
936
- };
937
988
  liveness: {
938
989
  /** `off`, selfie ICAO `alert` / `reject`, or `id_document` (ID-photo portrait, always rejects). */
939
990
  icao: "off" | "alert" | "reject" | "id_document";
@@ -980,6 +1031,20 @@ interface FlowServiceSettings {
980
1031
  showEstimatedAge?: boolean;
981
1032
  };
982
1033
  }
1034
+ /** One accepted kind of a proof of address rule and its maximum age (30 to 730 days). @public */
1035
+ interface PoaRuleKind {
1036
+ kind: PoaDocumentKind;
1037
+ maxAgeDays: number;
1038
+ }
1039
+ /** The kinds a proof of address accepts in one country (at least one, none twice). @public */
1040
+ interface PoaRule {
1041
+ kinds: PoaRuleKind[];
1042
+ }
1043
+ /** A proof of address step's rules ({@link FlowServiceSettings.proof_of_address}). @public */
1044
+ interface PoaRules {
1045
+ default: "presets" | PoaRule;
1046
+ byCountry?: Record<string, PoaRule>;
1047
+ }
983
1048
  /**
984
1049
  * `T` with every property optional, recursively. Arrays are replaced as a
985
1050
  * whole, never merged element by element.
@@ -1017,7 +1082,7 @@ type DeepPartial<T> = T extends readonly unknown[] ? T : T extends object ? {
1017
1082
  interface FlowOverrides {
1018
1083
  settings?: DeepPartial<FlowOverridableSettings>;
1019
1084
  services?: {
1020
- [S in ServiceId]?: DeepPartial<FlowServiceSettings[S]> | "off";
1085
+ [S in OverridableServiceId]?: DeepPartial<FlowServiceSettings[S]> | "off";
1021
1086
  };
1022
1087
  }
1023
1088
  /**
@@ -1519,7 +1584,7 @@ interface IdentityBirthPlace {
1519
1584
  }
1520
1585
  /** The holder's national number, when a per-country rule recognises it ({@link Identity.idNumber}). @public */
1521
1586
  interface IdentityIdNumber {
1522
- type: "national_id" | "passport" | "residence_permit";
1587
+ type: "national_id" | "passport" | "residence_permit" | "drivers_license";
1523
1588
  /** ISO 3166-1 alpha-2. */
1524
1589
  issuingCountry: string;
1525
1590
  /** The number, normalised. */
@@ -1527,7 +1592,9 @@ interface IdentityIdNumber {
1527
1592
  }
1528
1593
  /** The document or chip that was read ({@link Identity.document}). @public */
1529
1594
  interface IdentityDocument {
1530
- type: "national_id" | "passport" | "residence_permit";
1595
+ type: "national_id" | "passport" | "residence_permit" | "drivers_license";
1596
+ /** A driver's licence's vehicle categories as printed (`B`, `C1E`, ...). */
1597
+ categories?: string[];
1531
1598
  /** ISO 3166-1 alpha-2, or the ICAO code as read when it has no ISO equivalent. */
1532
1599
  issuingCountry?: string;
1533
1600
  /** The document number as read: upper case, no spaces. */
@@ -1541,6 +1608,36 @@ interface IdentityDocument {
1541
1608
  /** The keys whose value a check digit protects. Never the names. */
1542
1609
  mrzVerified?: Array<"number" | "birthDate" | "expiryDate" | "idNumber">;
1543
1610
  }
1611
+ /** The address an identity carries ({@link Identity.address}). @public */
1612
+ interface IdentityAddress {
1613
+ lines: string[];
1614
+ city: string;
1615
+ region?: string;
1616
+ postcode?: string;
1617
+ /** ISO 3166-1 alpha-2. */
1618
+ country: string;
1619
+ source: "proof_of_address" | "drivers_license";
1620
+ }
1621
+ /** A document kind a proof of address step accepts. @public */
1622
+ type PoaDocumentKind = "utility_bill" | "telecom_bill" | "bank_statement" | "tax_notice" | "rental_agreement" | "government_certificate" | "insurance_statement";
1623
+ /** The passed proof of address step ({@link Identity.proofOfAddress}). @public */
1624
+ interface IdentityProofOfAddress {
1625
+ /** `drivers_license` when a driver's licence read earlier gave the address. */
1626
+ documentKind: PoaDocumentKind | "drivers_license";
1627
+ issuer?: string;
1628
+ /** `YYYY-MM-DD`. */
1629
+ issueDate: string;
1630
+ /** How the holder's name matched: the person, the family name, or a signed letter from another holder. */
1631
+ matchedBy: "person" | "family_name" | "third_party";
1632
+ /** ISO 8601: when the step passed. */
1633
+ verifiedAt: string;
1634
+ }
1635
+ /**
1636
+ * Why a proof of address step failed (`reasonCode`). `provider_unavailable`,
1637
+ * `unreadable`, `pdf_protected` and `holder_letter_required` are never billed.
1638
+ * @public
1639
+ */
1640
+ type PoaReason = "provider_unavailable" | "unreadable" | "pdf_protected" | "document_kind_not_accepted" | "document_date_invalid" | "document_too_old" | "document_tampered" | "name_mismatch" | "holder_letter_required" | "holder_letter_missing" | "address_mismatch";
1544
1641
  /**
1545
1642
  * The scalar keys of {@link Identity} that {@link Identity.sources} reports on.
1546
1643
  * @public
@@ -1587,6 +1684,13 @@ interface Identity {
1587
1684
  country: string;
1588
1685
  verifiedAt?: string;
1589
1686
  };
1687
+ /**
1688
+ * The address a passed proof of address read (the newest pass), else the
1689
+ * address of a driver's licence the session accepted. Never in the result token.
1690
+ */
1691
+ address?: IdentityAddress;
1692
+ /** The passed proof of address step. */
1693
+ proofOfAddress?: IdentityProofOfAddress;
1590
1694
  /** ISO 8601: when the last identity step settled. */
1591
1695
  verifiedAt?: string;
1592
1696
  /** @deprecated Read {@link Identity.names}. The first Latin name as one string. */
@@ -1597,7 +1701,7 @@ interface Identity {
1597
1701
  * `reference_portrait` is the photo the face match compared against.
1598
1702
  * @public
1599
1703
  */
1600
- type MediaKind = "icao_portrait" | "document_front" | "document_back" | "document_portrait" | "chip_portrait" | "reference_portrait" | "supplied_photo" | "selfie" | "liveness_clip";
1704
+ type MediaKind = "icao_portrait" | "document_front" | "document_back" | "document_portrait" | "chip_portrait" | "reference_portrait" | "supplied_photo" | "selfie" | "liveness_clip" | "address_document" | "address_document_file" | "holder_letter";
1601
1705
  /**
1602
1706
  * One media object of a session ({@link SessionsApi.media}). `url` is a
1603
1707
  * download link valid 15 minutes, or the bytes route on this API
@@ -1619,7 +1723,7 @@ interface MediaItem {
1619
1723
  reason?: string;
1620
1724
  /** The attempt was set aside (for example a retake) and not counted. */
1621
1725
  voided?: string;
1622
- contentType: "image/jpeg" | "image/png" | "video/mp4" | "video/webm";
1726
+ contentType: "image/jpeg" | "image/png" | "video/mp4" | "video/webm" | "application/pdf";
1623
1727
  /** `reference_portrait` and `supplied_photo`: where the photo came from (`stored`: kept from an earlier verification). */
1624
1728
  source?: "registry" | "eid" | "chip" | "document" | "supplied" | "stored";
1625
1729
  /** `reference_portrait`: the registry photo was fetched again for this match. */
@@ -2148,7 +2252,7 @@ interface BlockIdNumber {
2148
2252
  number: string;
2149
2253
  /** ISO 3166-1 alpha-2 or alpha-3 code of the issuer. */
2150
2254
  issuingCountry: string;
2151
- type: "national_id" | "passport" | "residence_permit";
2255
+ type: "national_id" | "passport" | "residence_permit" | "drivers_license";
2152
2256
  }
2153
2257
  /**
2154
2258
  * What to block, with `sekyro.blocks.create`. `value` carries `external_ref`, `phone` and
@@ -2955,4 +3059,4 @@ declare class Sekyro {
2955
3059
  readiness(): Promise<ReadinessReport>;
2956
3060
  }
2957
3061
 
2958
- export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type SessionEventStep as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityBirthPlace as a3, type IdentityDocument as a4, type IdentityIdNumber as a5, type IdentityMethod as a6, type IdentityName as a7, type IdentityScalarKey as a8, type IdentitySource as a9, type PersonUpdatedEventData as aA, type PortraitReportEntry as aB, type PriorReviewReason as aC, type ProbeBindingReason as aD, type ProbeQuality as aE, type ProfileDocumentType as aF, type ReadinessProtection as aG, type ReadinessReport as aH, type RequestOptions as aI, type ResultTokenResponse as aJ, type ReviewOutcomeReason as aK, type RevokePersonInput as aL, type ScreenPersonInput as aM, type Screening as aN, type ScreeningHit as aO, type ScreeningHitSummary as aP, type ScreeningList as aQ, type ScreeningStatus as aR, type ScreeningTrigger as aS, type ScreeningUnavailableReason as aT, type SekyroOptions as aU, SekyroTestApi as aV, type Session as aW, type SessionClosedEventDataBase as aX, type SessionDecidingStep as aY, type SessionDevice as aZ, type SessionEventDataBase as a_, type IdentitySources as aa, type LevelTarget as ab, type LiftBlockInput as ac, type ListBlocksQuery as ad, type ListPeopleQuery as ae, type ListScreeningsQuery as af, type ListSessionsQuery as ag, type ListSignalsQuery as ah, type MatchReason as ai, type MediaBytes as aj, type MediaBytesOptions as ak, type MediaItem as al, type MediaKind as am, type MediaList as an, type NameForm as ao, type Page as ap, PeopleApi as aq, type Person as ar, type PersonBirthPlaceInput as as, type PersonDeletedEventData as at, type PersonDocumentInput as au, type PersonEnrolledEventData as av, type PersonRef as aw, type PersonSession as ax, type PersonSessionInput as ay, type PersonSessionTarget as az, type ServiceId as b, type SessionFailureReason as b0, type SessionFlowRef as b1, type SessionHandoff as b2, type SessionHandoffDevice as b3, type SessionLifecycleEventData as b4, type SessionLinkDelivery as b5, type SessionLinkExpiry as b6, type SessionLinkInput as b7, type SessionNetwork as b8, type SessionNetworkEvent as b9, type SubjectIdNumber as bA, type SubjectName as bB, type SubjectReferenceSource as bC, type SubjectReuseTarget as bD, type SubjectStatus as bE, type UpdateSignalInput as bF, type UsageThresholdReachedEventData as bG, type VerifiedContacts as bH, type WebhookEnvelopeOf as bI, type WebhookEventDataMap as bJ, type WebhookTestInput as bK, type WebhookTestResult as bL, WebhooksApi as bM, type SessionNotVerifiedEventData as ba, type SessionRetakeRequestedEventData as bb, type SessionReviewPendingEventData as bc, type SessionScreening as bd, type SessionStatus as be, type SessionStep as bf, type SessionStepAttempts as bg, type SessionStepBand as bh, type SessionStepDecision as bi, type SessionStepDocument as bj, type SessionStepPortrait as bk, SessionTestApi as bl, type SessionVerifiedEventData as bm, SessionsApi as bn, type Signal as bo, type SignalEventData as bp, type SignalEvidence as bq, type SignalGrade as br, type SignalKeyKind as bs, type SignalKind as bt, type SignalSeverity as bu, type SignalStatus as bv, SignalsApi as bw, type SimulateSessionInput as bx, type StepResult as by, type SubjectAssurance as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
3062
+ export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type ScreeningTrigger as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityAddress as a3, type IdentityBirthPlace as a4, type IdentityDocument as a5, type IdentityIdNumber as a6, type IdentityMethod as a7, type IdentityName as a8, type IdentityProofOfAddress as a9, type PersonRef as aA, type PersonSession as aB, type PersonSessionInput as aC, type PersonSessionTarget as aD, type PersonUpdatedEventData as aE, type PoaDocumentKind as aF, type PoaReason as aG, type PoaRule as aH, type PoaRuleKind as aI, type PoaRules as aJ, type PortraitReportEntry as aK, type PriorReviewReason as aL, type ProbeBindingReason as aM, type ProbeQuality as aN, type ProfileDocumentType as aO, type ReadinessProtection as aP, type ReadinessReport as aQ, type RequestOptions as aR, type ResultTokenResponse as aS, type ReviewOutcomeReason as aT, type RevokePersonInput as aU, type ScreenPersonInput as aV, type Screening as aW, type ScreeningHit as aX, type ScreeningHitSummary as aY, type ScreeningList as aZ, type ScreeningStatus as a_, type IdentityScalarKey as aa, type IdentitySource as ab, type IdentitySources as ac, type LevelTarget as ad, type LiftBlockInput as ae, type ListBlocksQuery as af, type ListPeopleQuery as ag, type ListScreeningsQuery as ah, type ListSessionsQuery as ai, type ListSignalsQuery as aj, type MatchReason as ak, type MediaBytes as al, type MediaBytesOptions as am, type MediaItem as an, type MediaKind as ao, type MediaList as ap, type NameForm as aq, type OverridableServiceId as ar, type Page as as, PeopleApi as at, type Person as au, type PersonAddressInput as av, type PersonBirthPlaceInput as aw, type PersonDeletedEventData as ax, type PersonDocumentInput as ay, type PersonEnrolledEventData as az, type ServiceId as b, type ScreeningUnavailableReason as b0, type SekyroOptions as b1, SekyroTestApi as b2, type Session as b3, type SessionClosedEventDataBase as b4, type SessionDecidingStep as b5, type SessionDevice as b6, type SessionEventDataBase as b7, type SessionEventStep as b8, type SessionFailureReason as b9, type SignalGrade as bA, type SignalKeyKind as bB, type SignalKind as bC, type SignalSeverity as bD, type SignalStatus as bE, SignalsApi as bF, type SimulateSessionInput as bG, type StepResult as bH, type SubjectAssurance as bI, type SubjectIdNumber as bJ, type SubjectName as bK, type SubjectReferenceSource as bL, type SubjectReuseTarget as bM, type SubjectStatus as bN, type UpdateSignalInput as bO, type UsageThresholdReachedEventData as bP, type VerifiedContacts as bQ, type WebhookEnvelopeOf as bR, type WebhookEventDataMap as bS, type WebhookTestInput as bT, type WebhookTestResult as bU, WebhooksApi as bV, type SessionFlowRef as ba, type SessionHandoff as bb, type SessionHandoffDevice as bc, type SessionLifecycleEventData as bd, type SessionLinkDelivery as be, type SessionLinkExpiry as bf, type SessionLinkInput as bg, type SessionNetwork as bh, type SessionNetworkEvent as bi, type SessionNotVerifiedEventData as bj, type SessionRetakeRequestedEventData as bk, type SessionReviewPendingEventData as bl, type SessionScreening as bm, type SessionStatus as bn, type SessionStep as bo, type SessionStepAttempts as bp, type SessionStepBand as bq, type SessionStepDecision as br, type SessionStepDocument as bs, type SessionStepPortrait as bt, SessionTestApi as bu, type SessionVerifiedEventData as bv, SessionsApi as bw, type Signal as bx, type SignalEventData as by, type SignalEvidence as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var express_exports={};__export(express_exports,{requireLevel:()=>requireLevel});module.exports=__toCommonJS(express_exports);var KNOWN_FLAGS=["face_mismatch","duplicate","revoked"],AGE_METHODS=["estimated","document","chip","registry","eid"];function ageProofOf(over,method){if(!(typeof over!="number"||!Number.isInteger(over)||over<=0)&&!(typeof method!="string"||!AGE_METHODS.includes(method)))return{over,method}}function canonicalId(id){return id.replace(/^(ses|per)_/,"")}function isRecord(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function isFiniteNumber(v){return typeof v=="number"&&Number.isFinite(v)}function build(c){let out={v:1,level:c.level,assurance:c.assurance,verified_at:c.verified_at};c.rechecked_at!==void 0&&(out.rechecked_at=c.rechecked_at),out.session_id=c.session_id,c.subject_id!==void 0&&(out.subject_id=canonicalId(c.subject_id)),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);flags.size>0&&(out.flags=[...flags].sort());let age=ageProofOf(c.age_over,c.age_method);return age&&(out.age_over=age.over,out.age_method=age.method),out}function parseClaim(value){let v=value;if(typeof v=="string")try{v=JSON.parse(v)}catch{return null}if(!isRecord(v)||!isFiniteNumber(v.v))return null;if(v.v>1)return v;if(v.v!==1)return null;let level=v.level;return level!==0&&level!==1&&level!==2&&level!==3||typeof v.assurance!="string"||!isFiniteNumber(v.verified_at)||typeof v.session_id!="string"||v.env!=="live"&&v.env!=="sandbox"?null:build({level,assurance:v.assurance,verified_at:v.verified_at,rechecked_at:isFiniteNumber(v.rechecked_at)?v.rechecked_at:void 0,session_id:v.session_id,subject_id:typeof v.subject_id=="string"?v.subject_id:void 0,env:v.env,flags:Array.isArray(v.flags)?v.flags:void 0,age_over:v.age_over,age_method:v.age_method})}var DEFAULT_DENY_FLAGS=["revoked","face_mismatch"],fail=(reason,action,claim)=>({ok:!1,reason,action,claim});function evaluateGate(claim,policy,nowSec=Math.floor(Date.now()/1e3)){let parsed=parseClaim(claim);if(!parsed)return fail("no_claim","verify",null);if(parsed.v>1)return fail("unsupported_version","verify",parsed);if(policy.env!==void 0&&parsed.env!==policy.env)return fail("wrong_env","verify",parsed);let deny2=policy.denyFlags??DEFAULT_DENY_FLAGS;if(parsed.flags?.some(f=>deny2.includes(f)))return fail("flagged","block",parsed);if(parsed.level<policy.level)return fail("level_too_low",parsed.level>=1?"step_up":"verify",parsed);if(policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400)return fail("stale","recheck",parsed);if(policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60)return fail("recheck_stale","recheck",parsed);if(policy.assurance&&!policy.assurance.includes(parsed.assurance))return fail("assurance_not_allowed","step_up",parsed);if(policy.minAge!==void 0){if(parsed.age_over===void 0||parsed.age_over<policy.minAge)return fail("age_not_proven","verify",parsed);if(policy.ageMethods&&(parsed.age_method===void 0||!policy.ageMethods.includes(parsed.age_method)))return fail("age_method_not_allowed","step_up",parsed)}return{ok:!0,claim:parsed}}function sekyroGate(source,tokenClaims,policy){let claims=tokenClaims??{};if("gate"in source)return source.gate(claims,policy);let effective=source.env!==void 0&&policy.env===void 0?{...policy,env:source.env}:policy;return evaluateGate(source.provider.readClaimFromToken(claims),effective)}function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}0&&(module.exports={requireLevel});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var express_exports={};__export(express_exports,{requireLevel:()=>requireLevel});module.exports=__toCommonJS(express_exports);var CLAIM_VERSION=2,KNOWN_FLAGS=["face_mismatch","duplicate","revoked"],AGE_METHODS=["estimated","document","chip","registry","eid"];function ageProofOf(over,method){if(!(typeof over!="number"||!Number.isInteger(over)||over<=0)&&!(typeof method!="string"||!AGE_METHODS.includes(method)))return{over,method}}function canonicalId(id){return id.replace(/^(ses|per)_/,"")}function isRecord(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function isFiniteNumber(v){return typeof v=="number"&&Number.isFinite(v)}function build(c){let out={v:CLAIM_VERSION,level:c.level,assurance:c.assurance,verified_at:c.verified_at};c.rechecked_at!==void 0&&(out.rechecked_at=c.rechecked_at),out.session_id=c.session_id,c.subject_id!==void 0&&(out.subject_id=canonicalId(c.subject_id)),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);flags.size>0&&(out.flags=[...flags].sort());let age=ageProofOf(c.age_over,c.age_method);return age&&(out.age_over=age.over,out.age_method=age.method),out}function parseClaim(value){let v=value;if(typeof v=="string")try{v=JSON.parse(v)}catch{return null}return!isRecord(v)||!isFiniteNumber(v.v)?null:v.v>CLAIM_VERSION?v:v.v!==CLAIM_VERSION||v.level!==0&&v.level!==1&&v.level!==2&&v.level!==3||typeof v.assurance!="string"||!isFiniteNumber(v.verified_at)||typeof v.session_id!="string"||v.env!=="live"&&v.env!=="sandbox"?null:build({level:v.level,assurance:v.assurance,verified_at:v.verified_at,rechecked_at:isFiniteNumber(v.rechecked_at)?v.rechecked_at:void 0,session_id:v.session_id,subject_id:typeof v.subject_id=="string"?v.subject_id:void 0,env:v.env,flags:Array.isArray(v.flags)?v.flags:void 0,age_over:v.age_over,age_method:v.age_method})}var DEFAULT_DENY_FLAGS=["revoked","face_mismatch"],fail=(reason,action,claim)=>({ok:!1,reason,action,claim});function evaluateGate(claim,policy,nowSec=Math.floor(Date.now()/1e3)){let parsed=parseClaim(claim);if(!parsed)return fail("no_claim","verify",null);if(parsed.v>CLAIM_VERSION)return fail("unsupported_version","verify",parsed);if(policy.env!==void 0&&parsed.env!==policy.env)return fail("wrong_env","verify",parsed);let deny2=policy.denyFlags??DEFAULT_DENY_FLAGS;if(parsed.flags?.some(f=>deny2.includes(f)))return fail("flagged","block",parsed);if(parsed.level<policy.level)return fail("level_too_low",parsed.level>=2?"step_up":"verify",parsed);if(policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400)return fail("stale","recheck",parsed);if(policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60)return fail("recheck_stale","recheck",parsed);if(policy.assurance&&!policy.assurance.includes(parsed.assurance))return fail("assurance_not_allowed","step_up",parsed);if(policy.minAge!==void 0){if(parsed.age_over===void 0||parsed.age_over<policy.minAge)return fail("age_not_proven","verify",parsed);if(policy.ageMethods&&(parsed.age_method===void 0||!policy.ageMethods.includes(parsed.age_method)))return fail("age_method_not_allowed","step_up",parsed)}return{ok:!0,claim:parsed}}function sekyroGate(source,tokenClaims,policy){let claims=tokenClaims??{};if("gate"in source)return source.gate(claims,policy);let effective=source.env!==void 0&&policy.env===void 0?{...policy,env:source.env}:policy;return evaluateGate(source.provider.readClaimFromToken(claims),effective)}function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}0&&(module.exports={requireLevel});
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-CyNFdiLv.cjs';
2
- import '../../client-BSzMfacG.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-BoksCP5p.cjs';
2
+ import '../../client-C5lyl8iQ.cjs';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/express`: a route gate for Express (and any
@@ -15,7 +15,7 @@ import '../../client-BSzMfacG.cjs';
15
15
  *
16
16
  * @example
17
17
  * ```ts
18
- * app.get("/payouts", requireLevel(connector, { level: 2, maxAgeDays: 365 }, { claims: (req) => (req as { auth?: Record<string, unknown> }).auth }), handler);
18
+ * app.get("/payouts", requireLevel(connector, { level: 3, maxAgeDays: 365 }, { claims: (req) => (req as { auth?: Record<string, unknown> }).auth }), handler);
19
19
  * ```
20
20
  * @param source - A connector, or `{ provider, env? }`.
21
21
  * @param policy - What the route requires.
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-D0CDGAOJ.js';
2
- import '../../client-BSzMfacG.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-CluvSk8L.js';
2
+ import '../../client-C5lyl8iQ.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/express`: a route gate for Express (and any
@@ -15,7 +15,7 @@ import '../../client-BSzMfacG.js';
15
15
  *
16
16
  * @example
17
17
  * ```ts
18
- * app.get("/payouts", requireLevel(connector, { level: 2, maxAgeDays: 365 }, { claims: (req) => (req as { auth?: Record<string, unknown> }).auth }), handler);
18
+ * app.get("/payouts", requireLevel(connector, { level: 3, maxAgeDays: 365 }, { claims: (req) => (req as { auth?: Record<string, unknown> }).auth }), handler);
19
19
  * ```
20
20
  * @param source - A connector, or `{ provider, env? }`.
21
21
  * @param policy - What the route requires.
@@ -1 +1 @@
1
- import{sekyroGate}from"../../chunk-VO3VIX3L.js";import"../../chunk-HQ4S5AND.js";function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}export{requireLevel};
1
+ import{sekyroGate}from"../../chunk-VALZSRLO.js";import"../../chunk-TPQKBAO4.js";function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}export{requireLevel};
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var connect_exports={};__export(connect_exports,{CLAIM_VERSION:()=>CLAIM_VERSION,SekyroConnectError:()=>SekyroConnectError,createConnector:()=>createConnector,evaluateGate:()=>evaluateGate,memoryStore:()=>memoryStore,mergeClaim:()=>mergeClaim,parseClaim:()=>parseClaim});module.exports=__toCommonJS(connect_exports);var CLAIM_VERSION=1,KNOWN_FLAGS=["face_mismatch","duplicate","revoked"],AGE_METHODS=["estimated","document","chip","registry","eid"];function ageProofOf(over,method){if(!(typeof over!="number"||!Number.isInteger(over)||over<=0)&&!(typeof method!="string"||!AGE_METHODS.includes(method)))return{over,method}}var ageRank=a=>a.method==="estimated"?0:1;function strongerAge(stored,next){if(!stored)return next;if(!next)return stored;let r=ageRank(next)-ageRank(stored);return r!==0?r>0?next:stored:next.over>stored.over?next:stored}var sameAge=(a,b)=>a?.over===b?.over&&a?.method===b?.method;function canonicalId(id){return id.replace(/^(ses|per)_/,"")}function isRecord(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function isFiniteNumber(v){return typeof v=="number"&&Number.isFinite(v)}function build(c){let out={v:1,level:c.level,assurance:c.assurance,verified_at:c.verified_at};c.rechecked_at!==void 0&&(out.rechecked_at=c.rechecked_at),out.session_id=c.session_id,c.subject_id!==void 0&&(out.subject_id=canonicalId(c.subject_id)),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);flags.size>0&&(out.flags=[...flags].sort());let age=ageProofOf(c.age_over,c.age_method);return age&&(out.age_over=age.over,out.age_method=age.method),out}function ageFields(age){return{age_over:age?.over,age_method:age?.method}}function parseClaim(value){let v=value;if(typeof v=="string")try{v=JSON.parse(v)}catch{return null}if(!isRecord(v)||!isFiniteNumber(v.v))return null;if(v.v>1)return v;if(v.v!==1)return null;let level=v.level;return level!==0&&level!==1&&level!==2&&level!==3||typeof v.assurance!="string"||!isFiniteNumber(v.verified_at)||typeof v.session_id!="string"||v.env!=="live"&&v.env!=="sandbox"?null:build({level,assurance:v.assurance,verified_at:v.verified_at,rechecked_at:isFiniteNumber(v.rechecked_at)?v.rechecked_at:void 0,session_id:v.session_id,subject_id:typeof v.subject_id=="string"?v.subject_id:void 0,env:v.env,flags:Array.isArray(v.flags)?v.flags:void 0,age_over:v.age_over,age_method:v.age_method})}function toUnix(isoTime,now){let ms=Date.parse(isoTime);return Math.floor((Number.isFinite(ms)?ms:now())/1e3)}var same=(claim,rule)=>({claim,changed:!1,rule}),wrote=(claim,rule)=>({claim,changed:!0,rule});function mergeClaim(previous,event,opts){let now=opts.now??Date.now,prev=parseClaim(previous);if(prev&&prev.v>1)return same(prev,"unsupported_version");if(event.kind==="revoked"||event.kind==="deleted"){if(!prev)return same(null,"no_change");if(!(prev.subject_id===void 0?event.userInExternalRefs===!0:prev.subject_id===canonicalId(event.subjectId)))return same(prev,"subject_mismatch");if(prev.level===0&&prev.flags?.includes("revoked"))return same(prev,"no_change");let{rechecked_at:_cleared,age_over:_over,age_method:_method,...kept}=prev;return wrote(build({...kept,level:0,subject_id:event.subjectId,flags:["revoked"]}),"revoked")}let r=event.result;if(r.env!==opts.env)return same(prev,"env_mismatch");let t=toUnix(r.verifiedAt,now);if(prev&&t<prev.verified_at)return same(prev,"stale_ignored");let revokedPrev=prev?.flags?.includes("revoked")===!0;if(prev&&revokedPrev&&(r.subjectId===void 0||canonicalId(r.subjectId)===prev.subject_id))return same(prev,"revoked_ignored");if(r.status==="not_verified"&&r.reason==="rejected"&&r.subjectConflict===!0)return!prev||prev.flags?.includes("face_mismatch")?same(prev,"no_change"):wrote(build({...prev,flags:[...prev.flags??[],"face_mismatch"]}),"face_mismatch");if(r.status!=="verified"||r.level===null||r.level===0)return same(prev,"not_verified");let level=r.level,assurance=r.assurance??"none",duplicate=r.duplicates===!0?["duplicate"]:[],nextAge=r.age?ageProofOf(r.age.over,r.age.method):void 0;if(!prev)return wrote(build({level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId,env:r.env,flags:duplicate,...ageFields(nextAge)}),"created");let prevAge=ageProofOf(prev.age_over,prev.age_method),otherPerson=prev.subject_id!==void 0&&r.subjectId!==void 0&&canonicalId(r.subjectId)!==prev.subject_id,mergedAge=otherPerson?prevAge:strongerAge(prevAge,nextAge);if(!revokedPrev&&(r.reuseMode==="recheck"||r.returning===!0&&level<=prev.level))return prev.rechecked_at!==void 0&&t<=prev.rechecked_at?same(prev,t<prev.rechecked_at?"stale_ignored":"no_change"):wrote(build({...prev,rechecked_at:t,subject_id:prev.subject_id??r.subjectId,...ageFields(mergedAge)}),"rechecked");if(level>prev.level){let kept=(prev.flags??[]).filter(f=>f!=="face_mismatch"&&f!=="revoked");return wrote(build({...prev,level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId??prev.subject_id,flags:[...kept,...duplicate],...ageFields(otherPerson?nextAge:mergedAge)}),"raised")}return level===prev.level&&t>prev.verified_at?wrote(build({...prev,assurance,verified_at:t,session_id:r.sessionId,subject_id:prev.subject_id??r.subjectId,flags:[...prev.flags??[],...duplicate],...ageFields(mergedAge)}),"renewed"):sameAge(mergedAge,prevAge)?same(prev,"no_change"):wrote(build({...prev,subject_id:prev.subject_id??r.subjectId,...ageFields(mergedAge)}),"age_proved")}var DEFAULT_DENY_FLAGS=["revoked","face_mismatch"],fail=(reason,action,claim)=>({ok:!1,reason,action,claim});function evaluateGate(claim,policy,nowSec=Math.floor(Date.now()/1e3)){let parsed=parseClaim(claim);if(!parsed)return fail("no_claim","verify",null);if(parsed.v>1)return fail("unsupported_version","verify",parsed);if(policy.env!==void 0&&parsed.env!==policy.env)return fail("wrong_env","verify",parsed);let deny=policy.denyFlags??DEFAULT_DENY_FLAGS;if(parsed.flags?.some(f=>deny.includes(f)))return fail("flagged","block",parsed);if(parsed.level<policy.level)return fail("level_too_low",parsed.level>=1?"step_up":"verify",parsed);if(policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400)return fail("stale","recheck",parsed);if(policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60)return fail("recheck_stale","recheck",parsed);if(policy.assurance&&!policy.assurance.includes(parsed.assurance))return fail("assurance_not_allowed","step_up",parsed);if(policy.minAge!==void 0){if(parsed.age_over===void 0||parsed.age_over<policy.minAge)return fail("age_not_proven","verify",parsed);if(policy.ageMethods&&(parsed.age_method===void 0||!policy.ageMethods.includes(parsed.age_method)))return fail("age_method_not_allowed","step_up",parsed)}return{ok:!0,claim:parsed}}var import_jose=require("jose"),import_result_token=require("@sekyro/node"),import_webhooks=require("@sekyro/node");var MESSAGES={token_session_mismatch:"The result token is for another session than the webhook",external_ref_mismatch:"The session belongs to another user",session_not_terminal:"The session has not finished yet",invalid_options:"Invalid connector options",unavailable:"The Sekyro AI public key set could not be fetched; try again"},SekyroConnectError=class extends Error{name="SekyroConnectError";code;constructor(code,message=MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}};var hasDuplicate=signals=>Array.isArray(signals)&&signals.some(s=>s!==null&&typeof s=="object"&&s.kind==="duplicate_identity");function factsOf(d,tokenSignals){let out={};return d.returning===!0&&(out.returning=!0),d.personConflict===!0&&(out.subjectConflict=!0),(hasDuplicate(d.signals)||hasDuplicate(tokenSignals))&&(out.duplicates=!0),out}function fromVerifiedResult(v,d){let out={sessionId:v.sessionId,status:v.status,level:v.level,assurance:v.assurance,verifiedAt:v.verifiedAt,env:v.env,...factsOf(d,v.signals)};return v.personId!==void 0&&(out.subjectId=canonicalId(v.personId)),v.reuseMode!==void 0&&(out.reuseMode=v.reuseMode),v.age!==void 0&&(out.age={over:v.age.over,method:v.age.method}),out}function fromWebhookData(d,env,nowMs){let out={sessionId:d.sessionId,status:d.status,level:d.level??null,assurance:d.assurance??null,verifiedAt:d.verifiedAt??new Date(nowMs).toISOString(),env,...factsOf(d)},person=d.personId;return typeof person=="string"&&person.length>0&&(out.subjectId=canonicalId(person)),d.reuseMode!==void 0&&(out.reuseMode=d.reuseMode),d.status==="not_verified"?(out.reason=d.reason,out):(d.age!==void 0&&d.age!==null&&(out.age={over:d.age.over,method:d.age.method}),out)}function memoryStore(opts={}){let now=opts.now??Date.now,ids=new Map,subjects=new Map,evict=t=>{for(let[id,expiresAt]of ids)expiresAt<=t&&ids.delete(id)};return{async seen(id,ttlSec){let t=now();return evict(t),ids.has(id)?!0:(ids.set(id,t+ttlSec*1e3),!1)},async forget(id){ids.delete(id)},async setSubjectUser(subjectId,userId){subjects.delete(subjectId),subjects.set(subjectId,userId),subjects.size>1e5&&subjects.delete(subjects.keys().next().value)},async getSubjectUser(subjectId){return subjects.get(subjectId)},size(){return evict(now()),ids.size}}}var KNOWN_CONNECTOR_PROVIDERS=new Set(["auth0","clerk","firebase","keycloak","supabase","zitadel"]),CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),TELEMETRY_TIMEOUT_MS=2e3,TELEMETRY_BATCH_MAX=50,QUEUE_MAX=500;function hooksOf(sekyro){let h=sekyro[CONNECT_TELEMETRY];return h&&typeof h.setConnector=="function"&&typeof h.postEvents=="function"?h:void 0}var OFF={record(){}};function connectTelemetry(opts){let hooks=hooksOf(opts.sekyro);if(!hooks)return OFF;let name=opts.provider.name;if(!opts.enabled||!KNOWN_CONNECTOR_PROVIDERS.has(name))return opts.enabled||hooks.setConnector(null),OFF;hooks.setConnector({provider:name,version:opts.provider.version??"unknown"});let queue=[],scheduled=!1,flush=()=>{for(scheduled=!1;queue.length>0;){let batch=queue.splice(0,TELEMETRY_BATCH_MAX);hooks.postEvents(batch,TELEMETRY_TIMEOUT_MS).catch(()=>{})}};return{record(event){if(queue.length>=QUEUE_MAX)return;let e={type:event.type,provider:name,at:new Date(opts.now()).toISOString()};if(typeof event.sessionId=="string"&&event.sessionId.length>0&&(e.sessionId=event.sessionId),typeof event.personId=="string"&&event.personId.length>0&&(e.personId=`per_${canonicalId(event.personId)}`),queue.push(e),scheduled)return;scheduled=!0,setTimeout(flush,0).unref?.()}}}var DEDUP_TTL_SEC=24*3600,JTI_TTL_SEC=600,TWIN_TTL_SEC=300;function isApiStatus(err,statuses){if(typeof err!="object"||err===null)return!1;let e=err;return e.name==="SekyroApiError"&&typeof e.status=="number"&&statuses.includes(e.status)}function linkOf(o){if(o.returnUrl===void 0&&o.state===void 0)return;let link={};return o.returnUrl!==void 0&&(link.returnUrl=o.returnUrl),o.state!==void 0&&(link.state=o.state),link}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}function personIdOf(d){let id=d.personId;return typeof id=="string"&&id.length>0?canonicalId(id):void 0}function assertUserId(method,userId){if(typeof userId!="string"||userId.length===0)throw new TypeError(`connector.${method}: \`userId\` must be a non-empty string`)}function createConnector(opts){let appIds=[opts?.appId].flat();if(appIds.length===0||appIds.some(id=>typeof id!="string"||id.length===0))throw new SekyroConnectError("invalid_options","`appId` must be a non-empty string or a non-empty array of them");if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroConnectError("invalid_options","`env` must be 'live' or 'sandbox'");if(typeof opts.webhookSecret!="string"||opts.webhookSecret.length===0)throw new SekyroConnectError("invalid_options","`webhookSecret` is required");if(!opts.sekyro||!opts.provider)throw new SekyroConnectError("invalid_options","`sekyro` and `provider` are required");let{sekyro,provider,env}=opts,now=opts.now??Date.now,store=opts.store??memoryStore({now}),ids=Object.freeze([...appIds]),userLock=perKeyLock(),telemetry=connectTelemetry({sekyro,provider,enabled:opts.telemetry!==!1,now});function updateClaim(userId,fn){return typeof provider.update=="function"?provider.update(userId,fn):userLock(userId,async()=>{let out=fn(await provider.readUser(userId));return out.changed&&out.claim&&await provider.writeUser(userId,out.claim),out})}let log=event=>{if(opts.logger)try{opts.logger(event)}catch{}},notifyRevocationUnresolved=event=>{let handler=opts.onRevocationUnresolved;if(typeof handler!="function")return;let failed=()=>log({type:"revocation_handler_failed",subjectId:event.subjectId});queueMicrotask(()=>{try{Promise.resolve(handler(event)).catch(failed)}catch{failed()}})},tokenOptions={appId:[...ids],env,now};opts.issuer!==void 0&&(tokenOptions.issuer=opts.issuer),opts.jwksUrl!==void 0&&(tokenOptions.jwksUrl=opts.jwksUrl),opts.fetch!==void 0&&(tokenOptions.fetch=opts.fetch);async function verifiedFor(token,sessionId,userId){let v;try{v=await(0,import_result_token.verifyResultToken)(token,tokenOptions)}catch(err){let e=err;throw e?.name==="SekyroResultTokenError"&&e.code==="jwks_unavailable"?new SekyroConnectError("unavailable",void 0,err):err}if(canonicalId(v.sessionId)!==canonicalId(sessionId))throw new SekyroConnectError("token_session_mismatch");if(v.externalRef!==void 0&&v.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");return v}async function applyResult(event,userId,result){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind:"result",result},{env,now}));return out.rule==="env_mismatch"?(log({type:"env_mismatch",sessionId:result.sessionId}),{handled:!1,event,reason:"env_mismatch"}):!out.changed||!out.claim?{handled:!0,event,userId,claim:out.claim,rule:out.rule}:(out.claim.subject_id!==void 0&&store.setSubjectUser&&await store.setSubjectUser(out.claim.subject_id,userId),log({type:"write",userId,sessionId:result.sessionId,rule:out.rule}),telemetry.record({type:"claim_written",sessionId:result.sessionId,personId:out.claim.subject_id}),{handled:!0,event,userId,claim:out.claim,rule:out.rule})}async function handleTerminal(event,d,envelopeEnv,remember){if(d.appId===void 0||!ids.includes(d.appId))return{handled:!1,event,reason:"other_app"};let userId=d.externalRef;if(typeof userId!="string"||userId.length===0)return{handled:!1,event,reason:"no_external_ref"};if(d.status==="not_verified")return applyResult(event,userId,fromWebhookData(d,envelopeEnv,now()));let result;if(typeof d.resultToken=="string"&&d.resultToken.length>0){let v=await verifiedFor(d.resultToken,d.sessionId,userId),jti=(0,import_jose.decodeJwt)(d.resultToken).jti;if(typeof jti=="string"&&jti.length>0&&await remember(`jti:${jti}`,JTI_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};result=fromVerifiedResult(v,d)}else{if(opts.requireResultToken===!0)return{handled:!1,event,reason:"result_token_required"};log({type:"result_token_absent",sessionId:d.sessionId}),result=fromWebhookData(d,envelopeEnv,now())}return applyResult(event,userId,result)}async function resolveUsers(kind,subjectId,refs){let clean=list=>Array.isArray(list)?[...new Set(list.filter(r=>typeof r=="string"&&r.length>0))]:[],fromEvent=clean(refs);if(fromEvent.length>0)return{users:fromEvent,fromRefs:!0};if(kind==="revoked"){let fromApi=clean((await sekyro.people.get(subjectId)).externalRefs);if(fromApi.length>0)return{users:fromApi,fromRefs:!0}}let fromStore=await store.getSubjectUser?.(subjectId);return{users:fromStore?[fromStore]:[],fromRefs:!1}}async function handleSubjectGone(event,subjectId,refs){let kind=event.endsWith(".updated")?"revoked":"deleted",{users,fromRefs}=await resolveUsers(kind,subjectId,refs);if(users.length===0)return log({type:"revocation_unresolved",subjectId}),telemetry.record({type:"revocation_unresolved",personId:subjectId}),notifyRevocationUnresolved({subjectId,personId:`per_${subjectId}`,provider:provider.name,reason:kind}),{handled:!1,event,reason:"revocation_unresolved"};let first;for(let userId of users){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind,subjectId,userInExternalRefs:fromRefs},{env,now}));out.changed&&out.claim&&(log({type:"write",userId,rule:out.rule}),telemetry.record({type:"claim_written",personId:subjectId})),first??={claim:out.claim,rule:out.rule}}return{handled:!0,event,userId:users[0],claim:first.claim,rule:first.rule}}async function routeEnvelope(envelope,remember){let event=envelope.event;switch(envelope.event){case"session.verified":case"session.not_verified":return await handleTerminal(envelope.event,envelope.data,envelope.env,remember);case"person.updated":{let d=envelope.data,id=personIdOf(d);return d.status!=="revoked"||id===void 0?{handled:!1,event,reason:"ignored_event"}:await remember(`gone:revoked:${id}`,TWIN_TTL_SEC)?{handled:!1,event,reason:"duplicate_delivery"}:await handleSubjectGone(envelope.event,id,d.externalRefs)}case"person.deleted":{let d=envelope.data,id=personIdOf(d);return id===void 0?{handled:!1,event,reason:"ignored_event"}:await remember(`gone:deleted:${id}`,TWIN_TTL_SEC)?{handled:!1,event,reason:"duplicate_delivery"}:await handleSubjectGone(envelope.event,id,d.externalRefs)}default:return{handled:!1,event,reason:"ignored_event"}}}async function handleEnvelope(envelope){let event=envelope.event,canForget=typeof store.forget=="function",recorded=[],deferred=[],remember=async(id,ttl)=>{if(!canForget)return deferred.push([id,ttl]),!1;let dup=await store.seen(id,ttl);return dup||recorded.push(id),dup};if(await remember(`wh:${envelope.id}`,DEDUP_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};let out;try{out=await routeEnvelope(envelope,remember)}catch(err){for(let id of recorded)await store.forget(id).catch(()=>{});throw err}for(let[id,ttl]of deferred)await store.seen(id,ttl);return out}async function createVia(userId,mode,o){assertUserId(mode==="recheck"?"recheck":"stepUp",userId);let input={mode};mode==="step_up"&&o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes);let link=linkOf(o);return link&&(input.link=link),sekyro.people.createSession({externalRef:userId},input)}return{env,appIds:ids,async webhook(rawBody,headers){let envelope=(0,import_webhooks.verifyWebhook)(rawBody,(0,import_webhooks.signatureFromHeaders)(headers),opts.webhookSecret,{now}),out=await handleEnvelope(envelope);if(!out.handled&&out.reason!=="env_mismatch"&&out.reason!=="revocation_unresolved"){let data=envelope.data,skip={type:"skip",reason:out.reason};typeof data.sessionId=="string"&&(skip.sessionId=data.sessionId);let person=personIdOf(data);person!==void 0&&(skip.subjectId=person),log(skip)}return out},async sync(userId,sessionId){assertUserId("sync",userId);let s=await sekyro.sessions.get(sessionId);if(s.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");if(s.status==="not_verified")return{claim:parseClaim(await provider.readUser(userId)),rule:"not_verified"};if(s.status!=="verified")throw new SekyroConnectError("session_not_terminal");let{token}=await sekyro.sessions.resultToken(sessionId),v=await verifiedFor(token,sessionId,userId),out=await applyResult("session.verified",userId,fromVerifiedResult(v,s));return out.handled?{claim:out.claim,rule:out.rule}:{claim:null,rule:"env_mismatch"}},async start(userId,o={}){assertUserId("start",userId);let input={};o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes),input.person={externalRef:userId};let link=linkOf(o);return link&&(input.link=link),sekyro.sessions.create(input)},recheck(userId,o={}){return createVia(userId,"recheck",o)},stepUp(userId,o){return createVia(userId,"step_up",o)},async userDeleted(userId){assertUserId("userDeleted",userId);let policy=opts.onUserDeleted??"ignore";if(policy==="ignore")return{policy,subjects:0};let people=[];for await(let p of sekyro.people.iterate({externalRef:userId}))Array.isArray(p?.externalRefs)&&p.externalRefs.includes(userId)&&people.push(p);for(let p of people)try{policy==="revoke"?await sekyro.people.revoke(p.id):await sekyro.people.delete(p.id)}catch(err){if(!isApiStatus(err,[404,409]))throw err}return{policy,subjects:people.length}},async claimOf(userId){return parseClaim(await provider.readUser(userId))},async clearFlag(userId,flag){let out=await updateClaim(userId,previous=>{let claim=parseClaim(previous);return!claim||claim.v>1||!claim.flags?.includes(flag)?{claim,changed:!1,rule:"no_change"}:{claim:parseClaim({...claim,flags:claim.flags.filter(f=>f!==flag)}),changed:!0,rule:"no_change"}});return out.changed&&log({type:"flag_cleared",userId,flag}),out.claim},gate(tokenClaims,policy){return evaluateGate(provider.readClaimFromToken(tokenClaims),{...policy,env:policy.env??env},Math.floor(now()/1e3))}}}0&&(module.exports={CLAIM_VERSION,SekyroConnectError,createConnector,evaluateGate,memoryStore,mergeClaim,parseClaim});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var connect_exports={};__export(connect_exports,{CLAIM_VERSION:()=>CLAIM_VERSION,SekyroConnectError:()=>SekyroConnectError,createConnector:()=>createConnector,evaluateGate:()=>evaluateGate,memoryStore:()=>memoryStore,mergeClaim:()=>mergeClaim,parseClaim:()=>parseClaim});module.exports=__toCommonJS(connect_exports);var ASSURANCE_ORDER=["device_only","contact_email","contact_phone","unbound_identity","live_only","live_unique","supplied_biometric","document_biometric","eid_authenticated","chip_biometric","registry_biometric"];function standingOf(assurance){return ASSURANCE_ORDER.indexOf(assurance)}var CLAIM_VERSION=2,KNOWN_FLAGS=["face_mismatch","duplicate","revoked"],AGE_METHODS=["estimated","document","chip","registry","eid"];function ageProofOf(over,method){if(!(typeof over!="number"||!Number.isInteger(over)||over<=0)&&!(typeof method!="string"||!AGE_METHODS.includes(method)))return{over,method}}var ageRank=a=>a.method==="estimated"?0:1;function strongerAge(stored,next){if(!stored)return next;if(!next)return stored;let r=ageRank(next)-ageRank(stored);return r!==0?r>0?next:stored:next.over>stored.over?next:stored}var sameAge=(a,b)=>a?.over===b?.over&&a?.method===b?.method;function canonicalId(id){return id.replace(/^(ses|per)_/,"")}function isRecord(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function isFiniteNumber(v){return typeof v=="number"&&Number.isFinite(v)}function build(c){let out={v:CLAIM_VERSION,level:c.level,assurance:c.assurance,verified_at:c.verified_at};c.rechecked_at!==void 0&&(out.rechecked_at=c.rechecked_at),out.session_id=c.session_id,c.subject_id!==void 0&&(out.subject_id=canonicalId(c.subject_id)),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);flags.size>0&&(out.flags=[...flags].sort());let age=ageProofOf(c.age_over,c.age_method);return age&&(out.age_over=age.over,out.age_method=age.method),out}function ageFields(age){return{age_over:age?.over,age_method:age?.method}}function parseClaim(value){let v=value;if(typeof v=="string")try{v=JSON.parse(v)}catch{return null}return!isRecord(v)||!isFiniteNumber(v.v)?null:v.v>CLAIM_VERSION?v:v.v!==CLAIM_VERSION||v.level!==0&&v.level!==1&&v.level!==2&&v.level!==3||typeof v.assurance!="string"||!isFiniteNumber(v.verified_at)||typeof v.session_id!="string"||v.env!=="live"&&v.env!=="sandbox"?null:build({level:v.level,assurance:v.assurance,verified_at:v.verified_at,rechecked_at:isFiniteNumber(v.rechecked_at)?v.rechecked_at:void 0,session_id:v.session_id,subject_id:typeof v.subject_id=="string"?v.subject_id:void 0,env:v.env,flags:Array.isArray(v.flags)?v.flags:void 0,age_over:v.age_over,age_method:v.age_method})}function toUnix(isoTime,now){let ms=Date.parse(isoTime);return Math.floor((Number.isFinite(ms)?ms:now())/1e3)}var same=(claim,rule)=>({claim,changed:!1,rule}),wrote=(claim,rule)=>({claim,changed:!0,rule});function mergeClaim(previous,event,opts){let now=opts.now??Date.now,prev=parseClaim(previous);if(prev&&prev.v>CLAIM_VERSION)return same(prev,"unsupported_version");if(event.kind==="revoked"||event.kind==="deleted"){if(!prev)return same(null,"no_change");if(!(prev.subject_id===void 0?event.userInExternalRefs===!0:prev.subject_id===canonicalId(event.subjectId)))return same(prev,"subject_mismatch");if(prev.level===0&&prev.flags?.includes("revoked"))return same(prev,"no_change");let{rechecked_at:_cleared,age_over:_over,age_method:_method,...kept}=prev;return wrote(build({...kept,level:0,subject_id:event.subjectId,flags:["revoked"]}),"revoked")}let r=event.result;if(r.env!==opts.env)return same(prev,"env_mismatch");let t=toUnix(r.verifiedAt,now);if(prev&&t<prev.verified_at)return same(prev,"stale_ignored");let revokedPrev=prev?.flags?.includes("revoked")===!0;if(prev&&revokedPrev&&(r.subjectId===void 0||canonicalId(r.subjectId)===prev.subject_id))return same(prev,"revoked_ignored");if(r.status==="not_verified"&&r.reason==="rejected"&&r.subjectConflict===!0)return!prev||prev.flags?.includes("face_mismatch")?same(prev,"no_change"):wrote(build({...prev,flags:[...prev.flags??[],"face_mismatch"]}),"face_mismatch");if(r.status!=="verified"||r.level===null||r.level===0)return same(prev,"not_verified");let level=r.level,assurance=r.assurance??"none",duplicate=r.duplicates===!0?["duplicate"]:[],nextAge=r.age?ageProofOf(r.age.over,r.age.method):void 0;if(!prev)return wrote(build({level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId,env:r.env,flags:duplicate,...ageFields(nextAge)}),"created");let prevAge=ageProofOf(prev.age_over,prev.age_method),otherPerson=prev.subject_id!==void 0&&r.subjectId!==void 0&&canonicalId(r.subjectId)!==prev.subject_id,mergedAge=otherPerson?prevAge:strongerAge(prevAge,nextAge),stronger=level>prev.level||level===prev.level&&standingOf(assurance)>standingOf(prev.assurance);if(!revokedPrev&&(r.reuseMode==="recheck"||r.returning===!0&&!stronger))return prev.rechecked_at!==void 0&&t<=prev.rechecked_at?same(prev,t<prev.rechecked_at?"stale_ignored":"no_change"):wrote(build({...prev,rechecked_at:t,subject_id:prev.subject_id??r.subjectId,...ageFields(mergedAge)}),"rechecked");if(stronger){let kept=(prev.flags??[]).filter(f=>f!=="face_mismatch"&&f!=="revoked");return wrote(build({...prev,level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId??prev.subject_id,flags:[...kept,...duplicate],...ageFields(otherPerson?nextAge:mergedAge)}),"raised")}return level===prev.level&&standingOf(assurance)===standingOf(prev.assurance)&&t>prev.verified_at?wrote(build({...prev,assurance,verified_at:t,session_id:r.sessionId,subject_id:prev.subject_id??r.subjectId,flags:[...prev.flags??[],...duplicate],...ageFields(mergedAge)}),"renewed"):sameAge(mergedAge,prevAge)?same(prev,"no_change"):wrote(build({...prev,subject_id:prev.subject_id??r.subjectId,...ageFields(mergedAge)}),"age_proved")}var DEFAULT_DENY_FLAGS=["revoked","face_mismatch"],fail=(reason,action,claim)=>({ok:!1,reason,action,claim});function evaluateGate(claim,policy,nowSec=Math.floor(Date.now()/1e3)){let parsed=parseClaim(claim);if(!parsed)return fail("no_claim","verify",null);if(parsed.v>CLAIM_VERSION)return fail("unsupported_version","verify",parsed);if(policy.env!==void 0&&parsed.env!==policy.env)return fail("wrong_env","verify",parsed);let deny=policy.denyFlags??DEFAULT_DENY_FLAGS;if(parsed.flags?.some(f=>deny.includes(f)))return fail("flagged","block",parsed);if(parsed.level<policy.level)return fail("level_too_low",parsed.level>=2?"step_up":"verify",parsed);if(policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400)return fail("stale","recheck",parsed);if(policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60)return fail("recheck_stale","recheck",parsed);if(policy.assurance&&!policy.assurance.includes(parsed.assurance))return fail("assurance_not_allowed","step_up",parsed);if(policy.minAge!==void 0){if(parsed.age_over===void 0||parsed.age_over<policy.minAge)return fail("age_not_proven","verify",parsed);if(policy.ageMethods&&(parsed.age_method===void 0||!policy.ageMethods.includes(parsed.age_method)))return fail("age_method_not_allowed","step_up",parsed)}return{ok:!0,claim:parsed}}var import_jose=require("jose"),import_result_token=require("@sekyro/node"),import_webhooks=require("@sekyro/node");var MESSAGES={token_session_mismatch:"The result token is for another session than the webhook",external_ref_mismatch:"The session belongs to another user",session_not_terminal:"The session has not finished yet",invalid_options:"Invalid connector options",unavailable:"The Sekyro AI public key set could not be fetched; try again"},SekyroConnectError=class extends Error{name="SekyroConnectError";code;constructor(code,message=MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}};var hasDuplicate=signals=>Array.isArray(signals)&&signals.some(s=>s!==null&&typeof s=="object"&&s.kind==="duplicate_identity");function factsOf(d,tokenSignals){let out={};return d.returning===!0&&(out.returning=!0),d.personConflict===!0&&(out.subjectConflict=!0),(hasDuplicate(d.signals)||hasDuplicate(tokenSignals))&&(out.duplicates=!0),out}function fromVerifiedResult(v,d){let out={sessionId:v.sessionId,status:v.status,level:v.level,assurance:v.assurance,verifiedAt:v.verifiedAt,env:v.env,...factsOf(d,v.signals)};return v.personId!==void 0&&(out.subjectId=canonicalId(v.personId)),v.reuseMode!==void 0&&(out.reuseMode=v.reuseMode),v.age!==void 0&&(out.age={over:v.age.over,method:v.age.method}),out}function fromWebhookData(d,env,nowMs){let out={sessionId:d.sessionId,status:d.status,level:d.level??null,assurance:d.assurance??null,verifiedAt:d.verifiedAt??new Date(nowMs).toISOString(),env,...factsOf(d)},person=d.personId;return typeof person=="string"&&person.length>0&&(out.subjectId=canonicalId(person)),d.reuseMode!==void 0&&(out.reuseMode=d.reuseMode),d.status==="not_verified"?(out.reason=d.reason,out):(d.age!==void 0&&d.age!==null&&(out.age={over:d.age.over,method:d.age.method}),out)}function memoryStore(opts={}){let now=opts.now??Date.now,ids=new Map,subjects=new Map,evict=t=>{for(let[id,expiresAt]of ids)expiresAt<=t&&ids.delete(id)};return{async seen(id,ttlSec){let t=now();return evict(t),ids.has(id)?!0:(ids.set(id,t+ttlSec*1e3),!1)},async forget(id){ids.delete(id)},async setSubjectUser(subjectId,userId){subjects.delete(subjectId),subjects.set(subjectId,userId),subjects.size>1e5&&subjects.delete(subjects.keys().next().value)},async getSubjectUser(subjectId){return subjects.get(subjectId)},size(){return evict(now()),ids.size}}}var KNOWN_CONNECTOR_PROVIDERS=new Set(["auth0","clerk","firebase","keycloak","supabase","zitadel"]),CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),TELEMETRY_TIMEOUT_MS=2e3,TELEMETRY_BATCH_MAX=50,QUEUE_MAX=500;function hooksOf(sekyro){let h=sekyro[CONNECT_TELEMETRY];return h&&typeof h.setConnector=="function"&&typeof h.postEvents=="function"?h:void 0}var OFF={record(){}};function connectTelemetry(opts){let hooks=hooksOf(opts.sekyro);if(!hooks)return OFF;let name=opts.provider.name;if(!opts.enabled||!KNOWN_CONNECTOR_PROVIDERS.has(name))return opts.enabled||hooks.setConnector(null),OFF;hooks.setConnector({provider:name,version:opts.provider.version??"unknown"});let queue=[],scheduled=!1,flush=()=>{for(scheduled=!1;queue.length>0;){let batch=queue.splice(0,TELEMETRY_BATCH_MAX);hooks.postEvents(batch,TELEMETRY_TIMEOUT_MS).catch(()=>{})}};return{record(event){if(queue.length>=QUEUE_MAX)return;let e={type:event.type,provider:name,at:new Date(opts.now()).toISOString()};if(typeof event.sessionId=="string"&&event.sessionId.length>0&&(e.sessionId=event.sessionId),typeof event.personId=="string"&&event.personId.length>0&&(e.personId=`per_${canonicalId(event.personId)}`),queue.push(e),scheduled)return;scheduled=!0,setTimeout(flush,0).unref?.()}}}var DEDUP_TTL_SEC=24*3600,JTI_TTL_SEC=600,TWIN_TTL_SEC=300;function isApiStatus(err,statuses){if(typeof err!="object"||err===null)return!1;let e=err;return e.name==="SekyroApiError"&&typeof e.status=="number"&&statuses.includes(e.status)}function linkOf(o){if(o.returnUrl===void 0&&o.state===void 0)return;let link={};return o.returnUrl!==void 0&&(link.returnUrl=o.returnUrl),o.state!==void 0&&(link.state=o.state),link}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}function personIdOf(d){let id=d.personId;return typeof id=="string"&&id.length>0?canonicalId(id):void 0}function assertUserId(method,userId){if(typeof userId!="string"||userId.length===0)throw new TypeError(`connector.${method}: \`userId\` must be a non-empty string`)}function createConnector(opts){let appIds=[opts?.appId].flat();if(appIds.length===0||appIds.some(id=>typeof id!="string"||id.length===0))throw new SekyroConnectError("invalid_options","`appId` must be a non-empty string or a non-empty array of them");if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroConnectError("invalid_options","`env` must be 'live' or 'sandbox'");if(typeof opts.webhookSecret!="string"||opts.webhookSecret.length===0)throw new SekyroConnectError("invalid_options","`webhookSecret` is required");if(!opts.sekyro||!opts.provider)throw new SekyroConnectError("invalid_options","`sekyro` and `provider` are required");let{sekyro,provider,env}=opts,now=opts.now??Date.now,store=opts.store??memoryStore({now}),ids=Object.freeze([...appIds]),userLock=perKeyLock(),telemetry=connectTelemetry({sekyro,provider,enabled:opts.telemetry!==!1,now});function updateClaim(userId,fn){return typeof provider.update=="function"?provider.update(userId,fn):userLock(userId,async()=>{let out=fn(await provider.readUser(userId));return out.changed&&out.claim&&await provider.writeUser(userId,out.claim),out})}let log=event=>{if(opts.logger)try{opts.logger(event)}catch{}},notifyRevocationUnresolved=event=>{let handler=opts.onRevocationUnresolved;if(typeof handler!="function")return;let failed=()=>log({type:"revocation_handler_failed",subjectId:event.subjectId});queueMicrotask(()=>{try{Promise.resolve(handler(event)).catch(failed)}catch{failed()}})},tokenOptions={appId:[...ids],env,now};opts.issuer!==void 0&&(tokenOptions.issuer=opts.issuer),opts.jwksUrl!==void 0&&(tokenOptions.jwksUrl=opts.jwksUrl),opts.fetch!==void 0&&(tokenOptions.fetch=opts.fetch);async function verifiedFor(token,sessionId,userId){let v;try{v=await(0,import_result_token.verifyResultToken)(token,tokenOptions)}catch(err){let e=err;throw e?.name==="SekyroResultTokenError"&&e.code==="jwks_unavailable"?new SekyroConnectError("unavailable",void 0,err):err}if(canonicalId(v.sessionId)!==canonicalId(sessionId))throw new SekyroConnectError("token_session_mismatch");if(v.externalRef!==void 0&&v.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");return v}async function applyResult(event,userId,result){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind:"result",result},{env,now}));return out.rule==="env_mismatch"?(log({type:"env_mismatch",sessionId:result.sessionId}),{handled:!1,event,reason:"env_mismatch"}):!out.changed||!out.claim?{handled:!0,event,userId,claim:out.claim,rule:out.rule}:(out.claim.subject_id!==void 0&&store.setSubjectUser&&await store.setSubjectUser(out.claim.subject_id,userId),log({type:"write",userId,sessionId:result.sessionId,rule:out.rule}),telemetry.record({type:"claim_written",sessionId:result.sessionId,personId:out.claim.subject_id}),{handled:!0,event,userId,claim:out.claim,rule:out.rule})}async function handleTerminal(event,d,envelopeEnv,remember){if(d.appId===void 0||!ids.includes(d.appId))return{handled:!1,event,reason:"other_app"};let userId=d.externalRef;if(typeof userId!="string"||userId.length===0)return{handled:!1,event,reason:"no_external_ref"};if(d.status==="not_verified")return applyResult(event,userId,fromWebhookData(d,envelopeEnv,now()));let result;if(typeof d.resultToken=="string"&&d.resultToken.length>0){let v=await verifiedFor(d.resultToken,d.sessionId,userId),jti=(0,import_jose.decodeJwt)(d.resultToken).jti;if(typeof jti=="string"&&jti.length>0&&await remember(`jti:${jti}`,JTI_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};result=fromVerifiedResult(v,d)}else{if(opts.requireResultToken===!0)return{handled:!1,event,reason:"result_token_required"};log({type:"result_token_absent",sessionId:d.sessionId}),result=fromWebhookData(d,envelopeEnv,now())}return applyResult(event,userId,result)}async function resolveUsers(kind,subjectId,refs){let clean=list=>Array.isArray(list)?[...new Set(list.filter(r=>typeof r=="string"&&r.length>0))]:[],fromEvent=clean(refs);if(fromEvent.length>0)return{users:fromEvent,fromRefs:!0};if(kind==="revoked"){let fromApi=clean((await sekyro.people.get(subjectId)).externalRefs);if(fromApi.length>0)return{users:fromApi,fromRefs:!0}}let fromStore=await store.getSubjectUser?.(subjectId);return{users:fromStore?[fromStore]:[],fromRefs:!1}}async function handleSubjectGone(event,subjectId,refs){let kind=event.endsWith(".updated")?"revoked":"deleted",{users,fromRefs}=await resolveUsers(kind,subjectId,refs);if(users.length===0)return log({type:"revocation_unresolved",subjectId}),telemetry.record({type:"revocation_unresolved",personId:subjectId}),notifyRevocationUnresolved({subjectId,personId:`per_${subjectId}`,provider:provider.name,reason:kind}),{handled:!1,event,reason:"revocation_unresolved"};let first;for(let userId of users){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind,subjectId,userInExternalRefs:fromRefs},{env,now}));out.changed&&out.claim&&(log({type:"write",userId,rule:out.rule}),telemetry.record({type:"claim_written",personId:subjectId})),first??={claim:out.claim,rule:out.rule}}return{handled:!0,event,userId:users[0],claim:first.claim,rule:first.rule}}async function routeEnvelope(envelope,remember){let event=envelope.event;switch(envelope.event){case"session.verified":case"session.not_verified":return await handleTerminal(envelope.event,envelope.data,envelope.env,remember);case"person.updated":{let d=envelope.data,id=personIdOf(d);return d.status!=="revoked"||id===void 0?{handled:!1,event,reason:"ignored_event"}:await remember(`gone:revoked:${id}`,TWIN_TTL_SEC)?{handled:!1,event,reason:"duplicate_delivery"}:await handleSubjectGone(envelope.event,id,d.externalRefs)}case"person.deleted":{let d=envelope.data,id=personIdOf(d);return id===void 0?{handled:!1,event,reason:"ignored_event"}:await remember(`gone:deleted:${id}`,TWIN_TTL_SEC)?{handled:!1,event,reason:"duplicate_delivery"}:await handleSubjectGone(envelope.event,id,d.externalRefs)}default:return{handled:!1,event,reason:"ignored_event"}}}async function handleEnvelope(envelope){let event=envelope.event,canForget=typeof store.forget=="function",recorded=[],deferred=[],remember=async(id,ttl)=>{if(!canForget)return deferred.push([id,ttl]),!1;let dup=await store.seen(id,ttl);return dup||recorded.push(id),dup};if(await remember(`wh:${envelope.id}`,DEDUP_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};let out;try{out=await routeEnvelope(envelope,remember)}catch(err){for(let id of recorded)await store.forget(id).catch(()=>{});throw err}for(let[id,ttl]of deferred)await store.seen(id,ttl);return out}async function createVia(userId,mode,o){assertUserId(mode==="recheck"?"recheck":"stepUp",userId);let input={mode};mode==="step_up"&&o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes);let link=linkOf(o);return link&&(input.link=link),sekyro.people.createSession({externalRef:userId},input)}return{env,appIds:ids,async webhook(rawBody,headers){let envelope=(0,import_webhooks.verifyWebhook)(rawBody,(0,import_webhooks.signatureFromHeaders)(headers),opts.webhookSecret,{now}),out=await handleEnvelope(envelope);if(!out.handled&&out.reason!=="env_mismatch"&&out.reason!=="revocation_unresolved"){let data=envelope.data,skip={type:"skip",reason:out.reason};typeof data.sessionId=="string"&&(skip.sessionId=data.sessionId);let person=personIdOf(data);person!==void 0&&(skip.subjectId=person),log(skip)}return out},async sync(userId,sessionId){assertUserId("sync",userId);let s=await sekyro.sessions.get(sessionId);if(s.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");if(s.status==="not_verified")return{claim:parseClaim(await provider.readUser(userId)),rule:"not_verified"};if(s.status!=="verified")throw new SekyroConnectError("session_not_terminal");let{token}=await sekyro.sessions.resultToken(sessionId),v=await verifiedFor(token,sessionId,userId),out=await applyResult("session.verified",userId,fromVerifiedResult(v,s));return out.handled?{claim:out.claim,rule:out.rule}:{claim:null,rule:"env_mismatch"}},async start(userId,o={}){assertUserId("start",userId);let input={};o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes),input.person={externalRef:userId};let link=linkOf(o);return link&&(input.link=link),sekyro.sessions.create(input)},recheck(userId,o={}){return createVia(userId,"recheck",o)},stepUp(userId,o){return createVia(userId,"step_up",o)},async userDeleted(userId){assertUserId("userDeleted",userId);let policy=opts.onUserDeleted??"ignore";if(policy==="ignore")return{policy,subjects:0};let people=[];for await(let p of sekyro.people.iterate({externalRef:userId}))Array.isArray(p?.externalRefs)&&p.externalRefs.includes(userId)&&people.push(p);for(let p of people)try{policy==="revoke"?await sekyro.people.revoke(p.id):await sekyro.people.delete(p.id)}catch(err){if(!isApiStatus(err,[404,409]))throw err}return{policy,subjects:people.length}},async claimOf(userId){return parseClaim(await provider.readUser(userId))},async clearFlag(userId,flag){let out=await updateClaim(userId,previous=>{let claim=parseClaim(previous);return!claim||claim.v>CLAIM_VERSION||!claim.flags?.includes(flag)?{claim,changed:!1,rule:"no_change"}:{claim:parseClaim({...claim,flags:claim.flags.filter(f=>f!==flag)}),changed:!0,rule:"no_change"}});return out.changed&&log({type:"flag_cleared",userId,flag}),out.claim},gate(tokenClaims,policy){return evaluateGate(provider.readClaimFromToken(tokenClaims),{...policy,env:policy.env??env},Math.floor(now()/1e3))}}}0&&(module.exports={CLAIM_VERSION,SekyroConnectError,createConnector,evaluateGate,memoryStore,mergeClaim,parseClaim});
@@ -1,5 +1,5 @@
1
- export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-CyNFdiLv.cjs';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-BSzMfacG.cjs';
1
+ export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-BoksCP5p.cjs';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-C5lyl8iQ.cjs';
3
3
 
4
4
  /**
5
5
  * Why a connector refused to act:
@@ -1,5 +1,5 @@
1
- export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-D0CDGAOJ.js';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-BSzMfacG.js';
1
+ export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-CluvSk8L.js';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-C5lyl8iQ.js';
3
3
 
4
4
  /**
5
5
  * Why a connector refused to act: