@sekyro/node 0.1.0-rc.7 → 0.1.0-rc.9

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.
@@ -60,6 +60,28 @@ interface ResultCheckProofs {
60
60
  captureProof: "verified" | "missing";
61
61
  injectionSignals: "clear" | "flagged";
62
62
  }
63
+ /**
64
+ * How a session proved the person's minimum age: `estimated` (the age check
65
+ * (selfie) step estimated the face over the threshold by a safety margin), or
66
+ * from identity data: `document`, `chip`, `registry` or `eid`.
67
+ * @public
68
+ */
69
+ type AgeMethod = "estimated" | "document" | "chip" | "registry" | "eid";
70
+ /**
71
+ * The age answer of a session whose flow sets a minimum age. `over` is the
72
+ * flow's minimum age (the threshold), never the person's age. `estimate`
73
+ * (years, one decimal) and `sigma` (its spread in years) are present only on
74
+ * the API session and webhooks, and only when the age check (selfie) step's
75
+ * "Keep and show the estimated age" setting is on; the result token never
76
+ * carries them.
77
+ * @public
78
+ */
79
+ interface AgeResult {
80
+ over: number;
81
+ method: AgeMethod;
82
+ estimate?: number;
83
+ sigma?: number;
84
+ }
63
85
  /** Another subject the person's face already matched (duplicate search). @public */
64
86
  interface ResultDuplicate {
65
87
  subjectId: string;
@@ -130,17 +152,29 @@ type DecisionReason = "liveness_inconclusive" | "match_inconclusive" | "document
130
152
  * a clearer photo; population_registry: terminal).
131
153
  * @public
132
154
  */
133
- type EligibilityReason = "document_type_not_accepted" | "nationality_not_allowed" | "underage" | "age_unverifiable";
155
+ type EligibilityReason = "document_type_not_accepted" | "nationality_not_allowed" | "underage" | "age_unverifiable" | "underage_estimated";
134
156
  /**
135
157
  * Why a profile-v2 policy ended a session: a session-level
136
158
  * {@link SessionFailureReason} (location / anonymizer gate), or the failed
137
159
  * check's policy reason — an {@link EligibilityReason} or
138
- * `document_nni_mismatch` (the document belongs to someone other than the
139
- * NNI the session was created for), or `camera_unavailable` (spec 2026-10-29 §3.4: the person had no usable camera,
160
+ * `document_id_number_mismatch` (the document belongs to someone other than the
161
+ * ID number the session was created for; `document_nni_mismatch` is its former
162
+ * name, still sent until the API switches to the new names), or `camera_unavailable` (spec 2026-10-29 §3.4: the person had no usable camera,
140
163
  * so the live step ended without a capture; the session is rejected at level 0 unless your flow has a fallback).
141
164
  * @public
142
165
  */
143
- type PolicyFailureReason = SessionFailureReason | EligibilityReason | "document_nni_mismatch" | "camera_unavailable";
166
+ type PolicyFailureReason = SessionFailureReason | EligibilityReason | "document_id_number_mismatch" | "document_nni_mismatch" | "camera_unavailable";
167
+ /**
168
+ * The ID-number reasons a check's {@link SessionStep.reason} may carry (person data
169
+ * spec Appendix A.2), each under its generic name and its former Mauritanian name:
170
+ * `id_number_invalid` (`nni_invalid`: the number fails its country's rule),
171
+ * `registry_record_not_found` (`nni_not_found`: no registry record for the number),
172
+ * `id_number_recheck` (`nni_recheck`: the number must be checked again) and
173
+ * `document_id_number_mismatch` (`document_nni_mismatch`). The API sends the former
174
+ * names until it switches to the generic ones; handle both.
175
+ * @public
176
+ */
177
+ type IdNumberReason = "id_number_invalid" | "nni_invalid" | "registry_record_not_found" | "nni_not_found" | "id_number_recheck" | "nni_recheck" | "document_id_number_mismatch" | "document_nni_mismatch";
144
178
  /**
145
179
  * Why the person had no camera (spec 2026-10-29 §3.4, 2026-10-30), when the SDK said: `denied` (the
146
180
  * person refused camera access) or `no_camera` (no usable camera: none found, an insecure page or a
@@ -256,29 +290,90 @@ interface SessionPortraitLink {
256
290
  interface DeliverOptions {
257
291
  /** Delivery channel. */
258
292
  channel: "sms" | "whatsapp";
259
- /** E.164 phone number of the recipient, e.g. `+22236123456`. */
293
+ /** E.164 phone number of the recipient (`+` and the country code). */
260
294
  to: string;
261
295
  }
296
+ /**
297
+ * An ID number of the person (person data spec §4.1): the document type, the
298
+ * issuing country (ISO 3166-1 alpha-2; alpha-3 is accepted and normalized) and
299
+ * the number (1 to 40 characters, then the issuing country's rule, e.g. the
300
+ * check digit of a Mauritanian national ID number).
301
+ * @public
302
+ */
303
+ interface SubjectIdNumber {
304
+ type: "national_id" | "passport" | "residence_permit";
305
+ issuingCountry: string;
306
+ number: string;
307
+ }
308
+ /**
309
+ * The person's name in one script (ISO 15924 code, e.g. `Latn` or `Arab`).
310
+ * @public
311
+ */
312
+ interface SubjectName {
313
+ script: string;
314
+ /** 1 to 100 characters. */
315
+ given: string;
316
+ /** 1 to 100 characters. */
317
+ family: string;
318
+ /** Optional, 1 to 100 characters. */
319
+ patronymic?: string;
320
+ }
262
321
  /**
263
322
  * What you already know about the person (`subject` at session create). A
264
323
  * closed object: unknown keys are refused (`400`). Every field is optional;
265
- * `null` or blank counts as absent. Identity fields are compared with the
266
- * person's document or registry record when the app's profile turns name
267
- * matching on; `nni` binds the session to that identity.
324
+ * `null` or blank counts as absent.
325
+ *
326
+ * The flow decides whether these are checked or believed: in a flow that checks
327
+ * identity from a document or a registry, they are a prefill compared with what
328
+ * the person shows; in a flow that verifies identity from your data (the
329
+ * response's `subjectUse: "reference"`), `idNumber`, `birthDate`, `photo` and
330
+ * `fetchedAt` are required and the record is the reference. `idNumber` binds the
331
+ * session to that identity in both cases: the hosted flow may omit it but cannot
332
+ * substitute another number.
268
333
  * @public
269
334
  */
270
335
  interface SessionSubjectInput {
271
- /** 10-digit Mauritanian NNI, as a string. */
336
+ /** The person's ID number. Binds the session. */
337
+ idNumber?: SubjectIdNumber;
338
+ /**
339
+ * @deprecated Use `idNumber: { type: "national_id", issuingCountry: "MR", number }`.
340
+ * A Mauritanian national ID number (10 digits), as a string.
341
+ */
272
342
  nni?: string;
273
- /** E.164 phone number, e.g. `+22236123456`. */
343
+ /** E.164 phone number (`+` and the country code). */
274
344
  phone?: string;
345
+ /** Email address, for the email OTP step. */
346
+ email?: string;
347
+ /** Full name, 1 to 200 characters, any script. */
275
348
  fullName?: string;
349
+ /** The name per script, at most 4 entries, one per script. */
350
+ names?: SubjectName[];
276
351
  /** ISO 8601 date (`YYYY-MM-DD`). */
277
352
  birthDate?: string;
278
- /** ISO 3166-1 alpha-2, e.g. `MR`. */
353
+ /** Place of birth, 1 to 120 characters, any script (kept only with a reference record). */
354
+ birthPlace?: string;
355
+ /** `M`, `F` or `X` (ICAO 9303 values; kept only with a reference record). */
356
+ sex?: "M" | "F" | "X";
357
+ /** ISO 3166-1 alpha-2. */
279
358
  nationality?: string;
280
- /** Identity-document number (1–40 characters). */
359
+ /**
360
+ * @deprecated Use `idNumber` with the document's `type` and `issuingCountry`.
361
+ * Identity-document number (1 to 40 characters).
362
+ */
281
363
  documentNumber?: string;
364
+ /**
365
+ * Base64 JPEG or PNG (optional data-URL prefix, at most 1 MB decoded): the
366
+ * face-match reference of a reference record. Refused in a flow that uses the
367
+ * data as a prefill (`422 subject_photo_not_used`).
368
+ */
369
+ photo?: string;
370
+ /** ISO 8601 date (`YYYY-MM-DD`) of the photo. */
371
+ photoDate?: string;
372
+ /**
373
+ * ISO 8601 date-time: when YOUR system obtained this data. Required with a
374
+ * reference record; at most 24 h old (`422 subject_record_stale`).
375
+ */
376
+ fetchedAt?: string;
282
377
  /**
283
378
  * Your own id for this person (1–128 characters). Echoed on the session and
284
379
  * its webhooks, and searchable on the subjects API.
@@ -306,9 +401,11 @@ interface SubjectReuseDocument {
306
401
  number: string;
307
402
  }
308
403
  /**
309
- * Which subject a returning-user session re-verifies — exactly ONE of the
310
- * subject id, your own `externalRef` (must match a single subject), the NNI
311
- * or an identity document the person verified with.
404
+ * Which subject a returning-user session re-verifies: exactly ONE of the
405
+ * subject id, your own `externalRef` (must match a single subject) or the
406
+ * `idNumber` the person verified with. `nni` and `document` are the deprecated
407
+ * names of the `idNumber` target: an `nni` is an `idNumber` of type
408
+ * `national_id` issued by `MR`; a `document` has the same three parts.
312
409
  * @public
313
410
  */
314
411
  type SubjectReuseTarget = ({
@@ -316,21 +413,33 @@ type SubjectReuseTarget = ({
316
413
  externalRef?: never;
317
414
  nni?: never;
318
415
  document?: never;
416
+ idNumber?: never;
319
417
  } | {
320
418
  externalRef: string;
321
419
  subjectId?: never;
322
420
  nni?: never;
323
421
  document?: never;
422
+ idNumber?: never;
324
423
  } | {
424
+ /** @deprecated Use `idNumber` with type `national_id` and issuing country `MR`. */
325
425
  nni: string;
326
426
  subjectId?: never;
327
427
  externalRef?: never;
328
428
  document?: never;
429
+ idNumber?: never;
329
430
  } | {
431
+ /** @deprecated Use `idNumber` (the same three parts). */
330
432
  document: SubjectReuseDocument;
331
433
  subjectId?: never;
332
434
  externalRef?: never;
333
435
  nni?: never;
436
+ idNumber?: never;
437
+ } | {
438
+ idNumber: SubjectIdNumber;
439
+ subjectId?: never;
440
+ externalRef?: never;
441
+ nni?: never;
442
+ document?: never;
334
443
  }) & {
335
444
  /**
336
445
  * `recheck` (default) or `step_up` ({@link SubjectReuseMode}). `step_up` on
@@ -348,7 +457,7 @@ type ProfileDocumentType = "carte_identite" | "passport" | "residence_permit";
348
457
  * portrait).
349
458
  * @public
350
459
  */
351
- type ServiceId = "device_network" | "phone_otp" | "email_otp" | "national_eid" | "document" | "nfc" | "population_registry" | "supplied_identity" | "summary_confirm" | "liveness" | "face_match" | "aml_screening" | "face_dedup";
460
+ type ServiceId = "device_network" | "phone_otp" | "email_otp" | "national_eid" | "document" | "nfc" | "population_registry" | "supplied_identity" | "summary_confirm" | "liveness" | "face_match" | "aml_screening" | "face_dedup" | "age_estimation";
352
461
  /**
353
462
  * The general settings of a flow that a session may override (the flow's
354
463
  * `link`, `language` and override policy are not overridable). Country codes
@@ -490,7 +599,13 @@ interface FlowServiceSettings {
490
599
  population_registry: {
491
600
  /** `'org'` (every registry the org can use, resolved at session create) or registry ids. */
492
601
  sources: "org" | Array<"MR.anrpts">;
602
+ /**
603
+ * @deprecated Use `idNumberSource` (same values). Both with different values is
604
+ * `400 override_invalid`.
605
+ */
493
606
  nniSource: "auto" | "typed" | "bound_only";
607
+ /** Where the ID number comes from: `auto`, `typed` (the person types it) or `bound_only` (your `subject.idNumber`). */
608
+ idNumberSource: "auto" | "typed" | "bound_only";
494
609
  onUncovered: "skip";
495
610
  attempts?: number;
496
611
  };
@@ -516,6 +631,11 @@ interface FlowServiceSettings {
516
631
  scope: "app" | "org";
517
632
  onDuplicate: "review" | "fail";
518
633
  };
634
+ /** The age check (selfie); the threshold is the flow's `eligibility.minAge`. */
635
+ age_estimation: {
636
+ /** Keep and show the estimated age ({@link AgeResult.estimate}) on the API session and webhooks. Default `false`. */
637
+ showEstimatedAge?: boolean;
638
+ };
519
639
  }
520
640
  /**
521
641
  * `T` with every property optional, recursively. Arrays are replaced as a
@@ -639,48 +759,49 @@ interface CreateSessionInput {
639
759
  */
640
760
  overrides?: FlowOverrides;
641
761
  /**
642
- * Step inputs consumed server-side. The known anchors are typed (all
643
- * strings — an `nni` is a 10-digit string, never a number); further keys
644
- * pass through to the API as-is. `nni` binds the session to that identity:
645
- * the hosted flow may omit it but cannot substitute another.
762
+ * Step inputs consumed server-side: an open record of branch facts your flow's
763
+ * conditions read. The person keys below are deprecated: send them in
764
+ * {@link CreateSessionInput.subject} (the response's `warnings` names each one
765
+ * you used). Values are strings (a number is a string, never a JSON number).
646
766
  */
647
767
  input?: {
648
- /** 10-digit Mauritanian NNI, as a string. */
768
+ /**
769
+ * @deprecated Use `subject.idNumber: { type: "national_id", issuingCountry: "MR", number }`.
770
+ * A Mauritanian national ID number (10 digits), as a string.
771
+ */
649
772
  nni?: string;
650
- /** E.164 phone number, e.g. `+22236123456`. */
773
+ /** @deprecated Use `subject.phone`. E.164 phone number. */
651
774
  phone?: string;
652
- /** Email address for the email OTP step (`emailSource` `prefilled` / `prefilled_or_entered`). */
775
+ /** @deprecated Use `subject.email`. Email address for the email OTP step. */
653
776
  email?: string;
777
+ /** @deprecated Use `subject.fullName`. */
654
778
  fullName?: string;
655
- /** ISO 8601 date (`YYYY-MM-DD`). */
779
+ /** @deprecated Use `subject.birthDate`. ISO 8601 date (`YYYY-MM-DD`). */
656
780
  birthDate?: string;
657
781
  /**
658
- * Partner-supplied identity data (`supplied` mode only): the person's
659
- * biographic record and photo as YOUR system holds them — for example
660
- * from your own ANRPTS answer, converted with {@link registryFromAnrpts}.
661
- * Sekyro AI stores it as data you vouch for, makes no registry call, and
662
- * never receives or stores any registry key. `nni` must be set too and
663
- * equal `suppliedIdentity.nni`. Refused unless Sekyro AI enabled the mode
664
- * for the environment (`403 supplied_identity_not_entitled`); required in
665
- * that mode when the app verifies identity (`422 supplied_identity_required`).
782
+ * @deprecated Use the reference keys of `subject` (`idNumber`, `names`,
783
+ * `birthDate`, `photo`, `fetchedAt`, ...), for example from
784
+ * {@link subjectFromNationalRegistry}.
785
+ * Partner-supplied identity data (`supplied` mode only).
666
786
  */
667
787
  suppliedIdentity?: SuppliedIdentityRecord;
668
788
  } & Record<string, unknown>;
669
789
  }
670
790
  /**
791
+ * @deprecated Send the record in `subject` instead (`idNumber`, `names`,
792
+ * `birthDate`, `birthPlace`, `sex`, `nationality`, `photo`, `photoDate`,
793
+ * `fetchedAt`), for example from {@link subjectFromNationalRegistry}.
794
+ *
671
795
  * Partner-supplied identity data (`sessions.create` `input.suppliedIdentity`):
672
796
  * the person's biographic record and photo, as your organization holds them.
673
- * Sekyro AI treats it as identity data supplied by your organization, not as
674
- * a registry lookup. Refusals at create: `400 supplied_identity_nni_mismatch`,
797
+ * Refusals at create: `400 supplied_identity_nni_mismatch`,
675
798
  * `422 supplied_identity_stale` (`fetchedAt` older than 24 h),
676
799
  * `422 supplied_identity_photo_unusable` (not a JPEG/PNG of at most 1 MB within the
677
- * size bounds). In a `supplied` environment whose app verifies identity, a create
678
- * without `input.suppliedIdentity` is `422 supplied_identity_required`. The face on
679
- * the photo is checked after consent, at the face match (`no_face_reference`).
800
+ * size bounds).
680
801
  * @public
681
802
  */
682
803
  interface SuppliedIdentityRecord {
683
- /** 10-digit NNI, as a string. */
804
+ /** 10-digit national ID number, as a string. */
684
805
  nni: string;
685
806
  firstNameFr: string;
686
807
  lastNameFr: string;
@@ -693,7 +814,7 @@ interface SuppliedIdentityRecord {
693
814
  birthPlaceFr?: string;
694
815
  birthPlaceAr?: string;
695
816
  sex?: "M" | "F";
696
- /** Nationality text as your source holds it (e.g. `Mauritanienne`). */
817
+ /** Nationality text as your source holds it. */
697
818
  nationalities?: string[];
698
819
  /** Base64 JPEG or PNG (at most 1 MB decoded). */
699
820
  photo: string;
@@ -730,6 +851,25 @@ interface CreatedSession {
730
851
  expiresAt: string;
731
852
  /** The levels the flow can reach on its paths; absent from older API versions. */
732
853
  levelTarget?: LevelTarget;
854
+ /**
855
+ * How the flow uses the person data you sent: `reference` (believed, your
856
+ * record is the identity reference) or `prefill` (checked against the
857
+ * person's document or registry record). Absent from older API versions.
858
+ */
859
+ subjectUse?: "reference" | "prefill";
860
+ /** One entry per deprecated request key you used, naming its replacement. Absent otherwise. */
861
+ warnings?: CreatedSessionWarning[];
862
+ }
863
+ /**
864
+ * A deprecation warning of {@link CreatedSession.warnings}: `field` is the
865
+ * deprecated key you sent (e.g. `input.nni`), `replacement` the key to send
866
+ * instead (e.g. `subject.idNumber`).
867
+ * @public
868
+ */
869
+ interface CreatedSessionWarning {
870
+ code: "deprecated_field";
871
+ field: string;
872
+ replacement: string;
733
873
  }
734
874
  /**
735
875
  * Input of {@link SubjectsApi.createSession}: a re-check or step-up session
@@ -841,7 +981,7 @@ interface EidResult {
841
981
  interface VerifiedContacts {
842
982
  /** From a passed `phone_otp` check. */
843
983
  phone?: {
844
- /** E.164, e.g. `+22236123456`. */
984
+ /** E.164 (`+` and the country code). */
845
985
  number: string;
846
986
  /** The channel the code was delivered on. */
847
987
  channel: "whatsapp" | "sms";
@@ -944,6 +1084,11 @@ interface Session {
944
1084
  verifiedContacts?: VerifiedContacts;
945
1085
  /** The national eID that verified this session (the `eid_auth` check passed); absent otherwise. */
946
1086
  eid?: EidResult;
1087
+ /**
1088
+ * When the flow sets a minimum age and the session proved it: the threshold
1089
+ * and how it was proved ({@link AgeResult}). Absent otherwise.
1090
+ */
1091
+ age?: AgeResult;
947
1092
  /**
948
1093
  * ID mode (`portrait.purpose = id_document`) only: the ICAO portrait can be
949
1094
  * fetched with {@link SessionsApi.portrait}.
@@ -1037,6 +1182,8 @@ interface SessionLifecycleEventData {
1037
1182
  verifiedContacts?: VerifiedContacts;
1038
1183
  /** On `completed` / `failed`: the national eID that verified this session, when one did. */
1039
1184
  eid?: EidResult;
1185
+ /** On `completed` / `failed`: the minimum age the session proved and how ({@link AgeResult}), when the flow sets one. */
1186
+ age?: AgeResult;
1040
1187
  /**
1041
1188
  * ID mode only, on `completed` / `failed`: the ICAO portrait can be fetched
1042
1189
  * with {@link SessionsApi.portrait} (the event never carries the image).
@@ -1264,6 +1411,27 @@ interface SessionReviewDecidedEventData {
1264
1411
  /** ID mode only: the ICAO portrait can be fetched with {@link SessionsApi.portrait}. */
1265
1412
  portraitAvailable?: boolean;
1266
1413
  }
1414
+ /**
1415
+ * `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
1416
+ * plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
1417
+ * tier, or the alert, e.g. `credit_80`, `usage_100_paid`, `spend_cap_reached`.
1418
+ * @public
1419
+ */
1420
+ interface UsageThresholdReachedEventData {
1421
+ kind: string;
1422
+ /** The verification unit, on per-unit alerts. */
1423
+ unit?: "human_verification" | "identity_verification";
1424
+ /** Percent of the limit (80, 100), or `overage` for the first verification beyond a tier. */
1425
+ threshold?: number | "overage";
1426
+ used?: number;
1427
+ limit?: number;
1428
+ /** UTC month, `YYYY-MM`. */
1429
+ period?: string;
1430
+ /** Tier alerts: verifications that reached a result this month. */
1431
+ confirmed?: number;
1432
+ /** Tier alerts: verifications beyond the tier this month. */
1433
+ overage?: number;
1434
+ }
1267
1435
  /**
1268
1436
  * Event type → the shape of its `data`. Session events are typed; the
1269
1437
  * remaining events carry an open record until their payloads are frozen.
@@ -1287,6 +1455,7 @@ interface WebhookEventDataMap {
1287
1455
  "invoice.generated": Record<string, unknown>;
1288
1456
  "invoice.paid": Record<string, unknown>;
1289
1457
  "invoice.overdue": Record<string, unknown>;
1458
+ "usage.threshold_reached": UsageThresholdReachedEventData;
1290
1459
  "webhook.test": Record<string, unknown>;
1291
1460
  }
1292
1461
  /** Every event a partner endpoint may receive. @public */
@@ -1482,4 +1651,4 @@ declare class Sekyro {
1482
1651
  listFlows(): Promise<FlowSummary[]>;
1483
1652
  }
1484
1653
 
1485
- export { type SessionLifecycleEventData as $, type ListSessionsQuery as A, type PortraitReportEntry as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type EidResult as E, type FetchLike as F, type ProbeBindingReason as G, type ProbeQuality as H, type IdentityMethod as I, type ProfileDocumentType as J, type RequestOptions as K, type Locale as L, type MatchReason as M, type ResultTokenResponse as N, type RevokeSubjectInput as O, type PolicyFailureReason as P, type SekyroOptions as Q, type ResultRisk as R, Sekyro as S, type Session as T, type SessionDevice as U, type VerificationLevel as V, type WebhookEventType as W, type SessionDeviceSignal as X, type SessionEventData as Y, type SessionFailureReason as Z, type SessionFlowRef as _, type ServiceId as a, type SessionLinkInput as a0, type SessionNetwork as a1, type SessionNetworkEvent as a2, type SessionPortraitLink as a3, type SessionReviewDecidedEventData as a4, type SessionStatus as a5, type SessionStep as a6, type SessionStepCompletedEventData as a7, type SessionSubjectInput as a8, SessionsApi as a9, type Subject as aa, type SubjectAssurance as ab, type SubjectDeletedEventData as ac, type SubjectEnrolledEventData as ad, type SubjectReferenceSource as ae, type SubjectReuseDocument as af, type SubjectReuseTarget as ag, type SubjectSession as ah, type SubjectSessionInput as ai, type SubjectSessionTarget as aj, type SubjectStatus as ak, type SubjectSuspiciousActivityEventData as al, type SubjectUpdatedEventData as am, SubjectsApi as an, type VerifiedContacts as ao, type WebhookEnvelopeOf as ap, type WebhookEventDataMap as aq, type SuppliedIdentityRecord as b, type WebhookEnvelope as c, type SekyroEnvironment as d, type VerificationAssurance as e, type SessionOutcome as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type ResultDuplicate as j, type CameraUnavailableCause as k, type CheckState as l, type CheckType as m, type CreateSessionInput as n, DEFAULT_TIMEOUT_MS as o, type DecisionReason as p, type DeepPartial as q, type DeletedSubject as r, type DeliverOptions as s, type DocumentSubstitutionSettings as t, type EligibilityReason as u, type FlowOverridableSettings as v, type FlowOverrides as w, type FlowServiceSettings as x, type FlowSummary as y, type LevelTarget as z };
1654
+ export { type SessionDeviceSignal as $, type AgeMethod as A, type FlowSummary as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type EidResult as E, type FetchLike as F, type IdentityMethod as G, type LevelTarget as H, type IdNumberReason as I, type ListSessionsQuery as J, type PortraitReportEntry as K, type Locale as L, type MatchReason as M, type ProbeBindingReason as N, type ProbeQuality as O, type PolicyFailureReason as P, type ProfileDocumentType as Q, type ResultRisk as R, Sekyro as S, type RequestOptions as T, type ResultTokenResponse as U, type VerificationLevel as V, type WebhookEventType as W, type RevokeSubjectInput as X, type SekyroOptions as Y, type Session as Z, type SessionDevice as _, type ServiceId as a, type SessionEventData as a0, type SessionFailureReason as a1, type SessionFlowRef as a2, type SessionLifecycleEventData as a3, type SessionLinkInput as a4, type SessionNetwork as a5, type SessionNetworkEvent as a6, type SessionPortraitLink as a7, type SessionReviewDecidedEventData as a8, type SessionStatus as a9, type SessionStep as aa, type SessionStepCompletedEventData as ab, SessionsApi as ac, type Subject as ad, type SubjectAssurance as ae, type SubjectDeletedEventData as af, type SubjectEnrolledEventData as ag, type SubjectIdNumber as ah, type SubjectName as ai, type SubjectReferenceSource as aj, type SubjectReuseDocument as ak, type SubjectReuseTarget as al, type SubjectSession as am, type SubjectSessionInput as an, type SubjectSessionTarget as ao, type SubjectStatus as ap, type SubjectSuspiciousActivityEventData as aq, type SubjectUpdatedEventData as ar, SubjectsApi as as, type SuppliedIdentityRecord as at, type UsageThresholdReachedEventData as au, type VerifiedContacts as av, type WebhookEnvelopeOf as aw, type WebhookEventDataMap as ax, type SessionSubjectInput as b, type WebhookEnvelope as c, type SekyroEnvironment as d, type VerificationAssurance as e, type SessionOutcome as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type ResultDuplicate as j, type AgeResult as k, type CameraUnavailableCause as l, type CheckState as m, type CheckType as n, type CreateSessionInput as o, type CreatedSessionWarning as p, DEFAULT_TIMEOUT_MS as q, type DecisionReason as r, type DeepPartial as s, type DeletedSubject as t, type DeliverOptions as u, type DocumentSubstitutionSettings as v, type EligibilityReason as w, type FlowOverridableSettings as x, type FlowOverrides as y, type FlowServiceSettings as z };
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-D1bhSLBl.cjs';
2
- import '../../client-DUMp_I-1.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-Bo0P3ytq.cjs';
2
+ import '../../client-BYoo67F-.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-CMHuC-CU.js';
2
- import '../../client-DUMp_I-1.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-B2vbywn2.js';
2
+ import '../../client-BYoo67F-.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, 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-D1bhSLBl.cjs';
2
- import '../client-DUMp_I-1.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, 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-Bo0P3ytq.cjs';
2
+ import '../client-BYoo67F-.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, 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-CMHuC-CU.js';
2
- import '../client-DUMp_I-1.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, 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-B2vbywn2.js';
2
+ import '../client-BYoo67F-.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-D1bhSLBl.cjs';
2
- import '../../client-DUMp_I-1.cjs';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-Bo0P3ytq.cjs';
2
+ import '../../client-BYoo67F-.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-CMHuC-CU.js';
2
- import '../../client-DUMp_I-1.js';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-B2vbywn2.js';
2
+ import '../../client-BYoo67F-.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/next`: gate helpers for Next.js middleware, route
@@ -1,4 +1,4 @@
1
- import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-DUMp_I-1.js';
1
+ import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-BYoo67F-.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -1,4 +1,4 @@
1
- import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-DUMp_I-1.cjs';
1
+ import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-BYoo67F-.cjs';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,registryFromAnrpts:()=>registryFromAnrpts,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",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 ANRPTS answer can't be used as a registry record"},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;retryable;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.retryable=isRetryable(init.status,init.code)}},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="0.1.0-rc.7";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4;function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{}}}var SUBJECT_ID_RE=/^[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.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}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;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}async call(method,path,body,idempotencyKey){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey);let init={method,headers,signal:AbortSignal.timeout(this.timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${this.timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init2.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init2.details=parsed.error.details),new SekyroApiError(init2)}throw new SekyroApiError({status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`})}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.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#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,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport))}async listFlows(){return this.#transport.call("GET","/flows")}};function registryFromAnrpts(response,options){let p=response?.personne??{},required=(field,value)=>{let s=text(value);if(s===void 0)throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the ANRPTS answer has no usable \`${field}\``);return s},birthDate=isoDay(p.dateNaissance);if(birthDate===void 0)throw new SekyroConfigError("invalid_registry_record","Sekyro AI: the ANRPTS answer has no usable `personne.dateNaissance`");let photo=required("photo",response?.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 ANRPTS answer) is missing or not a valid date");let record={nni:required("personne.nni",p.nni),firstNameFr:required("personne.prenomFr",p.prenomFr),lastNameFr:required("personne.patronymeFr",p.patronymeFr),firstNameAr:required("personne.prenomAr",p.prenomAr),lastNameAr:required("personne.patronymeAr",p.patronymeAr),birthDate,photo,fetchedAt:fetchedAt.toISOString()},optional=[["fatherNameFr",p.perePrenomFr],["fatherNameAr",p.perePrenomAr],["birthPlaceFr",p.lieuNaissanceFr],["birthPlaceAr",p.lieuNaissanceAr]];for(let[key,value]of optional){let s=text(value);s!==void 0&&(record[key]=s)}let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let nationalities=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0).slice(0,5):[];nationalities.length>0&&(record.nationalities=nationalities);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}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){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,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=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 r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;return c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup})),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);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(opts.env!==void 0&&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,registryFromAnrpts,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,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,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",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;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.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};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="0.1.0-rc.9";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4;function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{}}}var SUBJECT_ID_RE=/^[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.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}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;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}async call(method,path,body,idempotencyKey){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey);let init={method,headers,signal:AbortSignal.timeout(this.timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${this.timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init3={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init3.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init3.details=parsed.error.details),retryAfterSeconds!==void 0&&(init3.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init3)}let init2={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};throw retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}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.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#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,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport))}async listFlows(){return this.#transport.call("GET","/flows")}};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 subjectFromNationalRegistry(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.nationality=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){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,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=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 r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;return 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}),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);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(opts.env!==void 0&&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,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});