@sekyro/node 1.0.0-rc.26 → 1.0.0-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @sekyro/node
2
2
 
3
+ ## 1.0.0-rc.28
4
+
5
+ ### Patch Changes
6
+
7
+ - dfe2f1e: The doc comments of `blocks.create` and `signals` no longer list `403` errors the API does not answer: a block acts as soon as it exists, and Signals are available in every environment.
8
+
9
+ ## 1.0.0-rc.27
10
+
11
+ ### Minor Changes
12
+
13
+ - 4899a37: `VerificationUnit` gains `contact_verification`: the unit of a session that only verified a contact (an email or phone code was sent, or the device check ran), on the session, the result token and `session.verified`. `usage.threshold_reached` is typed as `IncludedVerificationsThresholdReachedEventData` (`included_verifications_80` and `included_verifications_100`, with `usedPercent`, `remaining` and `period`, no amount or currency) or `UsageLimitReachedEventData` for every other alert; the tier fields `confirmed` and `overage` and the `overage` threshold are gone.
14
+ - 95d5af8: Flows: `ServiceId` names the Form step (`form`), and `FlowOverrides.services.form` accepts `"off"` to turn the step off for one session.
15
+
3
16
  ## 1.0.0-rc.26
4
17
 
5
18
  ### Minor Changes
@@ -76,8 +76,13 @@ type VerificationLevel = 0 | 1 | 2 | 3;
76
76
  * @public
77
77
  */
78
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";
79
- /** The one billing unit a finished session consumed. @public */
80
- type VerificationUnit = "human_verification" | "identity_verification";
79
+ /**
80
+ * The one billing unit a finished session consumed: `identity_verification` when an identity
81
+ * source ran, else `human_verification` when liveness ran, else `contact_verification` when only
82
+ * contact steps did work (an email or phone code was sent, or the device check ran).
83
+ * @public
84
+ */
85
+ type VerificationUnit = "contact_verification" | "human_verification" | "identity_verification";
81
86
  /** The lowest and highest {@link VerificationLevel} the session's flow can reach. @public */
82
87
  interface LevelTarget {
83
88
  min: VerificationLevel;
@@ -800,7 +805,7 @@ type ProfileDocumentType = "carte_identite" | "passport" | "residence_permit";
800
805
  * its `confirmDetails` setting (see {@link OverridableServiceId}).
801
806
  * @public
802
807
  */
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";
808
+ 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" | "form";
804
809
  /**
805
810
  * The services a Sekyro flow is built from, as {@link FlowOverrides.services}
806
811
  * names them: every {@link ServiceId} except `summary_confirm` (the
@@ -1032,6 +1037,12 @@ interface FlowServiceSettings {
1032
1037
  /** Keep and show the estimated age ({@link AgeResult.estimate}) on the API session and webhooks. Default `false`. */
1033
1038
  showEstimatedAge?: boolean;
1034
1039
  };
1040
+ /**
1041
+ * The Form step: a session can only turn it off (`services: { form: "off" }`);
1042
+ * its questions are not overridable. Prefill its answers with
1043
+ * {@link CreateSessionInput.answers}.
1044
+ */
1045
+ form: never;
1035
1046
  }
1036
1047
  /** One accepted kind of a proof of address rule and its maximum age (30 to 730 days). @public */
1037
1048
  interface PoaRuleKind {
@@ -2757,26 +2768,50 @@ interface SessionLinkExpiry {
2757
2768
  expiresAt: string;
2758
2769
  }
2759
2770
  /**
2760
- * `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
2761
- * plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
2762
- * tier, or the alert, e.g. `credit_80`, `usage_100_paid`, `spend_cap_reached`.
2771
+ * `usage.threshold_reached` for the monthly included verifications of a paid plan: 80 percent
2772
+ * of this month's included verifications are used (`included_verifications_80`) or all of them
2773
+ * (`included_verifications_100`). Sent once per kind and billing month. No amount, no currency.
2774
+ * @public
2775
+ */
2776
+ interface IncludedVerificationsThresholdReachedEventData {
2777
+ kind: "included_verifications_80" | "included_verifications_100";
2778
+ threshold: 80 | 100;
2779
+ /** The share of this month's included verifications used, in whole percent (0 to 100). */
2780
+ usedPercent: number;
2781
+ /** Up to how many human or identity verifications are still included this month, any mix. */
2782
+ remaining: {
2783
+ human: number;
2784
+ identity: number;
2785
+ };
2786
+ /** The billing month the included verifications belong to (ISO 8601). */
2787
+ period: {
2788
+ from: string;
2789
+ to: string;
2790
+ };
2791
+ }
2792
+ /**
2793
+ * `usage.threshold_reached` for every other alert: a balance, starting credit, spend or email
2794
+ * allowance threshold, e.g. `credit_80`, `spend_cap_reached`, `email_allowance_80`.
2763
2795
  * @public
2764
2796
  */
2765
- interface UsageThresholdReachedEventData {
2797
+ interface UsageLimitReachedEventData {
2766
2798
  kind: string;
2767
2799
  /** The verification unit, on per-unit alerts. */
2768
- unit?: "human_verification" | "identity_verification";
2769
- /** Percent of the limit (80, 100), or `overage` for the first verification beyond a tier. */
2770
- threshold?: number | "overage";
2800
+ unit?: VerificationUnit;
2801
+ /** Percent of the limit (80, 100). */
2802
+ threshold?: number;
2771
2803
  used?: number;
2772
2804
  limit?: number;
2773
2805
  /** UTC month, `YYYY-MM`. */
2774
2806
  period?: string;
2775
- /** Tier alerts: verifications that reached a result this month. */
2776
- confirmed?: number;
2777
- /** Tier alerts: verifications beyond the tier this month. */
2778
- overage?: number;
2779
2807
  }
2808
+ /**
2809
+ * `usage.threshold_reached`: a threshold of the organization's plan was reached (sent once
2810
+ * per threshold and period). The included verifications alerts carry `usedPercent` and
2811
+ * `remaining`, so `"remaining" in data` tells them apart.
2812
+ * @public
2813
+ */
2814
+ type UsageThresholdReachedEventData = IncludedVerificationsThresholdReachedEventData | UsageLimitReachedEventData;
2780
2815
  /**
2781
2816
  * `data` of `session.retake_requested`: a reviewer sent the session back for a new capture of
2782
2817
  * one step. The session is open again until `expiresAt`.
@@ -3122,9 +3157,9 @@ declare class BlocksApi {
3122
3157
  /**
3123
3158
  * `POST /blocks`: blocks the key, or answers the active block already on it. `kind: "person"`
3124
3159
  * blocks each ID number of the person and answers a list. A shared device answers
3125
- * `409 device_shared` with `details.people` unless `force: true`. `403 blocks_disabled` while blocks
3126
- * are turned off. The API requires an idempotency key: one is generated when you pass none, so
3127
- * pass your own to make a retry of the same call safe.
3160
+ * `409 device_shared` with `details.people` unless `force: true`. A block acts as soon as it
3161
+ * exists. The API requires an idempotency key: one is generated when you pass none, so pass your
3162
+ * own to make a retry of the same call safe.
3128
3163
  */
3129
3164
  create(input: CreateBlockInput & {
3130
3165
  kind: "person";
@@ -3146,9 +3181,8 @@ declare class BlocksApi {
3146
3181
  /**
3147
3182
  * Findings: sessions of this environment that share a key and met a pattern
3148
3183
  * ({@link Signal}). Exposed as {@link Sekyro.signals}. Reading needs the
3149
- * `signals:read` scope, {@link SignalsApi.update} `signals:write`. Every call
3150
- * answers `403 signals_unavailable` while Signals are not available in the
3151
- * environment. Exported as a TYPE only.
3184
+ * `signals:read` scope, {@link SignalsApi.update} `signals:write`. Exported as
3185
+ * a TYPE only.
3152
3186
  * @public
3153
3187
  */
3154
3188
  declare class SignalsApi {
@@ -3291,4 +3325,4 @@ declare class Sekyro {
3291
3325
  readiness(): Promise<ReadinessReport>;
3292
3326
  }
3293
3327
 
3294
- export { type EligibilityReason 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 Declared as K, type Locale as L, type DeclaredAddress as M, type DeclaredAnswer as N, type DeclaredConsent as O, type DeclaredMismatch as P, type DeepPartial as Q, type ReviewReason as R, type SessionReason as S, type DeletedPerson as T, type DeliverOptions as U, type VerificationLevel as V, type WebhookEventType as W, type Device as X, DevicesApi as Y, type DocumentSubstitutionSettings as Z, type EidResult as _, Sekyro as a, type ResultTokenResponse as a$, type ExtendLinkInput as a0, type FlowOverridableSettings as a1, type FlowOverrides as a2, type FlowServiceSettings as a3, type FlowSummary as a4, FlowsApi as a5, type FormAnswerValue as a6, type FormQuestionType as a7, type FraudReason as a8, type FraudResponse as a9, type OverridableServiceId as aA, type Page as aB, PeopleApi as aC, type Person as aD, type PersonAddressInput as aE, type PersonBirthPlaceInput as aF, type PersonDeletedEventData as aG, type PersonDocumentInput as aH, type PersonEnrolledEventData as aI, type PersonRef as aJ, type PersonSession as aK, type PersonSessionInput as aL, type PersonSessionTarget as aM, type PersonUpdatedEventData as aN, type PoaDocumentKind as aO, type PoaReason as aP, type PoaRule as aQ, type PoaRuleKind as aR, type PoaRules as aS, type PortraitReportEntry as aT, type PriorReviewReason as aU, type ProbeBindingReason as aV, type ProbeQuality as aW, type ProfileDocumentType as aX, type ReadinessProtection as aY, type ReadinessReport as aZ, type RequestOptions as a_, type IdNumberReason as aa, type Identity as ab, type IdentityAddress as ac, type IdentityBirthPlace as ad, type IdentityDocument as ae, type IdentityIdNumber as af, type IdentityMethod as ag, type IdentityName as ah, type IdentityProofOfAddress as ai, type IdentityScalarKey as aj, type IdentitySource as ak, type IdentitySources as al, type LevelTarget as am, type LiftBlockInput as an, type ListBlocksQuery as ao, type ListPeopleQuery as ap, type ListScreeningsQuery as aq, type ListSessionsQuery as ar, type ListSignalsQuery as as, type MatchReason as at, type MediaBytes as au, type MediaBytesOptions as av, type MediaItem as aw, type MediaKind as ax, type MediaList as ay, type NameForm as az, type ServiceId as b, type VerifiedContacts as b$, type ReviewOutcomeReason as b0, type RevokePersonInput as b1, type SandboxSimulatedReason as b2, type SandboxSimulation as b3, type ScreenPersonInput as b4, type Screening as b5, type ScreeningHit as b6, type ScreeningHitSummary as b7, type ScreeningList as b8, type ScreeningStatus as b9, type SessionStepAttempts as bA, type SessionStepBand as bB, type SessionStepDecision as bC, type SessionStepDocument as bD, type SessionStepPortrait as bE, SessionTestApi as bF, type SessionVerifiedEventData as bG, SessionsApi as bH, type Signal as bI, type SignalEventData as bJ, type SignalEvidence as bK, type SignalGrade as bL, type SignalKeyKind as bM, type SignalKind as bN, type SignalSeverity as bO, type SignalStatus as bP, SignalsApi as bQ, type SimulateSessionInput as bR, type StepResult as bS, type SubjectAssurance as bT, type SubjectIdNumber as bU, type SubjectName as bV, type SubjectReferenceSource as bW, type SubjectReuseTarget as bX, type SubjectStatus as bY, type UpdateSignalInput as bZ, type UsageThresholdReachedEventData as b_, type ScreeningTrigger as ba, type ScreeningUnavailableReason as bb, type SekyroOptions as bc, SekyroTestApi as bd, type Session as be, type SessionClosedEventDataBase as bf, type SessionDecidingStep as bg, type SessionDevice as bh, type SessionEventDataBase as bi, type SessionEventStep as bj, type SessionFailureReason as bk, type SessionFlowRef as bl, type SessionHandoff as bm, type SessionHandoffDevice as bn, type SessionLifecycleEventData as bo, type SessionLinkDelivery as bp, type SessionLinkExpiry as bq, type SessionLinkInput as br, type SessionNetwork as bs, type SessionNetworkEvent as bt, type SessionNotVerifiedEventData as bu, type SessionRetakeRequestedEventData as bv, type SessionReviewPendingEventData as bw, type SessionScreening as bx, type SessionStatus as by, type SessionStep as bz, type SessionPersonInput as c, type WebhookEnvelopeOf as c0, type WebhookEventDataMap as c1, type WebhookTestInput as c2, type WebhookTestResult as c3, WebhooksApi as c4, 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 };
3328
+ export { type EligibilityReason 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 Declared as K, type Locale as L, type DeclaredAddress as M, type DeclaredAnswer as N, type DeclaredConsent as O, type DeclaredMismatch as P, type DeepPartial as Q, type ReviewReason as R, type SessionReason as S, type DeletedPerson as T, type DeliverOptions as U, type VerificationLevel as V, type WebhookEventType as W, type Device as X, DevicesApi as Y, type DocumentSubstitutionSettings as Z, type EidResult as _, Sekyro as a, type RequestOptions as a$, type ExtendLinkInput as a0, type FlowOverridableSettings as a1, type FlowOverrides as a2, type FlowServiceSettings as a3, type FlowSummary as a4, FlowsApi as a5, type FormAnswerValue as a6, type FormQuestionType as a7, type FraudReason as a8, type FraudResponse as a9, type NameForm as aA, type OverridableServiceId as aB, type Page as aC, PeopleApi as aD, type Person as aE, type PersonAddressInput as aF, type PersonBirthPlaceInput as aG, type PersonDeletedEventData as aH, type PersonDocumentInput as aI, type PersonEnrolledEventData as aJ, type PersonRef as aK, type PersonSession as aL, type PersonSessionInput as aM, type PersonSessionTarget as aN, type PersonUpdatedEventData as aO, type PoaDocumentKind as aP, type PoaReason as aQ, type PoaRule as aR, type PoaRuleKind as aS, type PoaRules as aT, type PortraitReportEntry as aU, type PriorReviewReason as aV, type ProbeBindingReason as aW, type ProbeQuality as aX, type ProfileDocumentType as aY, type ReadinessProtection as aZ, type ReadinessReport as a_, type IdNumberReason as aa, type Identity as ab, type IdentityAddress as ac, type IdentityBirthPlace as ad, type IdentityDocument as ae, type IdentityIdNumber as af, type IdentityMethod as ag, type IdentityName as ah, type IdentityProofOfAddress as ai, type IdentityScalarKey as aj, type IdentitySource as ak, type IdentitySources as al, type IncludedVerificationsThresholdReachedEventData as am, type LevelTarget as an, type LiftBlockInput as ao, type ListBlocksQuery as ap, type ListPeopleQuery as aq, type ListScreeningsQuery as ar, type ListSessionsQuery as as, type ListSignalsQuery as at, type MatchReason as au, type MediaBytes as av, type MediaBytesOptions as aw, type MediaItem as ax, type MediaKind as ay, type MediaList as az, type ServiceId as b, type UsageLimitReachedEventData as b$, type ResultTokenResponse as b0, type ReviewOutcomeReason as b1, type RevokePersonInput as b2, type SandboxSimulatedReason as b3, type SandboxSimulation as b4, type ScreenPersonInput as b5, type Screening as b6, type ScreeningHit as b7, type ScreeningHitSummary as b8, type ScreeningList as b9, type SessionStep as bA, type SessionStepAttempts as bB, type SessionStepBand as bC, type SessionStepDecision as bD, type SessionStepDocument as bE, type SessionStepPortrait as bF, SessionTestApi as bG, type SessionVerifiedEventData as bH, SessionsApi as bI, type Signal as bJ, type SignalEventData as bK, type SignalEvidence as bL, type SignalGrade as bM, type SignalKeyKind as bN, type SignalKind as bO, type SignalSeverity as bP, type SignalStatus as bQ, SignalsApi as bR, type SimulateSessionInput as bS, type StepResult as bT, type SubjectAssurance as bU, type SubjectIdNumber as bV, type SubjectName as bW, type SubjectReferenceSource as bX, type SubjectReuseTarget as bY, type SubjectStatus as bZ, type UpdateSignalInput as b_, type ScreeningStatus as ba, type ScreeningTrigger as bb, type ScreeningUnavailableReason as bc, type SekyroOptions as bd, SekyroTestApi as be, type Session as bf, type SessionClosedEventDataBase as bg, type SessionDecidingStep as bh, type SessionDevice as bi, type SessionEventDataBase as bj, type SessionEventStep as bk, type SessionFailureReason as bl, type SessionFlowRef as bm, type SessionHandoff as bn, type SessionHandoffDevice as bo, type SessionLifecycleEventData as bp, type SessionLinkDelivery as bq, type SessionLinkExpiry as br, type SessionLinkInput as bs, type SessionNetwork as bt, type SessionNetworkEvent as bu, type SessionNotVerifiedEventData as bv, type SessionRetakeRequestedEventData as bw, type SessionReviewPendingEventData as bx, type SessionScreening as by, type SessionStatus as bz, type SessionPersonInput as c, type UsageThresholdReachedEventData as c0, type VerifiedContacts as c1, type WebhookEnvelopeOf as c2, type WebhookEventDataMap as c3, type WebhookTestInput as c4, type WebhookTestResult as c5, WebhooksApi as c6, 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 };
@@ -76,8 +76,13 @@ type VerificationLevel = 0 | 1 | 2 | 3;
76
76
  * @public
77
77
  */
78
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";
79
- /** The one billing unit a finished session consumed. @public */
80
- type VerificationUnit = "human_verification" | "identity_verification";
79
+ /**
80
+ * The one billing unit a finished session consumed: `identity_verification` when an identity
81
+ * source ran, else `human_verification` when liveness ran, else `contact_verification` when only
82
+ * contact steps did work (an email or phone code was sent, or the device check ran).
83
+ * @public
84
+ */
85
+ type VerificationUnit = "contact_verification" | "human_verification" | "identity_verification";
81
86
  /** The lowest and highest {@link VerificationLevel} the session's flow can reach. @public */
82
87
  interface LevelTarget {
83
88
  min: VerificationLevel;
@@ -800,7 +805,7 @@ type ProfileDocumentType = "carte_identite" | "passport" | "residence_permit";
800
805
  * its `confirmDetails` setting (see {@link OverridableServiceId}).
801
806
  * @public
802
807
  */
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";
808
+ 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" | "form";
804
809
  /**
805
810
  * The services a Sekyro flow is built from, as {@link FlowOverrides.services}
806
811
  * names them: every {@link ServiceId} except `summary_confirm` (the
@@ -1032,6 +1037,12 @@ interface FlowServiceSettings {
1032
1037
  /** Keep and show the estimated age ({@link AgeResult.estimate}) on the API session and webhooks. Default `false`. */
1033
1038
  showEstimatedAge?: boolean;
1034
1039
  };
1040
+ /**
1041
+ * The Form step: a session can only turn it off (`services: { form: "off" }`);
1042
+ * its questions are not overridable. Prefill its answers with
1043
+ * {@link CreateSessionInput.answers}.
1044
+ */
1045
+ form: never;
1035
1046
  }
1036
1047
  /** One accepted kind of a proof of address rule and its maximum age (30 to 730 days). @public */
1037
1048
  interface PoaRuleKind {
@@ -2757,26 +2768,50 @@ interface SessionLinkExpiry {
2757
2768
  expiresAt: string;
2758
2769
  }
2759
2770
  /**
2760
- * `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
2761
- * plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
2762
- * tier, or the alert, e.g. `credit_80`, `usage_100_paid`, `spend_cap_reached`.
2771
+ * `usage.threshold_reached` for the monthly included verifications of a paid plan: 80 percent
2772
+ * of this month's included verifications are used (`included_verifications_80`) or all of them
2773
+ * (`included_verifications_100`). Sent once per kind and billing month. No amount, no currency.
2774
+ * @public
2775
+ */
2776
+ interface IncludedVerificationsThresholdReachedEventData {
2777
+ kind: "included_verifications_80" | "included_verifications_100";
2778
+ threshold: 80 | 100;
2779
+ /** The share of this month's included verifications used, in whole percent (0 to 100). */
2780
+ usedPercent: number;
2781
+ /** Up to how many human or identity verifications are still included this month, any mix. */
2782
+ remaining: {
2783
+ human: number;
2784
+ identity: number;
2785
+ };
2786
+ /** The billing month the included verifications belong to (ISO 8601). */
2787
+ period: {
2788
+ from: string;
2789
+ to: string;
2790
+ };
2791
+ }
2792
+ /**
2793
+ * `usage.threshold_reached` for every other alert: a balance, starting credit, spend or email
2794
+ * allowance threshold, e.g. `credit_80`, `spend_cap_reached`, `email_allowance_80`.
2763
2795
  * @public
2764
2796
  */
2765
- interface UsageThresholdReachedEventData {
2797
+ interface UsageLimitReachedEventData {
2766
2798
  kind: string;
2767
2799
  /** The verification unit, on per-unit alerts. */
2768
- unit?: "human_verification" | "identity_verification";
2769
- /** Percent of the limit (80, 100), or `overage` for the first verification beyond a tier. */
2770
- threshold?: number | "overage";
2800
+ unit?: VerificationUnit;
2801
+ /** Percent of the limit (80, 100). */
2802
+ threshold?: number;
2771
2803
  used?: number;
2772
2804
  limit?: number;
2773
2805
  /** UTC month, `YYYY-MM`. */
2774
2806
  period?: string;
2775
- /** Tier alerts: verifications that reached a result this month. */
2776
- confirmed?: number;
2777
- /** Tier alerts: verifications beyond the tier this month. */
2778
- overage?: number;
2779
2807
  }
2808
+ /**
2809
+ * `usage.threshold_reached`: a threshold of the organization's plan was reached (sent once
2810
+ * per threshold and period). The included verifications alerts carry `usedPercent` and
2811
+ * `remaining`, so `"remaining" in data` tells them apart.
2812
+ * @public
2813
+ */
2814
+ type UsageThresholdReachedEventData = IncludedVerificationsThresholdReachedEventData | UsageLimitReachedEventData;
2780
2815
  /**
2781
2816
  * `data` of `session.retake_requested`: a reviewer sent the session back for a new capture of
2782
2817
  * one step. The session is open again until `expiresAt`.
@@ -3122,9 +3157,9 @@ declare class BlocksApi {
3122
3157
  /**
3123
3158
  * `POST /blocks`: blocks the key, or answers the active block already on it. `kind: "person"`
3124
3159
  * blocks each ID number of the person and answers a list. A shared device answers
3125
- * `409 device_shared` with `details.people` unless `force: true`. `403 blocks_disabled` while blocks
3126
- * are turned off. The API requires an idempotency key: one is generated when you pass none, so
3127
- * pass your own to make a retry of the same call safe.
3160
+ * `409 device_shared` with `details.people` unless `force: true`. A block acts as soon as it
3161
+ * exists. The API requires an idempotency key: one is generated when you pass none, so pass your
3162
+ * own to make a retry of the same call safe.
3128
3163
  */
3129
3164
  create(input: CreateBlockInput & {
3130
3165
  kind: "person";
@@ -3146,9 +3181,8 @@ declare class BlocksApi {
3146
3181
  /**
3147
3182
  * Findings: sessions of this environment that share a key and met a pattern
3148
3183
  * ({@link Signal}). Exposed as {@link Sekyro.signals}. Reading needs the
3149
- * `signals:read` scope, {@link SignalsApi.update} `signals:write`. Every call
3150
- * answers `403 signals_unavailable` while Signals are not available in the
3151
- * environment. Exported as a TYPE only.
3184
+ * `signals:read` scope, {@link SignalsApi.update} `signals:write`. Exported as
3185
+ * a TYPE only.
3152
3186
  * @public
3153
3187
  */
3154
3188
  declare class SignalsApi {
@@ -3291,4 +3325,4 @@ declare class Sekyro {
3291
3325
  readiness(): Promise<ReadinessReport>;
3292
3326
  }
3293
3327
 
3294
- export { type EligibilityReason 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 Declared as K, type Locale as L, type DeclaredAddress as M, type DeclaredAnswer as N, type DeclaredConsent as O, type DeclaredMismatch as P, type DeepPartial as Q, type ReviewReason as R, type SessionReason as S, type DeletedPerson as T, type DeliverOptions as U, type VerificationLevel as V, type WebhookEventType as W, type Device as X, DevicesApi as Y, type DocumentSubstitutionSettings as Z, type EidResult as _, Sekyro as a, type ResultTokenResponse as a$, type ExtendLinkInput as a0, type FlowOverridableSettings as a1, type FlowOverrides as a2, type FlowServiceSettings as a3, type FlowSummary as a4, FlowsApi as a5, type FormAnswerValue as a6, type FormQuestionType as a7, type FraudReason as a8, type FraudResponse as a9, type OverridableServiceId as aA, type Page as aB, PeopleApi as aC, type Person as aD, type PersonAddressInput as aE, type PersonBirthPlaceInput as aF, type PersonDeletedEventData as aG, type PersonDocumentInput as aH, type PersonEnrolledEventData as aI, type PersonRef as aJ, type PersonSession as aK, type PersonSessionInput as aL, type PersonSessionTarget as aM, type PersonUpdatedEventData as aN, type PoaDocumentKind as aO, type PoaReason as aP, type PoaRule as aQ, type PoaRuleKind as aR, type PoaRules as aS, type PortraitReportEntry as aT, type PriorReviewReason as aU, type ProbeBindingReason as aV, type ProbeQuality as aW, type ProfileDocumentType as aX, type ReadinessProtection as aY, type ReadinessReport as aZ, type RequestOptions as a_, type IdNumberReason as aa, type Identity as ab, type IdentityAddress as ac, type IdentityBirthPlace as ad, type IdentityDocument as ae, type IdentityIdNumber as af, type IdentityMethod as ag, type IdentityName as ah, type IdentityProofOfAddress as ai, type IdentityScalarKey as aj, type IdentitySource as ak, type IdentitySources as al, type LevelTarget as am, type LiftBlockInput as an, type ListBlocksQuery as ao, type ListPeopleQuery as ap, type ListScreeningsQuery as aq, type ListSessionsQuery as ar, type ListSignalsQuery as as, type MatchReason as at, type MediaBytes as au, type MediaBytesOptions as av, type MediaItem as aw, type MediaKind as ax, type MediaList as ay, type NameForm as az, type ServiceId as b, type VerifiedContacts as b$, type ReviewOutcomeReason as b0, type RevokePersonInput as b1, type SandboxSimulatedReason as b2, type SandboxSimulation as b3, type ScreenPersonInput as b4, type Screening as b5, type ScreeningHit as b6, type ScreeningHitSummary as b7, type ScreeningList as b8, type ScreeningStatus as b9, type SessionStepAttempts as bA, type SessionStepBand as bB, type SessionStepDecision as bC, type SessionStepDocument as bD, type SessionStepPortrait as bE, SessionTestApi as bF, type SessionVerifiedEventData as bG, SessionsApi as bH, type Signal as bI, type SignalEventData as bJ, type SignalEvidence as bK, type SignalGrade as bL, type SignalKeyKind as bM, type SignalKind as bN, type SignalSeverity as bO, type SignalStatus as bP, SignalsApi as bQ, type SimulateSessionInput as bR, type StepResult as bS, type SubjectAssurance as bT, type SubjectIdNumber as bU, type SubjectName as bV, type SubjectReferenceSource as bW, type SubjectReuseTarget as bX, type SubjectStatus as bY, type UpdateSignalInput as bZ, type UsageThresholdReachedEventData as b_, type ScreeningTrigger as ba, type ScreeningUnavailableReason as bb, type SekyroOptions as bc, SekyroTestApi as bd, type Session as be, type SessionClosedEventDataBase as bf, type SessionDecidingStep as bg, type SessionDevice as bh, type SessionEventDataBase as bi, type SessionEventStep as bj, type SessionFailureReason as bk, type SessionFlowRef as bl, type SessionHandoff as bm, type SessionHandoffDevice as bn, type SessionLifecycleEventData as bo, type SessionLinkDelivery as bp, type SessionLinkExpiry as bq, type SessionLinkInput as br, type SessionNetwork as bs, type SessionNetworkEvent as bt, type SessionNotVerifiedEventData as bu, type SessionRetakeRequestedEventData as bv, type SessionReviewPendingEventData as bw, type SessionScreening as bx, type SessionStatus as by, type SessionStep as bz, type SessionPersonInput as c, type WebhookEnvelopeOf as c0, type WebhookEventDataMap as c1, type WebhookTestInput as c2, type WebhookTestResult as c3, WebhooksApi as c4, 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 };
3328
+ export { type EligibilityReason 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 Declared as K, type Locale as L, type DeclaredAddress as M, type DeclaredAnswer as N, type DeclaredConsent as O, type DeclaredMismatch as P, type DeepPartial as Q, type ReviewReason as R, type SessionReason as S, type DeletedPerson as T, type DeliverOptions as U, type VerificationLevel as V, type WebhookEventType as W, type Device as X, DevicesApi as Y, type DocumentSubstitutionSettings as Z, type EidResult as _, Sekyro as a, type RequestOptions as a$, type ExtendLinkInput as a0, type FlowOverridableSettings as a1, type FlowOverrides as a2, type FlowServiceSettings as a3, type FlowSummary as a4, FlowsApi as a5, type FormAnswerValue as a6, type FormQuestionType as a7, type FraudReason as a8, type FraudResponse as a9, type NameForm as aA, type OverridableServiceId as aB, type Page as aC, PeopleApi as aD, type Person as aE, type PersonAddressInput as aF, type PersonBirthPlaceInput as aG, type PersonDeletedEventData as aH, type PersonDocumentInput as aI, type PersonEnrolledEventData as aJ, type PersonRef as aK, type PersonSession as aL, type PersonSessionInput as aM, type PersonSessionTarget as aN, type PersonUpdatedEventData as aO, type PoaDocumentKind as aP, type PoaReason as aQ, type PoaRule as aR, type PoaRuleKind as aS, type PoaRules as aT, type PortraitReportEntry as aU, type PriorReviewReason as aV, type ProbeBindingReason as aW, type ProbeQuality as aX, type ProfileDocumentType as aY, type ReadinessProtection as aZ, type ReadinessReport as a_, type IdNumberReason as aa, type Identity as ab, type IdentityAddress as ac, type IdentityBirthPlace as ad, type IdentityDocument as ae, type IdentityIdNumber as af, type IdentityMethod as ag, type IdentityName as ah, type IdentityProofOfAddress as ai, type IdentityScalarKey as aj, type IdentitySource as ak, type IdentitySources as al, type IncludedVerificationsThresholdReachedEventData as am, type LevelTarget as an, type LiftBlockInput as ao, type ListBlocksQuery as ap, type ListPeopleQuery as aq, type ListScreeningsQuery as ar, type ListSessionsQuery as as, type ListSignalsQuery as at, type MatchReason as au, type MediaBytes as av, type MediaBytesOptions as aw, type MediaItem as ax, type MediaKind as ay, type MediaList as az, type ServiceId as b, type UsageLimitReachedEventData as b$, type ResultTokenResponse as b0, type ReviewOutcomeReason as b1, type RevokePersonInput as b2, type SandboxSimulatedReason as b3, type SandboxSimulation as b4, type ScreenPersonInput as b5, type Screening as b6, type ScreeningHit as b7, type ScreeningHitSummary as b8, type ScreeningList as b9, type SessionStep as bA, type SessionStepAttempts as bB, type SessionStepBand as bC, type SessionStepDecision as bD, type SessionStepDocument as bE, type SessionStepPortrait as bF, SessionTestApi as bG, type SessionVerifiedEventData as bH, SessionsApi as bI, type Signal as bJ, type SignalEventData as bK, type SignalEvidence as bL, type SignalGrade as bM, type SignalKeyKind as bN, type SignalKind as bO, type SignalSeverity as bP, type SignalStatus as bQ, SignalsApi as bR, type SimulateSessionInput as bS, type StepResult as bT, type SubjectAssurance as bU, type SubjectIdNumber as bV, type SubjectName as bW, type SubjectReferenceSource as bX, type SubjectReuseTarget as bY, type SubjectStatus as bZ, type UpdateSignalInput as b_, type ScreeningStatus as ba, type ScreeningTrigger as bb, type ScreeningUnavailableReason as bc, type SekyroOptions as bd, SekyroTestApi as be, type Session as bf, type SessionClosedEventDataBase as bg, type SessionDecidingStep as bh, type SessionDevice as bi, type SessionEventDataBase as bj, type SessionEventStep as bk, type SessionFailureReason as bl, type SessionFlowRef as bm, type SessionHandoff as bn, type SessionHandoffDevice as bo, type SessionLifecycleEventData as bp, type SessionLinkDelivery as bq, type SessionLinkExpiry as br, type SessionLinkInput as bs, type SessionNetwork as bt, type SessionNetworkEvent as bu, type SessionNotVerifiedEventData as bv, type SessionRetakeRequestedEventData as bw, type SessionReviewPendingEventData as bx, type SessionScreening as by, type SessionStatus as bz, type SessionPersonInput as c, type UsageThresholdReachedEventData as c0, type VerifiedContacts as c1, type WebhookEnvelopeOf as c2, type WebhookEventDataMap as c3, type WebhookTestInput as c4, type WebhookTestResult as c5, WebhooksApi as c6, 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,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-phyCLM3k.cjs';
2
- import '../../client-BoscyTQd.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-C66zNvN7.cjs';
2
+ import '../../client-D6zMa7hQ.cjs';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/express`: a route gate for Express (and any
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-CZ4k9r_4.js';
2
- import '../../client-BoscyTQd.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-D26UF7LX.js';
2
+ import '../../client-D6zMa7hQ.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/express`: a route gate for Express (and any
@@ -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-phyCLM3k.cjs';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-BoscyTQd.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-C66zNvN7.cjs';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-D6zMa7hQ.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-CZ4k9r_4.js';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-BoscyTQd.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-D26UF7LX.js';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-D6zMa7hQ.js';
3
3
 
4
4
  /**
5
5
  * Why a connector refused to act:
@@ -1,5 +1,5 @@
1
- import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-phyCLM3k.cjs';
2
- import '../../client-BoscyTQd.cjs';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-C66zNvN7.cjs';
2
+ import '../../client-D6zMa7hQ.cjs';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/next`: gate helpers for Next.js middleware, route
@@ -1,5 +1,5 @@
1
- import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-CZ4k9r_4.js';
2
- import '../../client-BoscyTQd.js';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-D26UF7LX.js';
2
+ import '../../client-D6zMa7hQ.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/next`: gate helpers for Next.js middleware, route
@@ -1,4 +1,4 @@
1
- import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-BoscyTQd.cjs';
1
+ import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-D6zMa7hQ.cjs';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -1,4 +1,4 @@
1
- import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-BoscyTQd.js';
1
+ import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-D6zMa7hQ.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
package/dist/index.cjs CHANGED
@@ -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 src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.26";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),claim.address_verified===!0&&typeof claim.address_country=="string"&&/^[A-Z]{2}$/.test(claim.address_country)&&(out.addressVerified=!0,out.addressCountry=claim.address_country);let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook});
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 src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.28";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),claim.address_verified===!0&&typeof claim.address_country=="string"&&/^[A-Z]{2}$/.test(claim.address_country)&&(out.addressVerified=!0,out.addressCountry=claim.address_country);let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-BoscyTQd.cjs';
2
- export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as Declared, M as DeclaredAddress, N as DeclaredAnswer, O as DeclaredConsent, P as DeclaredMismatch, Q as DeepPartial, T as DeletedPerson, U as DeliverOptions, X as Device, Y as DevicesApi, Z as DocumentSubstitutionSettings, _ as EidResult, $ as EligibilityReason, a0 as ExtendLinkInput, a1 as FlowOverridableSettings, a2 as FlowOverrides, a3 as FlowServiceSettings, a4 as FlowSummary, a5 as FlowsApi, a6 as FormAnswerValue, a7 as FormQuestionType, a8 as FraudReason, a9 as FraudResponse, aa as IdNumberReason, ab as Identity, ac as IdentityAddress, ad as IdentityBirthPlace, ae as IdentityDocument, af as IdentityIdNumber, ag as IdentityMethod, ah as IdentityName, ai as IdentityProofOfAddress, aj as IdentityScalarKey, ak as IdentitySource, al as IdentitySources, am as LevelTarget, an as LiftBlockInput, ao as ListBlocksQuery, ap as ListPeopleQuery, aq as ListScreeningsQuery, ar as ListSessionsQuery, as as ListSignalsQuery, L as Locale, at as MatchReason, au as MediaBytes, av as MediaBytesOptions, aw as MediaItem, ax as MediaKind, ay as MediaList, az as NameForm, aA as OverridableServiceId, aB as Page, aC as PeopleApi, aD as Person, aE as PersonAddressInput, aF as PersonBirthPlaceInput, aG as PersonDeletedEventData, aH as PersonDocumentInput, aI as PersonEnrolledEventData, aJ as PersonRef, aK as PersonSession, aL as PersonSessionInput, aM as PersonSessionTarget, aN as PersonUpdatedEventData, aO as PoaDocumentKind, aP as PoaReason, aQ as PoaRule, aR as PoaRuleKind, aS as PoaRules, aT as PortraitReportEntry, aU as PriorReviewReason, aV as ProbeBindingReason, aW as ProbeQuality, aX as ProfileDocumentType, aY as ReadinessProtection, aZ as ReadinessReport, a_ as RequestOptions, a$ as ResultTokenResponse, b0 as ReviewOutcomeReason, b1 as RevokePersonInput, b2 as SandboxSimulatedReason, b3 as SandboxSimulation, b4 as ScreenPersonInput, b5 as Screening, b6 as ScreeningHit, b7 as ScreeningHitSummary, b8 as ScreeningList, b9 as ScreeningStatus, ba as ScreeningTrigger, bb as ScreeningUnavailableReason, a as Sekyro, bc as SekyroOptions, bd as SekyroTestApi, be as Session, bf as SessionClosedEventDataBase, bg as SessionDecidingStep, bh as SessionDevice, bi as SessionEventDataBase, bj as SessionEventStep, bk as SessionFailureReason, bl as SessionFlowRef, bm as SessionHandoff, bn as SessionHandoffDevice, bo as SessionLifecycleEventData, bp as SessionLinkDelivery, bq as SessionLinkExpiry, br as SessionLinkInput, bs as SessionNetwork, bt as SessionNetworkEvent, bu as SessionNotVerifiedEventData, S as SessionReason, bv as SessionRetakeRequestedEventData, bw as SessionReviewPendingEventData, bx as SessionScreening, by as SessionStatus, bz as SessionStep, bA as SessionStepAttempts, bB as SessionStepBand, bC as SessionStepDecision, bD as SessionStepDocument, bE as SessionStepPortrait, bF as SessionTestApi, bG as SessionVerifiedEventData, bH as SessionsApi, bI as Signal, bJ as SignalEventData, bK as SignalEvidence, bL as SignalGrade, bM as SignalKeyKind, bN as SignalKind, bO as SignalSeverity, bP as SignalStatus, bQ as SignalsApi, bR as SimulateSessionInput, bS as StepResult, bT as SubjectAssurance, bU as SubjectIdNumber, bV as SubjectName, bW as SubjectReferenceSource, bX as SubjectReuseTarget, bY as SubjectStatus, bZ as UpdateSignalInput, b_ as UsageThresholdReachedEventData, b$ as VerifiedContacts, c0 as WebhookEnvelopeOf, c1 as WebhookEventDataMap, W as WebhookEventType, c2 as WebhookTestInput, c3 as WebhookTestResult, c4 as WebhooksApi } from './client-BoscyTQd.cjs';
1
+ import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-D6zMa7hQ.cjs';
2
+ export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as Declared, M as DeclaredAddress, N as DeclaredAnswer, O as DeclaredConsent, P as DeclaredMismatch, Q as DeepPartial, T as DeletedPerson, U as DeliverOptions, X as Device, Y as DevicesApi, Z as DocumentSubstitutionSettings, _ as EidResult, $ as EligibilityReason, a0 as ExtendLinkInput, a1 as FlowOverridableSettings, a2 as FlowOverrides, a3 as FlowServiceSettings, a4 as FlowSummary, a5 as FlowsApi, a6 as FormAnswerValue, a7 as FormQuestionType, a8 as FraudReason, a9 as FraudResponse, aa as IdNumberReason, ab as Identity, ac as IdentityAddress, ad as IdentityBirthPlace, ae as IdentityDocument, af as IdentityIdNumber, ag as IdentityMethod, ah as IdentityName, ai as IdentityProofOfAddress, aj as IdentityScalarKey, ak as IdentitySource, al as IdentitySources, am as IncludedVerificationsThresholdReachedEventData, an as LevelTarget, ao as LiftBlockInput, ap as ListBlocksQuery, aq as ListPeopleQuery, ar as ListScreeningsQuery, as as ListSessionsQuery, at as ListSignalsQuery, L as Locale, au as MatchReason, av as MediaBytes, aw as MediaBytesOptions, ax as MediaItem, ay as MediaKind, az as MediaList, aA as NameForm, aB as OverridableServiceId, aC as Page, aD as PeopleApi, aE as Person, aF as PersonAddressInput, aG as PersonBirthPlaceInput, aH as PersonDeletedEventData, aI as PersonDocumentInput, aJ as PersonEnrolledEventData, aK as PersonRef, aL as PersonSession, aM as PersonSessionInput, aN as PersonSessionTarget, aO as PersonUpdatedEventData, aP as PoaDocumentKind, aQ as PoaReason, aR as PoaRule, aS as PoaRuleKind, aT as PoaRules, aU as PortraitReportEntry, aV as PriorReviewReason, aW as ProbeBindingReason, aX as ProbeQuality, aY as ProfileDocumentType, aZ as ReadinessProtection, a_ as ReadinessReport, a$ as RequestOptions, b0 as ResultTokenResponse, b1 as ReviewOutcomeReason, b2 as RevokePersonInput, b3 as SandboxSimulatedReason, b4 as SandboxSimulation, b5 as ScreenPersonInput, b6 as Screening, b7 as ScreeningHit, b8 as ScreeningHitSummary, b9 as ScreeningList, ba as ScreeningStatus, bb as ScreeningTrigger, bc as ScreeningUnavailableReason, a as Sekyro, bd as SekyroOptions, be as SekyroTestApi, bf as Session, bg as SessionClosedEventDataBase, bh as SessionDecidingStep, bi as SessionDevice, bj as SessionEventDataBase, bk as SessionEventStep, bl as SessionFailureReason, bm as SessionFlowRef, bn as SessionHandoff, bo as SessionHandoffDevice, bp as SessionLifecycleEventData, bq as SessionLinkDelivery, br as SessionLinkExpiry, bs as SessionLinkInput, bt as SessionNetwork, bu as SessionNetworkEvent, bv as SessionNotVerifiedEventData, S as SessionReason, bw as SessionRetakeRequestedEventData, bx as SessionReviewPendingEventData, by as SessionScreening, bz as SessionStatus, bA as SessionStep, bB as SessionStepAttempts, bC as SessionStepBand, bD as SessionStepDecision, bE as SessionStepDocument, bF as SessionStepPortrait, bG as SessionTestApi, bH as SessionVerifiedEventData, bI as SessionsApi, bJ as Signal, bK as SignalEventData, bL as SignalEvidence, bM as SignalGrade, bN as SignalKeyKind, bO as SignalKind, bP as SignalSeverity, bQ as SignalStatus, bR as SignalsApi, bS as SimulateSessionInput, bT as StepResult, bU as SubjectAssurance, bV as SubjectIdNumber, bW as SubjectName, bX as SubjectReferenceSource, bY as SubjectReuseTarget, bZ as SubjectStatus, b_ as UpdateSignalInput, b$ as UsageLimitReachedEventData, c0 as UsageThresholdReachedEventData, c1 as VerifiedContacts, c2 as WebhookEnvelopeOf, c3 as WebhookEventDataMap, W as WebhookEventType, c4 as WebhookTestInput, c5 as WebhookTestResult, c6 as WebhooksApi } from './client-D6zMa7hQ.cjs';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-BoscyTQd.js';
2
- export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as Declared, M as DeclaredAddress, N as DeclaredAnswer, O as DeclaredConsent, P as DeclaredMismatch, Q as DeepPartial, T as DeletedPerson, U as DeliverOptions, X as Device, Y as DevicesApi, Z as DocumentSubstitutionSettings, _ as EidResult, $ as EligibilityReason, a0 as ExtendLinkInput, a1 as FlowOverridableSettings, a2 as FlowOverrides, a3 as FlowServiceSettings, a4 as FlowSummary, a5 as FlowsApi, a6 as FormAnswerValue, a7 as FormQuestionType, a8 as FraudReason, a9 as FraudResponse, aa as IdNumberReason, ab as Identity, ac as IdentityAddress, ad as IdentityBirthPlace, ae as IdentityDocument, af as IdentityIdNumber, ag as IdentityMethod, ah as IdentityName, ai as IdentityProofOfAddress, aj as IdentityScalarKey, ak as IdentitySource, al as IdentitySources, am as LevelTarget, an as LiftBlockInput, ao as ListBlocksQuery, ap as ListPeopleQuery, aq as ListScreeningsQuery, ar as ListSessionsQuery, as as ListSignalsQuery, L as Locale, at as MatchReason, au as MediaBytes, av as MediaBytesOptions, aw as MediaItem, ax as MediaKind, ay as MediaList, az as NameForm, aA as OverridableServiceId, aB as Page, aC as PeopleApi, aD as Person, aE as PersonAddressInput, aF as PersonBirthPlaceInput, aG as PersonDeletedEventData, aH as PersonDocumentInput, aI as PersonEnrolledEventData, aJ as PersonRef, aK as PersonSession, aL as PersonSessionInput, aM as PersonSessionTarget, aN as PersonUpdatedEventData, aO as PoaDocumentKind, aP as PoaReason, aQ as PoaRule, aR as PoaRuleKind, aS as PoaRules, aT as PortraitReportEntry, aU as PriorReviewReason, aV as ProbeBindingReason, aW as ProbeQuality, aX as ProfileDocumentType, aY as ReadinessProtection, aZ as ReadinessReport, a_ as RequestOptions, a$ as ResultTokenResponse, b0 as ReviewOutcomeReason, b1 as RevokePersonInput, b2 as SandboxSimulatedReason, b3 as SandboxSimulation, b4 as ScreenPersonInput, b5 as Screening, b6 as ScreeningHit, b7 as ScreeningHitSummary, b8 as ScreeningList, b9 as ScreeningStatus, ba as ScreeningTrigger, bb as ScreeningUnavailableReason, a as Sekyro, bc as SekyroOptions, bd as SekyroTestApi, be as Session, bf as SessionClosedEventDataBase, bg as SessionDecidingStep, bh as SessionDevice, bi as SessionEventDataBase, bj as SessionEventStep, bk as SessionFailureReason, bl as SessionFlowRef, bm as SessionHandoff, bn as SessionHandoffDevice, bo as SessionLifecycleEventData, bp as SessionLinkDelivery, bq as SessionLinkExpiry, br as SessionLinkInput, bs as SessionNetwork, bt as SessionNetworkEvent, bu as SessionNotVerifiedEventData, S as SessionReason, bv as SessionRetakeRequestedEventData, bw as SessionReviewPendingEventData, bx as SessionScreening, by as SessionStatus, bz as SessionStep, bA as SessionStepAttempts, bB as SessionStepBand, bC as SessionStepDecision, bD as SessionStepDocument, bE as SessionStepPortrait, bF as SessionTestApi, bG as SessionVerifiedEventData, bH as SessionsApi, bI as Signal, bJ as SignalEventData, bK as SignalEvidence, bL as SignalGrade, bM as SignalKeyKind, bN as SignalKind, bO as SignalSeverity, bP as SignalStatus, bQ as SignalsApi, bR as SimulateSessionInput, bS as StepResult, bT as SubjectAssurance, bU as SubjectIdNumber, bV as SubjectName, bW as SubjectReferenceSource, bX as SubjectReuseTarget, bY as SubjectStatus, bZ as UpdateSignalInput, b_ as UsageThresholdReachedEventData, b$ as VerifiedContacts, c0 as WebhookEnvelopeOf, c1 as WebhookEventDataMap, W as WebhookEventType, c2 as WebhookTestInput, c3 as WebhookTestResult, c4 as WebhooksApi } from './client-BoscyTQd.js';
1
+ import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-D6zMa7hQ.js';
2
+ export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as Declared, M as DeclaredAddress, N as DeclaredAnswer, O as DeclaredConsent, P as DeclaredMismatch, Q as DeepPartial, T as DeletedPerson, U as DeliverOptions, X as Device, Y as DevicesApi, Z as DocumentSubstitutionSettings, _ as EidResult, $ as EligibilityReason, a0 as ExtendLinkInput, a1 as FlowOverridableSettings, a2 as FlowOverrides, a3 as FlowServiceSettings, a4 as FlowSummary, a5 as FlowsApi, a6 as FormAnswerValue, a7 as FormQuestionType, a8 as FraudReason, a9 as FraudResponse, aa as IdNumberReason, ab as Identity, ac as IdentityAddress, ad as IdentityBirthPlace, ae as IdentityDocument, af as IdentityIdNumber, ag as IdentityMethod, ah as IdentityName, ai as IdentityProofOfAddress, aj as IdentityScalarKey, ak as IdentitySource, al as IdentitySources, am as IncludedVerificationsThresholdReachedEventData, an as LevelTarget, ao as LiftBlockInput, ap as ListBlocksQuery, aq as ListPeopleQuery, ar as ListScreeningsQuery, as as ListSessionsQuery, at as ListSignalsQuery, L as Locale, au as MatchReason, av as MediaBytes, aw as MediaBytesOptions, ax as MediaItem, ay as MediaKind, az as MediaList, aA as NameForm, aB as OverridableServiceId, aC as Page, aD as PeopleApi, aE as Person, aF as PersonAddressInput, aG as PersonBirthPlaceInput, aH as PersonDeletedEventData, aI as PersonDocumentInput, aJ as PersonEnrolledEventData, aK as PersonRef, aL as PersonSession, aM as PersonSessionInput, aN as PersonSessionTarget, aO as PersonUpdatedEventData, aP as PoaDocumentKind, aQ as PoaReason, aR as PoaRule, aS as PoaRuleKind, aT as PoaRules, aU as PortraitReportEntry, aV as PriorReviewReason, aW as ProbeBindingReason, aX as ProbeQuality, aY as ProfileDocumentType, aZ as ReadinessProtection, a_ as ReadinessReport, a$ as RequestOptions, b0 as ResultTokenResponse, b1 as ReviewOutcomeReason, b2 as RevokePersonInput, b3 as SandboxSimulatedReason, b4 as SandboxSimulation, b5 as ScreenPersonInput, b6 as Screening, b7 as ScreeningHit, b8 as ScreeningHitSummary, b9 as ScreeningList, ba as ScreeningStatus, bb as ScreeningTrigger, bc as ScreeningUnavailableReason, a as Sekyro, bd as SekyroOptions, be as SekyroTestApi, bf as Session, bg as SessionClosedEventDataBase, bh as SessionDecidingStep, bi as SessionDevice, bj as SessionEventDataBase, bk as SessionEventStep, bl as SessionFailureReason, bm as SessionFlowRef, bn as SessionHandoff, bo as SessionHandoffDevice, bp as SessionLifecycleEventData, bq as SessionLinkDelivery, br as SessionLinkExpiry, bs as SessionLinkInput, bt as SessionNetwork, bu as SessionNetworkEvent, bv as SessionNotVerifiedEventData, S as SessionReason, bw as SessionRetakeRequestedEventData, bx as SessionReviewPendingEventData, by as SessionScreening, bz as SessionStatus, bA as SessionStep, bB as SessionStepAttempts, bC as SessionStepBand, bD as SessionStepDecision, bE as SessionStepDocument, bF as SessionStepPortrait, bG as SessionTestApi, bH as SessionVerifiedEventData, bI as SessionsApi, bJ as Signal, bK as SignalEventData, bL as SignalEvidence, bM as SignalGrade, bN as SignalKeyKind, bO as SignalKind, bP as SignalSeverity, bQ as SignalStatus, bR as SignalsApi, bS as SimulateSessionInput, bT as StepResult, bU as SubjectAssurance, bV as SubjectIdNumber, bW as SubjectName, bX as SubjectReferenceSource, bY as SubjectReuseTarget, bZ as SubjectStatus, b_ as UpdateSignalInput, b$ as UsageLimitReachedEventData, c0 as UsageThresholdReachedEventData, c1 as VerifiedContacts, c2 as WebhookEnvelopeOf, c3 as WebhookEventDataMap, W as WebhookEventType, c4 as WebhookTestInput, c5 as WebhookTestResult, c6 as WebhooksApi } from './client-D6zMa7hQ.js';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.26";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),claim.address_verified===!0&&typeof claim.address_country=="string"&&/^[A-Z]{2}$/.test(claim.address_country)&&(out.addressVerified=!0,out.addressCountry=claim.address_country);let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook};
1
+ var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.28";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),claim.address_verified===!0&&typeof claim.address_country=="string"&&/^[A-Z]{2}$/.test(claim.address_country)&&(out.addressVerified=!0,out.addressCountry=claim.address_country);let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sekyro/node",
3
- "version": "1.0.0-rc.26",
3
+ "version": "1.0.0-rc.28",
4
4
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
package/sbom.cdx.json CHANGED
@@ -97,8 +97,8 @@
97
97
  "type": "application",
98
98
  "name": "node",
99
99
  "group": "@sekyro",
100
- "version": "1.0.0-rc.26",
101
- "bom-ref": "@sekyro/node@1.0.0-rc.26",
100
+ "version": "1.0.0-rc.28",
101
+ "bom-ref": "@sekyro/node@1.0.0-rc.28",
102
102
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
103
103
  "licenses": [
104
104
  {
@@ -108,7 +108,7 @@
108
108
  }
109
109
  }
110
110
  ],
111
- "purl": "pkg:npm/%40sekyro/node@1.0.0-rc.26?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
111
+ "purl": "pkg:npm/%40sekyro/node@1.0.0-rc.28?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
112
112
  "externalReferences": [
113
113
  {
114
114
  "url": "https://github.com/IBTIKAR-Technologies/ibtikar-identity/issues",
@@ -149,7 +149,7 @@
149
149
  "type": "library",
150
150
  "name": "jose",
151
151
  "version": "5.10.0",
152
- "bom-ref": "@sekyro/node@1.0.0-rc.26|jose@5.10.0",
152
+ "bom-ref": "@sekyro/node@1.0.0-rc.28|jose@5.10.0",
153
153
  "licenses": [
154
154
  {
155
155
  "license": {
@@ -182,13 +182,13 @@
182
182
  ],
183
183
  "dependencies": [
184
184
  {
185
- "ref": "@sekyro/node@1.0.0-rc.26",
185
+ "ref": "@sekyro/node@1.0.0-rc.28",
186
186
  "dependsOn": [
187
- "@sekyro/node@1.0.0-rc.26|jose@5.10.0"
187
+ "@sekyro/node@1.0.0-rc.28|jose@5.10.0"
188
188
  ]
189
189
  },
190
190
  {
191
- "ref": "@sekyro/node@1.0.0-rc.26|jose@5.10.0"
191
+ "ref": "@sekyro/node@1.0.0-rc.28|jose@5.10.0"
192
192
  }
193
193
  ]
194
194
  }