@sekyro/node 1.0.0-rc.17 → 1.0.0-rc.18

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.
@@ -1030,21 +1030,140 @@ interface SessionFlowRef {
1030
1030
  version: number;
1031
1031
  }
1032
1032
  /**
1033
- * Input of {@link SessionsApi.simulate}.
1033
+ * Input of {@link SessionTestApi.simulate}: where a simulated Sandbox session
1034
+ * ends. Each outcome is reached through the real engine (expiry, cancel,
1035
+ * supersession, reviewer decision), never by writing a status, so the
1036
+ * webhooks, the result token and the dashboard rows are the real ones.
1034
1037
  * @public
1035
1038
  */
1036
1039
  interface SimulateSessionInput {
1040
+ /** Where the session ends. */
1041
+ status: "verified" | "not_verified" | "review_pending";
1037
1042
  /**
1038
- * Where the session ends: `verified`, `not_verified` or `review_pending`. The flow must be able
1039
- * to reach it, else `422 simulate_status_unreachable`.
1043
+ * `not_verified` only: why. Defaults to the reason the engine gives for the
1044
+ * path. A pair the outcome model cannot produce answers
1045
+ * `422 simulate_pair_invalid` with the valid pairs in `details.validPairs`.
1040
1046
  */
1041
- status: "verified" | "not_verified" | "review_pending";
1047
+ reason?: SessionReason;
1048
+ /** Who closes the session. Defaults to the value the engine gives for the path. */
1049
+ closedBy?: ClosedBy;
1042
1050
  /**
1043
- * Only with `not_verified`: the code a step on the path fails with, e.g. `spoof_detected`
1044
- * (the session's {@link Session.reasonCode}). No step on the path can fail with it:
1045
- * `422 simulate_reason_invalid`.
1051
+ * `not_verified` closed `automatic` only: the detailed code a step on the
1052
+ * path ends with, e.g. `spoof_detected` ({@link Session.reasonCode}).
1046
1053
  */
1047
1054
  reasonCode?: string;
1055
+ /** The service of the step that decides the outcome, e.g. `liveness`. */
1056
+ step?: ServiceId;
1057
+ /**
1058
+ * What happens once `status` is reached. After `review_pending`:
1059
+ * `decide:approve` and `decide:reject` record a reviewer decision, `retake`
1060
+ * asks the person for a retake (the session goes back to `in_progress` and
1061
+ * `session.retake_requested` is sent). With `verified`: `binding_retake`
1062
+ * stops at the face match whose probe does not bind to the liveness clip,
1063
+ * and the session waits for the person to retake their face.
1064
+ */
1065
+ then?: "retake" | "decide:approve" | "decide:reject" | "binding_retake";
1066
+ }
1067
+ /**
1068
+ * One client protection in a {@link ReadinessReport}: how often it tripped, and what Live's
1069
+ * posture would do.
1070
+ * @public
1071
+ */
1072
+ interface ReadinessProtection {
1073
+ /** The organization's Live posture. */
1074
+ livePosture: "off" | "signal" | "enforce";
1075
+ /** Sessions of the window whose check carried the failing signal. */
1076
+ sessions: number;
1077
+ /** Of those, how many Live would have stopped (the posture is `enforce`). */
1078
+ wouldStopInLive: number;
1079
+ }
1080
+ /**
1081
+ * Result of {@link Sekyro.readiness}: what Live would change for your integration, from the key
1082
+ * environment's sessions of the last 30 days. Counts and ids only, never a person value.
1083
+ * @public
1084
+ */
1085
+ interface ReadinessReport {
1086
+ env: "sandbox" | "live";
1087
+ /** The window counted (ISO 8601). */
1088
+ window: {
1089
+ from: string;
1090
+ to: string;
1091
+ days: number;
1092
+ };
1093
+ /** Sessions created in the window that were counted, newest first; `capped` when older ones were left out. */
1094
+ sessions: {
1095
+ counted: number;
1096
+ capped: boolean;
1097
+ };
1098
+ clientAttestation: {
1099
+ /** Native attestation (App Attest, Play Integrity) that did not pass. */
1100
+ deviceAttestation: ReadinessProtection;
1101
+ /** Uploads without a valid live-camera capture proof. */
1102
+ captureOrigin: ReadinessProtection;
1103
+ /** Automation and emulator signals: recorded in both environments, they never stop a session. */
1104
+ automation: {
1105
+ webdriver: number;
1106
+ headless: number;
1107
+ emulator: number;
1108
+ };
1109
+ };
1110
+ webhooks: {
1111
+ /** Enabled endpoints per environment. */
1112
+ endpoints: {
1113
+ sandbox: number;
1114
+ live: number;
1115
+ };
1116
+ /** Deliveries of this environment that failed or died in the window. */
1117
+ failedDeliveries: number;
1118
+ };
1119
+ registries: {
1120
+ /** The active flows with a registry step, and whether Live has registry access for them. */
1121
+ flows: Array<{
1122
+ flowId: string;
1123
+ name: string;
1124
+ liveAccess: boolean;
1125
+ }>;
1126
+ };
1127
+ limits: Array<{
1128
+ id: "api_requests" | "verifications_started";
1129
+ /** The value in force in Live, per minute. */
1130
+ live: number;
1131
+ /** The busiest minute of this environment in the last 24 hours (`null`: nothing counted). */
1132
+ peakPerMinute: number | null;
1133
+ /** Requests of this environment the limit refused in the last 7 days. */
1134
+ rejected7d: number;
1135
+ }>;
1136
+ /** The SDK versions the sessions used. */
1137
+ sdks: Array<{
1138
+ sdk: string;
1139
+ version: string;
1140
+ /** The lowest version Sekyro AI recommends for this platform (`null`: none). */
1141
+ recommended: string | null;
1142
+ outdated: boolean;
1143
+ }>;
1144
+ /** Whether your server verified result tokens. Not known yet: always `null`. */
1145
+ resultTokenVerification: null;
1146
+ }
1147
+ /**
1148
+ * Input of {@link WebhooksApi.test}.
1149
+ * @public
1150
+ */
1151
+ interface WebhookTestInput {
1152
+ /**
1153
+ * The event to send as a realistic sample payload, with fresh ids and
1154
+ * timestamps. Defaults to `webhook.test`.
1155
+ */
1156
+ event?: WebhookEventType;
1157
+ }
1158
+ /**
1159
+ * Result of {@link WebhooksApi.test}.
1160
+ * @public
1161
+ */
1162
+ interface WebhookTestResult {
1163
+ /** `false` when no enabled endpoint of the key's environment subscribes to the event. */
1164
+ dispatched: boolean;
1165
+ /** The endpoints the event was queued for. */
1166
+ endpoints: number;
1048
1167
  }
1049
1168
  /**
1050
1169
  * The API key in use, from {@link Sekyro.me}. Never carries the secret.
@@ -1179,10 +1298,13 @@ interface CreatedSession {
1179
1298
  subjectUse?: "reference" | "prefill";
1180
1299
  /**
1181
1300
  * With {@link CreateSessionInput.deliver} only: the send of the hosted link.
1182
- * `failed` never fails the create; `simulated` on a simulated Sandbox session.
1301
+ * `failed` never fails the create. `simulated: true` in the Sandbox when the
1302
+ * destination is not an enrolled tester's: the destination passed the same
1303
+ * checks as in Live and nothing is sent.
1183
1304
  */
1184
1305
  delivery?: {
1185
- status: "queued" | "failed" | "simulated";
1306
+ status: "queued" | "failed";
1307
+ simulated?: true;
1186
1308
  };
1187
1309
  }
1188
1310
  /**
@@ -2291,8 +2413,9 @@ type ExtendLinkInput = {
2291
2413
  interface SessionLinkDelivery {
2292
2414
  delivery: {
2293
2415
  channel: "sms" | "whatsapp" | "email";
2294
- /** `simulated` in the Sandbox: nothing is sent. */
2295
- status: "queued" | "sent" | "failed" | "simulated";
2416
+ status: "queued" | "sent" | "failed";
2417
+ /** `true` in the Sandbox when the destination is not an enrolled tester's: nothing is sent. */
2418
+ simulated?: true;
2296
2419
  };
2297
2420
  }
2298
2421
  /** Result of {@link SessionsApi.extendLink}. @public */
@@ -2557,18 +2680,6 @@ declare class SessionsApi {
2557
2680
  * (it has no token). Needs the `sessions:read` scope.
2558
2681
  */
2559
2682
  resultToken(id: string): Promise<ResultTokenResponse>;
2560
- /**
2561
- * `POST /sessions/:id/simulate`: finishes a simulated Sandbox session in one
2562
- * call, for tests and CI. It runs every step of the flow through the real
2563
- * engine, so the status, the webhooks, the result token and the dashboard
2564
- * behave as for a session driven by a person. Never billed. Returns the
2565
- * finished session; pass an `idempotencyKey` to make a retry safe. Errors:
2566
- * `400 sandbox_only` (Live key), `409 session_not_simulated` (bound to a
2567
- * tester), `409 session_already_final`, `422 simulate_status_unreachable`
2568
- * (`details.issues` says why), `422 simulate_reason_invalid`. Needs the
2569
- * `sessions:create` scope.
2570
- */
2571
- simulate(id: string, input: SimulateSessionInput, opts?: RequestOptions): Promise<Session>;
2572
2683
  }
2573
2684
  /**
2574
2685
  * `sekyro.flows`: the flows of the API key's app.
@@ -2761,6 +2872,59 @@ declare class DevicesApi {
2761
2872
  shared: boolean;
2762
2873
  }, opts?: RequestOptions): Promise<Device>;
2763
2874
  }
2875
+ /**
2876
+ * `sekyro.webhooks`: your webhook endpoints. Exported as a TYPE only: obtained
2877
+ * through {@link Sekyro.webhooks}.
2878
+ * @public
2879
+ */
2880
+ declare class WebhooksApi {
2881
+ private readonly t;
2882
+ /** @internal */
2883
+ constructor(t: {
2884
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2885
+ });
2886
+ /**
2887
+ * `POST /webhooks/test`: sends a realistic sample of `event` (default
2888
+ * `webhook.test`) to the endpoints of the key's environment that subscribe
2889
+ * to it, signed like any delivery. Works with Sandbox and Live keys. Needs
2890
+ * the `webhooks:test` scope.
2891
+ */
2892
+ test(input?: WebhookTestInput): Promise<WebhookTestResult>;
2893
+ }
2894
+ /**
2895
+ * `sekyro.test.sessions`: test tools for simulated Sandbox sessions. Keep them
2896
+ * out of your production code path: a Live key is refused. Exported as a TYPE
2897
+ * only: obtained through {@link SekyroTestApi.sessions}.
2898
+ * @public
2899
+ */
2900
+ declare class SessionTestApi {
2901
+ private readonly t;
2902
+ /** @internal */
2903
+ constructor(t: {
2904
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2905
+ });
2906
+ /**
2907
+ * `POST /sessions/:id/simulate`: ends a simulated Sandbox session with the
2908
+ * outcome you name, through the real engine, so the webhooks, the result
2909
+ * token and the dashboard behave as for a session driven by a person. Never
2910
+ * billed. Returns the session; pass an `idempotencyKey` to make a retry
2911
+ * safe. Errors: `400 sandbox_only` (a Live key), `409 session_bound` (a
2912
+ * tester runs real checks in it), `409 session_already_final`,
2913
+ * `422 simulate_pair_invalid` (`details.validPairs` lists the valid pairs),
2914
+ * `422 simulate_status_unreachable` (`details.issues` says why) and
2915
+ * `422 simulate_reason_invalid`. Needs the `sessions:create` scope.
2916
+ */
2917
+ simulate(id: string, input: SimulateSessionInput, opts?: RequestOptions): Promise<Session>;
2918
+ }
2919
+ /**
2920
+ * `sekyro.test`: tools for tests and CI in the Sandbox. Exported as a TYPE only.
2921
+ * @public
2922
+ */
2923
+ declare class SekyroTestApi {
2924
+ readonly sessions: SessionTestApi;
2925
+ /** @internal */
2926
+ constructor(t: ConstructorParameters<typeof SessionTestApi>[0]);
2927
+ }
2764
2928
  /**
2765
2929
  * Sekyro AI partner API client. Server-side only: it carries your API key.
2766
2930
  *
@@ -2783,6 +2947,9 @@ declare class Sekyro {
2783
2947
  readonly signals: SignalsApi;
2784
2948
  readonly devices: DevicesApi;
2785
2949
  readonly flows: FlowsApi;
2950
+ readonly webhooks: WebhooksApi;
2951
+ /** Test tools for the Sandbox: {@link SekyroTestApi}. */
2952
+ readonly test: SekyroTestApi;
2786
2953
  constructor(opts: SekyroOptions);
2787
2954
  /**
2788
2955
  * `GET /me`: which key this is. Tells a Sandbox key from a Live one, and
@@ -2790,6 +2957,14 @@ declare class Sekyro {
2790
2957
  * never returns the secret. An invalid key answers `401 unauthorized`.
2791
2958
  */
2792
2959
  me(): Promise<ApiKeyIdentity>;
2960
+ /**
2961
+ * `GET /readiness`: what Live would change for your integration, from the
2962
+ * key environment's sessions of the last 30 days (counts and ids only). With
2963
+ * a Sandbox key it shows what Live would have stopped, so CI can assert
2964
+ * readiness before go-live; with a Live key it reports on Live. Needs the
2965
+ * `sessions:read` scope.
2966
+ */
2967
+ readiness(): Promise<ReadinessReport>;
2793
2968
  }
2794
2969
 
2795
- export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type SessionFlowRef as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityBirthPlace as a3, type IdentityDocument as a4, type IdentityIdNumber as a5, type IdentityMethod as a6, type IdentityName as a7, type IdentityScalarKey as a8, type IdentitySource as a9, type PersonSuspiciousActivityEventData as aA, type PersonUpdatedEventData as aB, type PortraitReportEntry as aC, type PriorReviewReason as aD, type ProbeBindingReason as aE, type ProbeQuality as aF, type ProfileDocumentType as aG, type RequestOptions as aH, type ResultTokenResponse as aI, type ReviewOutcomeReason as aJ, type RevokePersonInput as aK, type ScreenPersonInput as aL, type Screening as aM, type ScreeningHit as aN, type ScreeningHitSummary as aO, type ScreeningList as aP, type ScreeningStatus as aQ, type ScreeningTrigger as aR, type ScreeningUnavailableReason as aS, type SekyroOptions as aT, type Session as aU, type SessionClosedEventDataBase as aV, type SessionDecidingStep as aW, type SessionDevice as aX, type SessionEventDataBase as aY, type SessionEventStep as aZ, type SessionFailureReason as a_, type IdentitySources as aa, type LevelTarget as ab, type LiftBlockInput as ac, type ListBlocksQuery as ad, type ListPeopleQuery as ae, type ListScreeningsQuery as af, type ListSessionsQuery as ag, type ListSignalsQuery as ah, type MatchReason as ai, type MediaBytes as aj, type MediaBytesOptions as ak, type MediaItem as al, type MediaKind as am, type MediaList as an, type NameForm as ao, type Page as ap, PeopleApi as aq, type Person as ar, type PersonBirthPlaceInput as as, type PersonDeletedEventData as at, type PersonDocumentInput as au, type PersonEnrolledEventData as av, type PersonRef as aw, type PersonSession as ax, type PersonSessionInput as ay, type PersonSessionTarget as az, type ServiceId as b, type SessionHandoff as b0, type SessionHandoffDevice as b1, type SessionLifecycleEventData as b2, type SessionLinkDelivery as b3, type SessionLinkExpiry as b4, type SessionLinkInput as b5, type SessionNetwork as b6, type SessionNetworkEvent as b7, type SessionNotVerifiedEventData as b8, type SessionRetakeRequestedEventData as b9, type SubjectReuseTarget as bA, type SubjectStatus as bB, type UpdateSignalInput as bC, type UsageThresholdReachedEventData as bD, type VerifiedContacts as bE, type WebhookEnvelopeOf as bF, type WebhookEventDataMap as bG, type SessionReviewPendingEventData as ba, type SessionScreening as bb, type SessionStatus as bc, type SessionStep as bd, type SessionStepAttempts as be, type SessionStepBand as bf, type SessionStepDecision as bg, type SessionStepDocument as bh, type SessionStepPortrait as bi, type SessionVerifiedEventData as bj, SessionsApi as bk, type Signal as bl, type SignalEventData as bm, type SignalEvidence as bn, type SignalGrade as bo, type SignalKeyKind as bp, type SignalKind as bq, type SignalSeverity as br, type SignalStatus as bs, SignalsApi as bt, type SimulateSessionInput as bu, type StepResult as bv, type SubjectAssurance as bw, type SubjectIdNumber as bx, type SubjectName as by, type SubjectReferenceSource as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
2970
+ export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type SessionEventDataBase as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityBirthPlace as a3, type IdentityDocument as a4, type IdentityIdNumber as a5, type IdentityMethod as a6, type IdentityName as a7, type IdentityScalarKey as a8, type IdentitySource as a9, type PersonSuspiciousActivityEventData as aA, type PersonUpdatedEventData as aB, type PortraitReportEntry as aC, type PriorReviewReason as aD, type ProbeBindingReason as aE, type ProbeQuality as aF, type ProfileDocumentType as aG, type ReadinessProtection as aH, type ReadinessReport as aI, type RequestOptions as aJ, type ResultTokenResponse as aK, type ReviewOutcomeReason as aL, type RevokePersonInput as aM, type ScreenPersonInput as aN, type Screening as aO, type ScreeningHit as aP, type ScreeningHitSummary as aQ, type ScreeningList as aR, type ScreeningStatus as aS, type ScreeningTrigger as aT, type ScreeningUnavailableReason as aU, type SekyroOptions as aV, SekyroTestApi as aW, type Session as aX, type SessionClosedEventDataBase as aY, type SessionDecidingStep as aZ, type SessionDevice as a_, type IdentitySources as aa, type LevelTarget as ab, type LiftBlockInput as ac, type ListBlocksQuery as ad, type ListPeopleQuery as ae, type ListScreeningsQuery as af, type ListSessionsQuery as ag, type ListSignalsQuery as ah, type MatchReason as ai, type MediaBytes as aj, type MediaBytesOptions as ak, type MediaItem as al, type MediaKind as am, type MediaList as an, type NameForm as ao, type Page as ap, PeopleApi as aq, type Person as ar, type PersonBirthPlaceInput as as, type PersonDeletedEventData as at, type PersonDocumentInput as au, type PersonEnrolledEventData as av, type PersonRef as aw, type PersonSession as ax, type PersonSessionInput as ay, type PersonSessionTarget as az, type ServiceId as b, type SessionEventStep as b0, type SessionFailureReason as b1, type SessionFlowRef as b2, type SessionHandoff as b3, type SessionHandoffDevice as b4, type SessionLifecycleEventData as b5, type SessionLinkDelivery as b6, type SessionLinkExpiry as b7, type SessionLinkInput as b8, type SessionNetwork as b9, type SubjectAssurance as bA, type SubjectIdNumber as bB, type SubjectName as bC, type SubjectReferenceSource as bD, type SubjectReuseTarget as bE, type SubjectStatus as bF, type UpdateSignalInput as bG, type UsageThresholdReachedEventData as bH, type VerifiedContacts as bI, type WebhookEnvelopeOf as bJ, type WebhookEventDataMap as bK, type WebhookTestInput as bL, type WebhookTestResult as bM, WebhooksApi as bN, type SessionNetworkEvent as ba, type SessionNotVerifiedEventData as bb, type SessionRetakeRequestedEventData as bc, type SessionReviewPendingEventData as bd, type SessionScreening as be, type SessionStatus as bf, type SessionStep as bg, type SessionStepAttempts as bh, type SessionStepBand as bi, type SessionStepDecision as bj, type SessionStepDocument as bk, type SessionStepPortrait as bl, SessionTestApi as bm, type SessionVerifiedEventData as bn, SessionsApi as bo, type Signal as bp, type SignalEventData as bq, type SignalEvidence as br, type SignalGrade as bs, type SignalKeyKind as bt, type SignalKind as bu, type SignalSeverity as bv, type SignalStatus as bw, SignalsApi as bx, type SimulateSessionInput as by, type StepResult as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-D97yp6iq.cjs';
2
- import '../../client-DkpEJOBk.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-Cs-y1iL9.cjs';
2
+ import '../../client-B0zqD-HZ.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-CiZVHNOR.js';
2
- import '../../client-DkpEJOBk.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-CPyS23b7.js';
2
+ import '../../client-B0zqD-HZ.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-D97yp6iq.cjs';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-DkpEJOBk.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-Cs-y1iL9.cjs';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-B0zqD-HZ.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-CiZVHNOR.js';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-DkpEJOBk.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-CPyS23b7.js';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-B0zqD-HZ.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-D97yp6iq.cjs';
2
- import '../../client-DkpEJOBk.cjs';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-Cs-y1iL9.cjs';
2
+ import '../../client-B0zqD-HZ.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-CiZVHNOR.js';
2
- import '../../client-DkpEJOBk.js';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-CPyS23b7.js';
2
+ import '../../client-B0zqD-HZ.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-DkpEJOBk.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-B0zqD-HZ.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -468,7 +468,7 @@ interface Connector {
468
468
  * const connector = createConnector({
469
469
  * sekyro: new Sekyro({ apiKey: process.env.SEKYRO_API_KEY! }),
470
470
  * appId: process.env.SEKYRO_APP_ID!,
471
- * env: "live",
471
+ * env: process.env.SEKYRO_ENV as "live" | "sandbox", // "sandbox" with an sk_test_ key
472
472
  * webhookSecret: process.env.SEKYRO_WEBHOOK_SECRET!,
473
473
  * provider,
474
474
  * });
@@ -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-DkpEJOBk.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-B0zqD-HZ.cjs';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -468,7 +468,7 @@ interface Connector {
468
468
  * const connector = createConnector({
469
469
  * sekyro: new Sekyro({ apiKey: process.env.SEKYRO_API_KEY! }),
470
470
  * appId: process.env.SEKYRO_APP_ID!,
471
- * env: "live",
471
+ * env: process.env.SEKYRO_ENV as "live" | "sandbox", // "sandbox" with an sk_test_ key
472
472
  * webhookSecret: process.env.SEKYRO_WEBHOOK_SECRET!,
473
473
  * provider,
474
474
  * });
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.17";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"))}async simulate(id,input,opts={}){return assertId("sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},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)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;#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),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")}};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});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.18";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});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-DkpEJOBk.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 DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as PersonSuspiciousActivityEventData, aB as PersonUpdatedEventData, aC as PortraitReportEntry, aD as PriorReviewReason, aE as ProbeBindingReason, aF as ProbeQuality, aG as ProfileDocumentType, aH as RequestOptions, aI as ResultTokenResponse, aJ as ReviewOutcomeReason, aK as RevokePersonInput, aL as ScreenPersonInput, aM as Screening, aN as ScreeningHit, aO as ScreeningHitSummary, aP as ScreeningList, aQ as ScreeningStatus, aR as ScreeningTrigger, aS as ScreeningUnavailableReason, a as Sekyro, aT as SekyroOptions, aU as Session, aV as SessionClosedEventDataBase, aW as SessionDecidingStep, aX as SessionDevice, aY as SessionEventDataBase, aZ as SessionEventStep, a_ as SessionFailureReason, a$ as SessionFlowRef, b0 as SessionHandoff, b1 as SessionHandoffDevice, b2 as SessionLifecycleEventData, b3 as SessionLinkDelivery, b4 as SessionLinkExpiry, b5 as SessionLinkInput, b6 as SessionNetwork, b7 as SessionNetworkEvent, b8 as SessionNotVerifiedEventData, S as SessionReason, b9 as SessionRetakeRequestedEventData, ba as SessionReviewPendingEventData, bb as SessionScreening, bc as SessionStatus, bd as SessionStep, be as SessionStepAttempts, bf as SessionStepBand, bg as SessionStepDecision, bh as SessionStepDocument, bi as SessionStepPortrait, bj as SessionVerifiedEventData, bk as SessionsApi, bl as Signal, bm as SignalEventData, bn as SignalEvidence, bo as SignalGrade, bp as SignalKeyKind, bq as SignalKind, br as SignalSeverity, bs as SignalStatus, bt as SignalsApi, bu as SimulateSessionInput, bv as StepResult, bw as SubjectAssurance, bx as SubjectIdNumber, by as SubjectName, bz as SubjectReferenceSource, bA as SubjectReuseTarget, bB as SubjectStatus, bC as UpdateSignalInput, bD as UsageThresholdReachedEventData, bE as VerifiedContacts, bF as WebhookEnvelopeOf, bG as WebhookEventDataMap, W as WebhookEventType } from './client-DkpEJOBk.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-B0zqD-HZ.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 DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as PersonSuspiciousActivityEventData, aB as PersonUpdatedEventData, aC as PortraitReportEntry, aD as PriorReviewReason, aE as ProbeBindingReason, aF as ProbeQuality, aG as ProfileDocumentType, aH as ReadinessProtection, aI as ReadinessReport, aJ as RequestOptions, aK as ResultTokenResponse, aL as ReviewOutcomeReason, aM as RevokePersonInput, aN as ScreenPersonInput, aO as Screening, aP as ScreeningHit, aQ as ScreeningHitSummary, aR as ScreeningList, aS as ScreeningStatus, aT as ScreeningTrigger, aU as ScreeningUnavailableReason, a as Sekyro, aV as SekyroOptions, aW as SekyroTestApi, aX as Session, aY as SessionClosedEventDataBase, aZ as SessionDecidingStep, a_ as SessionDevice, a$ as SessionEventDataBase, b0 as SessionEventStep, b1 as SessionFailureReason, b2 as SessionFlowRef, b3 as SessionHandoff, b4 as SessionHandoffDevice, b5 as SessionLifecycleEventData, b6 as SessionLinkDelivery, b7 as SessionLinkExpiry, b8 as SessionLinkInput, b9 as SessionNetwork, ba as SessionNetworkEvent, bb as SessionNotVerifiedEventData, S as SessionReason, bc as SessionRetakeRequestedEventData, bd as SessionReviewPendingEventData, be as SessionScreening, bf as SessionStatus, bg as SessionStep, bh as SessionStepAttempts, bi as SessionStepBand, bj as SessionStepDecision, bk as SessionStepDocument, bl as SessionStepPortrait, bm as SessionTestApi, bn as SessionVerifiedEventData, bo as SessionsApi, bp as Signal, bq as SignalEventData, br as SignalEvidence, bs as SignalGrade, bt as SignalKeyKind, bu as SignalKind, bv as SignalSeverity, bw as SignalStatus, bx as SignalsApi, by as SimulateSessionInput, bz as StepResult, bA as SubjectAssurance, bB as SubjectIdNumber, bC as SubjectName, bD as SubjectReferenceSource, bE as SubjectReuseTarget, bF as SubjectStatus, bG as UpdateSignalInput, bH as UsageThresholdReachedEventData, bI as VerifiedContacts, bJ as WebhookEnvelopeOf, bK as WebhookEventDataMap, W as WebhookEventType, bL as WebhookTestInput, bM as WebhookTestResult, bN as WebhooksApi } from './client-B0zqD-HZ.cjs';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";