@sekyro/node 0.1.0-rc.13 → 0.1.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @sekyro/node
2
2
 
3
+ ## 0.1.0-rc.14
4
+
5
+ ### Minor Changes
6
+
7
+ - 4323262: `sekyro.blocks` creates, lists, checks and lifts blocks on devices, people, accounts and contacts. `sekyro.devices` reads a device and marks it shared. `sessions.list` filters by `deviceId`.
8
+
9
+ ### Patch Changes
10
+
11
+ - 96a3b2b: `SessionFailureReason` gains `blocked_by_org`: one of your blocks (a device, a person, an account or a contact) stopped the session. Not retryable, not billed. Nothing returns it until blocks are available to your organization.
12
+ - 6a58d80: Sessions carry `device.deviceId`, an opaque device identity inside your organization and environment.
13
+ - c3c8f3e: `Block.ruleId` is now a `rul_...` id and `Block.ruleVersion` is documented, on blocks made by an automatic rule. `ReviewReason` gains `org_rule`, for a review an organization rule asked for.
14
+
3
15
  ## 0.1.0-rc.13
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -415,7 +415,7 @@ same person, reference photo and face was reused; `sessionId` names your
415
415
  earlier session). `mode` is `single` or `dual`, `votes` counts the votes that
416
416
  formed it and `agreement` says whether two dual reviewers agreed. `reasons`
417
417
  (`ReviewReason[]`: `document_authenticity`, `liveness`, `face_match`,
418
- `data_mismatch`, `other`) says what failed on a rejection, or what was
418
+ `data_mismatch`, `screening`, `org_rule`, `other`) says what failed on a rejection, or what was
419
419
  overridden on an approval. The object never names a reviewer or a vote.
420
420
 
421
421
  A review that reaches its deadline ends with `session.failed`, `decidedBy:
@@ -138,10 +138,12 @@ type CheckState = "pending" | "input_required" | "processing" | "passed" | "fail
138
138
  * - `platform_unsupported` — the flow requires a chip read and the person
139
139
  * opened the link on the web (the link stays usable in a native app);
140
140
  * - `cancelled_by_organization` — you cancelled the session
141
- * ({@link SessionsApi.cancel}).
141
+ * ({@link SessionsApi.cancel});
142
+ * - `blocked_by_org`: one of your blocks (a device, a person, an account or a
143
+ * contact) stopped the session. Not retryable, not billed.
142
144
  * @public
143
145
  */
144
- type SessionFailureReason = "location_not_allowed" | "anonymizer_blocked" | "capture_tampered" | "device_velocity_exceeded" | "device_cooldown" | "platform_unsupported" | "cancelled_by_organization";
146
+ type SessionFailureReason = "location_not_allowed" | "anonymizer_blocked" | "capture_tampered" | "device_velocity_exceeded" | "device_cooldown" | "platform_unsupported" | "cancelled_by_organization" | "blocked_by_org";
145
147
  /**
146
148
  * Profile-v2 decision-mode reasons a check's {@link SessionStep.reason} may
147
149
  * carry when the app decides automatically (`decisions.mode: 'automatic'`)
@@ -232,7 +234,7 @@ type ReviewOutcomeReason = "superseded_by_retry" | "review_split";
232
234
  * reviewer overrode on an approval.
233
235
  * @public
234
236
  */
235
- type ReviewReason = "document_authenticity" | "liveness" | "face_match" | "data_mismatch" | "screening" | "other";
237
+ type ReviewReason = "document_authenticity" | "liveness" | "face_match" | "data_mismatch" | "screening" | "org_rule" | "other";
236
238
  /**
237
239
  * How a person decided a step: a reviewer (`source: "review"`), or an earlier
238
240
  * review of the same person, reference photo and face that was reused
@@ -1140,7 +1142,13 @@ interface SessionDevice {
1140
1142
  browserVersion?: string;
1141
1143
  deviceClass: "mobile" | "tablet" | "desktop" | "unknown";
1142
1144
  model?: string;
1143
- /** Device ids hashed with a key unique to your organization. */
1145
+ /**
1146
+ * Opaque device identity inside your organization and environment, stable across sessions
1147
+ * while the device keeps its install id. May be absent (for example without a device
1148
+ * header).
1149
+ */
1150
+ deviceId?: string;
1151
+ /** Hashed device keys of this session, per organization. */
1144
1152
  deviceKeys: string[];
1145
1153
  signals: SessionDeviceSignal[];
1146
1154
  }
@@ -1439,7 +1447,8 @@ interface Session {
1439
1447
  /**
1440
1448
  * Risk signals recorded on the session (e.g. `device_velocity`,
1441
1449
  * `timezone_mismatch`, `icao_non_compliant` when an `alert` ICAO policy flagged
1442
- * the selfie) — signals only, never a verdict by themselves.
1450
+ * the selfie, `document_uploaded` and the `document_upload_*` signals when the
1451
+ * person uploaded a photo of the document) — signals only, never a verdict by themselves.
1443
1452
  */
1444
1453
  riskSignals?: string[];
1445
1454
  /**
@@ -1786,11 +1795,145 @@ interface ListSessionsQuery {
1786
1795
  createdAfter?: string | Date;
1787
1796
  /** Sessions created before this time (ISO 8601 or a `Date`). */
1788
1797
  createdBefore?: string | Date;
1798
+ /** Only the sessions of this device (`device.deviceId` of a session). */
1799
+ deviceId?: string;
1789
1800
  /** Page size, 1 to 100 (the API's default is 50). */
1790
1801
  limit?: number;
1791
1802
  /** The {@link Page.nextCursor} of the previous page. */
1792
1803
  cursor?: string;
1793
1804
  }
1805
+ /**
1806
+ * What a block holds, as {@link BlocksApi.list} shows it. `face` blocks are made in the dashboard.
1807
+ * @public
1808
+ */
1809
+ type BlockKind = "id_number" | "external_ref" | "phone" | "email" | "device" | "face";
1810
+ /** Why a block exists. `rule`: an automatic rule made it. @public */
1811
+ type BlockReason = "fraud_confirmed" | "chargeback" | "abuse" | "test" | "rule" | "other";
1812
+ /** How long a block lasts; `null` has no end. @public */
1813
+ type BlockDuration = "P1D" | "P7D" | "P30D" | null;
1814
+ /**
1815
+ * A block on one key of this environment. Never a value or a hash.
1816
+ * @public
1817
+ */
1818
+ interface Block {
1819
+ /** `blk_...` */
1820
+ id: string;
1821
+ kind: BlockKind;
1822
+ /** Four characters derived from the key, to tell blocks apart. */
1823
+ label: string;
1824
+ /** The device, on a device block. */
1825
+ deviceId?: string;
1826
+ effect: "block" | "flag" | "review";
1827
+ reason: BlockReason;
1828
+ /** When it ends; `null` has no end. */
1829
+ expiresAt: string | null;
1830
+ createdAt: string;
1831
+ status: "active" | "lifted" | "expired";
1832
+ /** `rul_...`: the rule that made it, on a block made by a rule. Such a block has no end date. */
1833
+ ruleId?: string;
1834
+ /** The version of that rule when it made the block. */
1835
+ ruleVersion?: number;
1836
+ liftedAt?: string;
1837
+ }
1838
+ /** An ID number as a document shows it. Hashed by the API, never stored. @public */
1839
+ interface BlockIdNumber {
1840
+ number: string;
1841
+ /** ISO 3166-1 alpha-2 or alpha-3 code of the issuer. */
1842
+ issuingCountry: string;
1843
+ type: "national_id" | "passport" | "residence_permit";
1844
+ }
1845
+ /**
1846
+ * What to block, with `sekyro.blocks.create`. `value` carries `external_ref`, `phone` and
1847
+ * `email`; `person` blocks each ID number of the person and answers a list.
1848
+ * @public
1849
+ */
1850
+ type CreateBlockInput = {
1851
+ expiresIn: BlockDuration;
1852
+ reason?: Exclude<BlockReason, "rule">;
1853
+ /** Your note. It stays on your dashboard. */
1854
+ note?: string;
1855
+ } & ({
1856
+ kind: "external_ref" | "phone" | "email";
1857
+ value: string;
1858
+ } | {
1859
+ kind: "id_number";
1860
+ idNumber: BlockIdNumber;
1861
+ } | {
1862
+ kind: "person";
1863
+ personId: string;
1864
+ } | ({
1865
+ kind: "device";
1866
+ force?: boolean;
1867
+ } & ({
1868
+ deviceId: string;
1869
+ } | {
1870
+ sessionId: string;
1871
+ })));
1872
+ /** What to look up, with {@link BlocksApi.check}. @public */
1873
+ type BlockCheckInput = {
1874
+ kind: "external_ref" | "phone" | "email";
1875
+ value: string;
1876
+ } | {
1877
+ kind: "id_number";
1878
+ idNumber: BlockIdNumber;
1879
+ } | {
1880
+ kind: "person";
1881
+ personId: string;
1882
+ } | {
1883
+ kind: "device";
1884
+ deviceId: string;
1885
+ };
1886
+ /** The answer of {@link BlocksApi.check}. @public */
1887
+ interface BlockCheck {
1888
+ blocked: boolean;
1889
+ /** When the block ends; `null` has no end. Only when blocked. */
1890
+ expiresAt?: string | null;
1891
+ }
1892
+ /** Why a block is lifted, with {@link BlocksApi.lift}. @public */
1893
+ interface LiftBlockInput {
1894
+ /**
1895
+ * `false_positive` also marks the signal behind the block, so no rule fires on it again. On a
1896
+ * block made by a rule it counts against the rule, which pauses after too many reports.
1897
+ */
1898
+ reason?: "false_positive" | "other";
1899
+ note?: string;
1900
+ }
1901
+ /**
1902
+ * Filters of {@link BlocksApi.list}, {@link BlocksApi.listPage} and {@link BlocksApi.iterate}.
1903
+ * Newest first.
1904
+ * @public
1905
+ */
1906
+ interface ListBlocksQuery {
1907
+ kind?: BlockKind;
1908
+ status?: Block["status"];
1909
+ /** Page size, 1 to 100 (the API's default is 50). */
1910
+ limit?: number;
1911
+ /** The {@link Page.nextCursor} of the previous page. */
1912
+ cursor?: string;
1913
+ }
1914
+ /**
1915
+ * A device of this environment, counted inside it.
1916
+ * @public
1917
+ */
1918
+ interface Device {
1919
+ /** `dev_...`, as a session's `device.deviceId`. */
1920
+ deviceId: string;
1921
+ platform: "web" | "android" | "ios";
1922
+ model?: string;
1923
+ firstSeenAt: string;
1924
+ lastSeenAt: string;
1925
+ /** Your sessions on this device. */
1926
+ sessions: number;
1927
+ /** Distinct verified people among them over 90 days. */
1928
+ people: number;
1929
+ /** An agent filmed on it, many verified people passed on it, or you marked it. */
1930
+ shared: boolean;
1931
+ /** Its active block. */
1932
+ block: {
1933
+ id: string;
1934
+ expiresAt: string | null;
1935
+ } | null;
1936
+ }
1794
1937
  /**
1795
1938
  * Filters of {@link PeopleApi.list}, {@link PeopleApi.listPage} and
1796
1939
  * {@link PeopleApi.iterate}. Newest first; only people who passed a verification.
@@ -2279,6 +2422,7 @@ interface ConnectorIdentity {
2279
2422
  /** The connector package version, for example `0.1.0`: at most 64 characters. */
2280
2423
  version: string;
2281
2424
  }
2425
+ type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
2282
2426
  /**
2283
2427
  * `sekyro.sessions` — create and read verification sessions.
2284
2428
  *
@@ -2486,6 +2630,64 @@ declare class PeopleApi {
2486
2630
  * @public
2487
2631
  */
2488
2632
  type SubjectsApi = PeopleApi;
2633
+ /**
2634
+ * Stops the next sessions of a device, a person, an account or a contact. Exposed as
2635
+ * {@link Sekyro.blocks}. Needs the `blocks:read` or `blocks:write` scope.
2636
+ * Exported as a TYPE only.
2637
+ * @public
2638
+ */
2639
+ declare class BlocksApi {
2640
+ private readonly t;
2641
+ /** @internal */
2642
+ constructor(t: {
2643
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2644
+ page<T>(path: string): Promise<Page<T>>;
2645
+ });
2646
+ /**
2647
+ * `POST /blocks`: blocks the key, or answers the active block already on it. `kind: "person"`
2648
+ * blocks each ID number of the person and answers a list. A shared device answers
2649
+ * `409 device_shared` with `details.people` unless `force: true`. `403 blocks_disabled` while blocks
2650
+ * are turned off. The API requires an idempotency key: one is generated when you pass none, so
2651
+ * pass your own to make a retry of the same call safe.
2652
+ */
2653
+ create(input: CreateBlockInput & {
2654
+ kind: "person";
2655
+ }, opts?: RequestOptions): Promise<Block[]>;
2656
+ create(input: CreateBlockInput, opts?: RequestOptions): Promise<Block>;
2657
+ /** The first page of the blocks of this environment, newest first. Every page: {@link BlocksApi.iterate}. */
2658
+ list(query?: ListBlocksQuery): Promise<Block[]>;
2659
+ /** One page of {@link BlocksApi.list} with its `nextCursor` (absent on the last page). */
2660
+ listPage(query?: ListBlocksQuery): Promise<Page<Block>>;
2661
+ /** Every block matching `query`, newest first, following `nextCursor` page after page. */
2662
+ iterate(query?: ListBlocksQuery): AsyncGenerator<Block, void, undefined>;
2663
+ /** `GET /blocks/:id`. */
2664
+ get(id: string): Promise<Block>;
2665
+ /** `DELETE /blocks/:id`: the next sessions on its key go through. Lifting again is a no-op. */
2666
+ lift(id: string, input?: LiftBlockInput, opts?: RequestOptions): Promise<Block>;
2667
+ /** `POST /blocks/check`: whether a value is blocked. A POST, so it never sits in a URL or a log. */
2668
+ check(input: BlockCheckInput): Promise<BlockCheck>;
2669
+ }
2670
+ /**
2671
+ * What you know about a device before you block it. Exposed as {@link Sekyro.devices}. Needs the
2672
+ * `blocks:read` or `blocks:write` scope. Exported as a TYPE only.
2673
+ * @public
2674
+ */
2675
+ declare class DevicesApi {
2676
+ private readonly t;
2677
+ /** @internal */
2678
+ constructor(t: {
2679
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2680
+ });
2681
+ /** `GET /devices/:deviceId`: `404 device_not_found` for a device of another environment. */
2682
+ get(deviceId: string): Promise<Device>;
2683
+ /**
2684
+ * `PATCH /devices/:deviceId`: marks or unmarks the device as shared. Unmarking only clears your
2685
+ * own mark: a device recognised as shared from its sessions stays shared.
2686
+ */
2687
+ update(deviceId: string, input: {
2688
+ shared: boolean;
2689
+ }, opts?: RequestOptions): Promise<Device>;
2690
+ }
2489
2691
  /**
2490
2692
  * Sekyro AI partner API client. Server-side only: it carries your API key.
2491
2693
  *
@@ -2504,6 +2706,8 @@ declare class Sekyro {
2504
2706
  #private;
2505
2707
  readonly sessions: SessionsApi;
2506
2708
  readonly people: PeopleApi;
2709
+ readonly blocks: BlocksApi;
2710
+ readonly devices: DevicesApi;
2507
2711
  /** @deprecated Use {@link Sekyro.people}: the same object. */
2508
2712
  readonly subjects: PeopleApi;
2509
2713
  constructor(opts: SekyroOptions);
@@ -2516,4 +2720,4 @@ declare class Sekyro {
2516
2720
  listFlows(): Promise<FlowSummary[]>;
2517
2721
  }
2518
2722
 
2519
- export { type IdentitySources as $, type AgeMethod as A, type DeliverOptions as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type DocumentSubstitutionSettings as E, type FetchLike as F, type EidResult as G, type EligibilityReason as H, type ExtendLinkInput as I, type FlowOverridableSettings as J, type FlowOverrides as K, type Locale as L, type FlowServiceSettings as M, type FlowSummary as N, type IdNumberReason as O, type Identity as P, type IdentityBirthPlace as Q, type ReviewReason as R, Sekyro as S, type IdentityDocument as T, type IdentityIdNumber as U, type VerificationLevel as V, type WebhookEventType as W, type IdentityMethod as X, type IdentityName as Y, type IdentityScalarKey as Z, type IdentitySource as _, type ServiceId as a, type SessionSupersededEventData as a$, type LevelTarget as a0, type ListPeopleQuery as a1, type ListScreeningsQuery as a2, type ListSessionsQuery as a3, type MatchReason as a4, type MediaBytes as a5, type MediaBytesOptions as a6, type MediaItem as a7, type MediaKind as a8, type MediaList as a9, type ScreeningHit as aA, type ScreeningHitSummary as aB, type ScreeningList as aC, type ScreeningStatus as aD, type ScreeningTrigger as aE, type ScreeningUnavailableReason as aF, type SekyroOptions as aG, type Session as aH, type SessionDevice as aI, type SessionDeviceSignal as aJ, type SessionEventData as aK, type SessionFailureReason as aL, type SessionFlowRef as aM, type SessionLifecycleEventData as aN, type SessionLinkDelivery as aO, type SessionLinkExpiry as aP, type SessionLinkInput as aQ, type SessionNetwork as aR, type SessionNetworkEvent as aS, type SessionPortraitLink as aT, type SessionReviewDecidedEventData as aU, type SessionScreening as aV, type SessionStatus as aW, type SessionStep as aX, type SessionStepCompletedEventData as aY, type SessionStepDecision as aZ, type SessionSubjectInput as a_, type NameForm as aa, type Page as ab, PeopleApi as ac, type Person as ad, type PersonBirthPlaceInput as ae, type PersonDeletedEventData as af, type PersonDocumentInput as ag, type PersonEnrolledEventData as ah, type PersonSession as ai, type PersonSessionInput as aj, type PersonSessionTarget as ak, type PersonSuspiciousActivityEventData as al, type PersonUpdatedEventData as am, type PolicyFailureReason as an, type PortraitReportEntry as ao, type PriorReviewReason as ap, type ProbeBindingReason as aq, type ProbeQuality as ar, type ProfileDocumentType as as, type RequestOptions as at, type ResultTokenResponse as au, type ReviewOutcomeReason as av, type RevokePersonInput as aw, type RevokeSubjectInput as ax, type ScreenPersonInput as ay, type Screening as az, type SessionPersonInput as b, SessionsApi as b0, type Subject as b1, type SubjectAssurance as b2, type SubjectDeletedEventData as b3, type SubjectEnrolledEventData as b4, type SubjectIdNumber as b5, type SubjectName as b6, type SubjectReferenceSource as b7, type SubjectReuseDocument as b8, type SubjectReuseTarget as b9, type SubjectSession as ba, type SubjectSessionInput as bb, type SubjectSessionTarget as bc, type SubjectStatus as bd, type SubjectSuspiciousActivityEventData as be, type SubjectUpdatedEventData as bf, type SubjectsApi as bg, type SuppliedIdentityRecord as bh, type UsageThresholdReachedEventData as bi, type VerifiedContacts as bj, type WebhookEnvelopeOf as bk, type WebhookEventDataMap as bl, 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 ResultRisk as i, type ResultCheckProofs as j, type ResultDuplicate as k, type FailureIdentification as l, type AgeResult as m, type AmlMatchFlaggedEventData as n, type CameraUnavailableCause as o, type CheckState as p, type CheckType as q, type ConnectorIdentity as r, type CreateSessionInput as s, type CreatedSessionWarning as t, DEFAULT_TIMEOUT_MS as u, type DecidedBy as v, type DecisionReason as w, type DeepPartial as x, type DeletedPerson as y, type DeletedSubject as z };
2723
+ export { type FlowServiceSettings as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type CreateSessionInput as D, type CreatedSessionWarning as E, type FetchLike as F, DEFAULT_BASE_URL as G, DEFAULT_TIMEOUT_MS as H, type DecidedBy as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeletedSubject as N, type DeliverOptions as O, type Device as P, DevicesApi as Q, type ReviewReason as R, Sekyro as S, type DocumentSubstitutionSettings as T, type EidResult as U, type VerificationLevel as V, type WebhookEventType as W, type EligibilityReason as X, type ExtendLinkInput as Y, type FlowOverridableSettings as Z, type FlowOverrides as _, type ServiceId as a, type SessionLinkDelivery as a$, type FlowSummary 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 PolicyFailureReason as aA, type PortraitReportEntry as aB, type PriorReviewReason as aC, type ProbeBindingReason as aD, type ProbeQuality as aE, type ProfileDocumentType as aF, type RequestOptions as aG, type ResultTokenResponse as aH, type ReviewOutcomeReason as aI, type RevokePersonInput as aJ, type RevokeSubjectInput 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 SessionDevice as aV, type SessionDeviceSignal as aW, type SessionEventData as aX, type SessionFailureReason as aY, type SessionFlowRef as aZ, type SessionLifecycleEventData 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 MatchReason as ah, type MediaBytes as ai, type MediaBytesOptions as aj, type MediaItem as ak, type MediaKind as al, type MediaList as am, type NameForm as an, type Page as ao, PeopleApi as ap, type Person as aq, type PersonBirthPlaceInput as ar, type PersonDeletedEventData as as, type PersonDocumentInput as at, type PersonEnrolledEventData as au, type PersonSession as av, type PersonSessionInput as aw, type PersonSessionTarget as ax, type PersonSuspiciousActivityEventData as ay, type PersonUpdatedEventData as az, type SessionPersonInput as b, type SessionLinkExpiry as b0, type SessionLinkInput as b1, type SessionNetwork as b2, type SessionNetworkEvent as b3, type SessionPortraitLink as b4, type SessionReviewDecidedEventData as b5, type SessionScreening as b6, type SessionStatus as b7, type SessionStep as b8, type SessionStepCompletedEventData as b9, type SessionStepDecision as ba, type SessionSubjectInput as bb, type SessionSupersededEventData as bc, SessionsApi as bd, type Subject as be, type SubjectAssurance as bf, type SubjectDeletedEventData as bg, type SubjectEnrolledEventData as bh, type SubjectIdNumber as bi, type SubjectName as bj, type SubjectReferenceSource as bk, type SubjectReuseDocument as bl, type SubjectReuseTarget as bm, type SubjectSession as bn, type SubjectSessionInput as bo, type SubjectSessionTarget as bp, type SubjectStatus as bq, type SubjectSuspiciousActivityEventData as br, type SubjectUpdatedEventData as bs, type SubjectsApi as bt, type SuppliedIdentityRecord as bu, type UsageThresholdReachedEventData as bv, type VerifiedContacts as bw, type WebhookEnvelopeOf as bx, type WebhookEventDataMap as by, 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 ResultRisk as i, type ResultCheckProofs as j, type ResultDuplicate as k, type FailureIdentification as l, type AgeResult as m, type AmlMatchFlaggedEventData as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockReason as t, BlocksApi as u, type CameraUnavailableCause as v, type CheckState as w, type CheckType as x, type ConnectorIdentity as y, type CreateBlockInput as z };
@@ -138,10 +138,12 @@ type CheckState = "pending" | "input_required" | "processing" | "passed" | "fail
138
138
  * - `platform_unsupported` — the flow requires a chip read and the person
139
139
  * opened the link on the web (the link stays usable in a native app);
140
140
  * - `cancelled_by_organization` — you cancelled the session
141
- * ({@link SessionsApi.cancel}).
141
+ * ({@link SessionsApi.cancel});
142
+ * - `blocked_by_org`: one of your blocks (a device, a person, an account or a
143
+ * contact) stopped the session. Not retryable, not billed.
142
144
  * @public
143
145
  */
144
- type SessionFailureReason = "location_not_allowed" | "anonymizer_blocked" | "capture_tampered" | "device_velocity_exceeded" | "device_cooldown" | "platform_unsupported" | "cancelled_by_organization";
146
+ type SessionFailureReason = "location_not_allowed" | "anonymizer_blocked" | "capture_tampered" | "device_velocity_exceeded" | "device_cooldown" | "platform_unsupported" | "cancelled_by_organization" | "blocked_by_org";
145
147
  /**
146
148
  * Profile-v2 decision-mode reasons a check's {@link SessionStep.reason} may
147
149
  * carry when the app decides automatically (`decisions.mode: 'automatic'`)
@@ -232,7 +234,7 @@ type ReviewOutcomeReason = "superseded_by_retry" | "review_split";
232
234
  * reviewer overrode on an approval.
233
235
  * @public
234
236
  */
235
- type ReviewReason = "document_authenticity" | "liveness" | "face_match" | "data_mismatch" | "screening" | "other";
237
+ type ReviewReason = "document_authenticity" | "liveness" | "face_match" | "data_mismatch" | "screening" | "org_rule" | "other";
236
238
  /**
237
239
  * How a person decided a step: a reviewer (`source: "review"`), or an earlier
238
240
  * review of the same person, reference photo and face that was reused
@@ -1140,7 +1142,13 @@ interface SessionDevice {
1140
1142
  browserVersion?: string;
1141
1143
  deviceClass: "mobile" | "tablet" | "desktop" | "unknown";
1142
1144
  model?: string;
1143
- /** Device ids hashed with a key unique to your organization. */
1145
+ /**
1146
+ * Opaque device identity inside your organization and environment, stable across sessions
1147
+ * while the device keeps its install id. May be absent (for example without a device
1148
+ * header).
1149
+ */
1150
+ deviceId?: string;
1151
+ /** Hashed device keys of this session, per organization. */
1144
1152
  deviceKeys: string[];
1145
1153
  signals: SessionDeviceSignal[];
1146
1154
  }
@@ -1439,7 +1447,8 @@ interface Session {
1439
1447
  /**
1440
1448
  * Risk signals recorded on the session (e.g. `device_velocity`,
1441
1449
  * `timezone_mismatch`, `icao_non_compliant` when an `alert` ICAO policy flagged
1442
- * the selfie) — signals only, never a verdict by themselves.
1450
+ * the selfie, `document_uploaded` and the `document_upload_*` signals when the
1451
+ * person uploaded a photo of the document) — signals only, never a verdict by themselves.
1443
1452
  */
1444
1453
  riskSignals?: string[];
1445
1454
  /**
@@ -1786,11 +1795,145 @@ interface ListSessionsQuery {
1786
1795
  createdAfter?: string | Date;
1787
1796
  /** Sessions created before this time (ISO 8601 or a `Date`). */
1788
1797
  createdBefore?: string | Date;
1798
+ /** Only the sessions of this device (`device.deviceId` of a session). */
1799
+ deviceId?: string;
1789
1800
  /** Page size, 1 to 100 (the API's default is 50). */
1790
1801
  limit?: number;
1791
1802
  /** The {@link Page.nextCursor} of the previous page. */
1792
1803
  cursor?: string;
1793
1804
  }
1805
+ /**
1806
+ * What a block holds, as {@link BlocksApi.list} shows it. `face` blocks are made in the dashboard.
1807
+ * @public
1808
+ */
1809
+ type BlockKind = "id_number" | "external_ref" | "phone" | "email" | "device" | "face";
1810
+ /** Why a block exists. `rule`: an automatic rule made it. @public */
1811
+ type BlockReason = "fraud_confirmed" | "chargeback" | "abuse" | "test" | "rule" | "other";
1812
+ /** How long a block lasts; `null` has no end. @public */
1813
+ type BlockDuration = "P1D" | "P7D" | "P30D" | null;
1814
+ /**
1815
+ * A block on one key of this environment. Never a value or a hash.
1816
+ * @public
1817
+ */
1818
+ interface Block {
1819
+ /** `blk_...` */
1820
+ id: string;
1821
+ kind: BlockKind;
1822
+ /** Four characters derived from the key, to tell blocks apart. */
1823
+ label: string;
1824
+ /** The device, on a device block. */
1825
+ deviceId?: string;
1826
+ effect: "block" | "flag" | "review";
1827
+ reason: BlockReason;
1828
+ /** When it ends; `null` has no end. */
1829
+ expiresAt: string | null;
1830
+ createdAt: string;
1831
+ status: "active" | "lifted" | "expired";
1832
+ /** `rul_...`: the rule that made it, on a block made by a rule. Such a block has no end date. */
1833
+ ruleId?: string;
1834
+ /** The version of that rule when it made the block. */
1835
+ ruleVersion?: number;
1836
+ liftedAt?: string;
1837
+ }
1838
+ /** An ID number as a document shows it. Hashed by the API, never stored. @public */
1839
+ interface BlockIdNumber {
1840
+ number: string;
1841
+ /** ISO 3166-1 alpha-2 or alpha-3 code of the issuer. */
1842
+ issuingCountry: string;
1843
+ type: "national_id" | "passport" | "residence_permit";
1844
+ }
1845
+ /**
1846
+ * What to block, with `sekyro.blocks.create`. `value` carries `external_ref`, `phone` and
1847
+ * `email`; `person` blocks each ID number of the person and answers a list.
1848
+ * @public
1849
+ */
1850
+ type CreateBlockInput = {
1851
+ expiresIn: BlockDuration;
1852
+ reason?: Exclude<BlockReason, "rule">;
1853
+ /** Your note. It stays on your dashboard. */
1854
+ note?: string;
1855
+ } & ({
1856
+ kind: "external_ref" | "phone" | "email";
1857
+ value: string;
1858
+ } | {
1859
+ kind: "id_number";
1860
+ idNumber: BlockIdNumber;
1861
+ } | {
1862
+ kind: "person";
1863
+ personId: string;
1864
+ } | ({
1865
+ kind: "device";
1866
+ force?: boolean;
1867
+ } & ({
1868
+ deviceId: string;
1869
+ } | {
1870
+ sessionId: string;
1871
+ })));
1872
+ /** What to look up, with {@link BlocksApi.check}. @public */
1873
+ type BlockCheckInput = {
1874
+ kind: "external_ref" | "phone" | "email";
1875
+ value: string;
1876
+ } | {
1877
+ kind: "id_number";
1878
+ idNumber: BlockIdNumber;
1879
+ } | {
1880
+ kind: "person";
1881
+ personId: string;
1882
+ } | {
1883
+ kind: "device";
1884
+ deviceId: string;
1885
+ };
1886
+ /** The answer of {@link BlocksApi.check}. @public */
1887
+ interface BlockCheck {
1888
+ blocked: boolean;
1889
+ /** When the block ends; `null` has no end. Only when blocked. */
1890
+ expiresAt?: string | null;
1891
+ }
1892
+ /** Why a block is lifted, with {@link BlocksApi.lift}. @public */
1893
+ interface LiftBlockInput {
1894
+ /**
1895
+ * `false_positive` also marks the signal behind the block, so no rule fires on it again. On a
1896
+ * block made by a rule it counts against the rule, which pauses after too many reports.
1897
+ */
1898
+ reason?: "false_positive" | "other";
1899
+ note?: string;
1900
+ }
1901
+ /**
1902
+ * Filters of {@link BlocksApi.list}, {@link BlocksApi.listPage} and {@link BlocksApi.iterate}.
1903
+ * Newest first.
1904
+ * @public
1905
+ */
1906
+ interface ListBlocksQuery {
1907
+ kind?: BlockKind;
1908
+ status?: Block["status"];
1909
+ /** Page size, 1 to 100 (the API's default is 50). */
1910
+ limit?: number;
1911
+ /** The {@link Page.nextCursor} of the previous page. */
1912
+ cursor?: string;
1913
+ }
1914
+ /**
1915
+ * A device of this environment, counted inside it.
1916
+ * @public
1917
+ */
1918
+ interface Device {
1919
+ /** `dev_...`, as a session's `device.deviceId`. */
1920
+ deviceId: string;
1921
+ platform: "web" | "android" | "ios";
1922
+ model?: string;
1923
+ firstSeenAt: string;
1924
+ lastSeenAt: string;
1925
+ /** Your sessions on this device. */
1926
+ sessions: number;
1927
+ /** Distinct verified people among them over 90 days. */
1928
+ people: number;
1929
+ /** An agent filmed on it, many verified people passed on it, or you marked it. */
1930
+ shared: boolean;
1931
+ /** Its active block. */
1932
+ block: {
1933
+ id: string;
1934
+ expiresAt: string | null;
1935
+ } | null;
1936
+ }
1794
1937
  /**
1795
1938
  * Filters of {@link PeopleApi.list}, {@link PeopleApi.listPage} and
1796
1939
  * {@link PeopleApi.iterate}. Newest first; only people who passed a verification.
@@ -2279,6 +2422,7 @@ interface ConnectorIdentity {
2279
2422
  /** The connector package version, for example `0.1.0`: at most 64 characters. */
2280
2423
  version: string;
2281
2424
  }
2425
+ type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
2282
2426
  /**
2283
2427
  * `sekyro.sessions` — create and read verification sessions.
2284
2428
  *
@@ -2486,6 +2630,64 @@ declare class PeopleApi {
2486
2630
  * @public
2487
2631
  */
2488
2632
  type SubjectsApi = PeopleApi;
2633
+ /**
2634
+ * Stops the next sessions of a device, a person, an account or a contact. Exposed as
2635
+ * {@link Sekyro.blocks}. Needs the `blocks:read` or `blocks:write` scope.
2636
+ * Exported as a TYPE only.
2637
+ * @public
2638
+ */
2639
+ declare class BlocksApi {
2640
+ private readonly t;
2641
+ /** @internal */
2642
+ constructor(t: {
2643
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2644
+ page<T>(path: string): Promise<Page<T>>;
2645
+ });
2646
+ /**
2647
+ * `POST /blocks`: blocks the key, or answers the active block already on it. `kind: "person"`
2648
+ * blocks each ID number of the person and answers a list. A shared device answers
2649
+ * `409 device_shared` with `details.people` unless `force: true`. `403 blocks_disabled` while blocks
2650
+ * are turned off. The API requires an idempotency key: one is generated when you pass none, so
2651
+ * pass your own to make a retry of the same call safe.
2652
+ */
2653
+ create(input: CreateBlockInput & {
2654
+ kind: "person";
2655
+ }, opts?: RequestOptions): Promise<Block[]>;
2656
+ create(input: CreateBlockInput, opts?: RequestOptions): Promise<Block>;
2657
+ /** The first page of the blocks of this environment, newest first. Every page: {@link BlocksApi.iterate}. */
2658
+ list(query?: ListBlocksQuery): Promise<Block[]>;
2659
+ /** One page of {@link BlocksApi.list} with its `nextCursor` (absent on the last page). */
2660
+ listPage(query?: ListBlocksQuery): Promise<Page<Block>>;
2661
+ /** Every block matching `query`, newest first, following `nextCursor` page after page. */
2662
+ iterate(query?: ListBlocksQuery): AsyncGenerator<Block, void, undefined>;
2663
+ /** `GET /blocks/:id`. */
2664
+ get(id: string): Promise<Block>;
2665
+ /** `DELETE /blocks/:id`: the next sessions on its key go through. Lifting again is a no-op. */
2666
+ lift(id: string, input?: LiftBlockInput, opts?: RequestOptions): Promise<Block>;
2667
+ /** `POST /blocks/check`: whether a value is blocked. A POST, so it never sits in a URL or a log. */
2668
+ check(input: BlockCheckInput): Promise<BlockCheck>;
2669
+ }
2670
+ /**
2671
+ * What you know about a device before you block it. Exposed as {@link Sekyro.devices}. Needs the
2672
+ * `blocks:read` or `blocks:write` scope. Exported as a TYPE only.
2673
+ * @public
2674
+ */
2675
+ declare class DevicesApi {
2676
+ private readonly t;
2677
+ /** @internal */
2678
+ constructor(t: {
2679
+ call<T>(method: HttpMethod, path: string, body?: unknown, idempotencyKey?: string): Promise<T>;
2680
+ });
2681
+ /** `GET /devices/:deviceId`: `404 device_not_found` for a device of another environment. */
2682
+ get(deviceId: string): Promise<Device>;
2683
+ /**
2684
+ * `PATCH /devices/:deviceId`: marks or unmarks the device as shared. Unmarking only clears your
2685
+ * own mark: a device recognised as shared from its sessions stays shared.
2686
+ */
2687
+ update(deviceId: string, input: {
2688
+ shared: boolean;
2689
+ }, opts?: RequestOptions): Promise<Device>;
2690
+ }
2489
2691
  /**
2490
2692
  * Sekyro AI partner API client. Server-side only: it carries your API key.
2491
2693
  *
@@ -2504,6 +2706,8 @@ declare class Sekyro {
2504
2706
  #private;
2505
2707
  readonly sessions: SessionsApi;
2506
2708
  readonly people: PeopleApi;
2709
+ readonly blocks: BlocksApi;
2710
+ readonly devices: DevicesApi;
2507
2711
  /** @deprecated Use {@link Sekyro.people}: the same object. */
2508
2712
  readonly subjects: PeopleApi;
2509
2713
  constructor(opts: SekyroOptions);
@@ -2516,4 +2720,4 @@ declare class Sekyro {
2516
2720
  listFlows(): Promise<FlowSummary[]>;
2517
2721
  }
2518
2722
 
2519
- export { type IdentitySources as $, type AgeMethod as A, type DeliverOptions as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type DocumentSubstitutionSettings as E, type FetchLike as F, type EidResult as G, type EligibilityReason as H, type ExtendLinkInput as I, type FlowOverridableSettings as J, type FlowOverrides as K, type Locale as L, type FlowServiceSettings as M, type FlowSummary as N, type IdNumberReason as O, type Identity as P, type IdentityBirthPlace as Q, type ReviewReason as R, Sekyro as S, type IdentityDocument as T, type IdentityIdNumber as U, type VerificationLevel as V, type WebhookEventType as W, type IdentityMethod as X, type IdentityName as Y, type IdentityScalarKey as Z, type IdentitySource as _, type ServiceId as a, type SessionSupersededEventData as a$, type LevelTarget as a0, type ListPeopleQuery as a1, type ListScreeningsQuery as a2, type ListSessionsQuery as a3, type MatchReason as a4, type MediaBytes as a5, type MediaBytesOptions as a6, type MediaItem as a7, type MediaKind as a8, type MediaList as a9, type ScreeningHit as aA, type ScreeningHitSummary as aB, type ScreeningList as aC, type ScreeningStatus as aD, type ScreeningTrigger as aE, type ScreeningUnavailableReason as aF, type SekyroOptions as aG, type Session as aH, type SessionDevice as aI, type SessionDeviceSignal as aJ, type SessionEventData as aK, type SessionFailureReason as aL, type SessionFlowRef as aM, type SessionLifecycleEventData as aN, type SessionLinkDelivery as aO, type SessionLinkExpiry as aP, type SessionLinkInput as aQ, type SessionNetwork as aR, type SessionNetworkEvent as aS, type SessionPortraitLink as aT, type SessionReviewDecidedEventData as aU, type SessionScreening as aV, type SessionStatus as aW, type SessionStep as aX, type SessionStepCompletedEventData as aY, type SessionStepDecision as aZ, type SessionSubjectInput as a_, type NameForm as aa, type Page as ab, PeopleApi as ac, type Person as ad, type PersonBirthPlaceInput as ae, type PersonDeletedEventData as af, type PersonDocumentInput as ag, type PersonEnrolledEventData as ah, type PersonSession as ai, type PersonSessionInput as aj, type PersonSessionTarget as ak, type PersonSuspiciousActivityEventData as al, type PersonUpdatedEventData as am, type PolicyFailureReason as an, type PortraitReportEntry as ao, type PriorReviewReason as ap, type ProbeBindingReason as aq, type ProbeQuality as ar, type ProfileDocumentType as as, type RequestOptions as at, type ResultTokenResponse as au, type ReviewOutcomeReason as av, type RevokePersonInput as aw, type RevokeSubjectInput as ax, type ScreenPersonInput as ay, type Screening as az, type SessionPersonInput as b, SessionsApi as b0, type Subject as b1, type SubjectAssurance as b2, type SubjectDeletedEventData as b3, type SubjectEnrolledEventData as b4, type SubjectIdNumber as b5, type SubjectName as b6, type SubjectReferenceSource as b7, type SubjectReuseDocument as b8, type SubjectReuseTarget as b9, type SubjectSession as ba, type SubjectSessionInput as bb, type SubjectSessionTarget as bc, type SubjectStatus as bd, type SubjectSuspiciousActivityEventData as be, type SubjectUpdatedEventData as bf, type SubjectsApi as bg, type SuppliedIdentityRecord as bh, type UsageThresholdReachedEventData as bi, type VerifiedContacts as bj, type WebhookEnvelopeOf as bk, type WebhookEventDataMap as bl, 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 ResultRisk as i, type ResultCheckProofs as j, type ResultDuplicate as k, type FailureIdentification as l, type AgeResult as m, type AmlMatchFlaggedEventData as n, type CameraUnavailableCause as o, type CheckState as p, type CheckType as q, type ConnectorIdentity as r, type CreateSessionInput as s, type CreatedSessionWarning as t, DEFAULT_TIMEOUT_MS as u, type DecidedBy as v, type DecisionReason as w, type DeepPartial as x, type DeletedPerson as y, type DeletedSubject as z };
2723
+ export { type FlowServiceSettings as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type CreateSessionInput as D, type CreatedSessionWarning as E, type FetchLike as F, DEFAULT_BASE_URL as G, DEFAULT_TIMEOUT_MS as H, type DecidedBy as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeletedSubject as N, type DeliverOptions as O, type Device as P, DevicesApi as Q, type ReviewReason as R, Sekyro as S, type DocumentSubstitutionSettings as T, type EidResult as U, type VerificationLevel as V, type WebhookEventType as W, type EligibilityReason as X, type ExtendLinkInput as Y, type FlowOverridableSettings as Z, type FlowOverrides as _, type ServiceId as a, type SessionLinkDelivery as a$, type FlowSummary 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 PolicyFailureReason as aA, type PortraitReportEntry as aB, type PriorReviewReason as aC, type ProbeBindingReason as aD, type ProbeQuality as aE, type ProfileDocumentType as aF, type RequestOptions as aG, type ResultTokenResponse as aH, type ReviewOutcomeReason as aI, type RevokePersonInput as aJ, type RevokeSubjectInput 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 SessionDevice as aV, type SessionDeviceSignal as aW, type SessionEventData as aX, type SessionFailureReason as aY, type SessionFlowRef as aZ, type SessionLifecycleEventData 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 MatchReason as ah, type MediaBytes as ai, type MediaBytesOptions as aj, type MediaItem as ak, type MediaKind as al, type MediaList as am, type NameForm as an, type Page as ao, PeopleApi as ap, type Person as aq, type PersonBirthPlaceInput as ar, type PersonDeletedEventData as as, type PersonDocumentInput as at, type PersonEnrolledEventData as au, type PersonSession as av, type PersonSessionInput as aw, type PersonSessionTarget as ax, type PersonSuspiciousActivityEventData as ay, type PersonUpdatedEventData as az, type SessionPersonInput as b, type SessionLinkExpiry as b0, type SessionLinkInput as b1, type SessionNetwork as b2, type SessionNetworkEvent as b3, type SessionPortraitLink as b4, type SessionReviewDecidedEventData as b5, type SessionScreening as b6, type SessionStatus as b7, type SessionStep as b8, type SessionStepCompletedEventData as b9, type SessionStepDecision as ba, type SessionSubjectInput as bb, type SessionSupersededEventData as bc, SessionsApi as bd, type Subject as be, type SubjectAssurance as bf, type SubjectDeletedEventData as bg, type SubjectEnrolledEventData as bh, type SubjectIdNumber as bi, type SubjectName as bj, type SubjectReferenceSource as bk, type SubjectReuseDocument as bl, type SubjectReuseTarget as bm, type SubjectSession as bn, type SubjectSessionInput as bo, type SubjectSessionTarget as bp, type SubjectStatus as bq, type SubjectSuspiciousActivityEventData as br, type SubjectUpdatedEventData as bs, type SubjectsApi as bt, type SuppliedIdentityRecord as bu, type UsageThresholdReachedEventData as bv, type VerifiedContacts as bw, type WebhookEnvelopeOf as bx, type WebhookEventDataMap as by, 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 ResultRisk as i, type ResultCheckProofs as j, type ResultDuplicate as k, type FailureIdentification as l, type AgeResult as m, type AmlMatchFlaggedEventData as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockReason as t, BlocksApi as u, type CameraUnavailableCause as v, type CheckState as w, type CheckType as x, type ConnectorIdentity as y, type CreateBlockInput as z };
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-80bgRkSI.cjs';
2
- import '../../client-C2VDmckH.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-DL-RL9jQ.cjs';
2
+ import '../../client-Dpgpk9cE.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-BV3zVPrh.js';
2
- import '../../client-C2VDmckH.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-B9XkmMMb.js';
2
+ import '../../client-Dpgpk9cE.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-80bgRkSI.cjs';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-C2VDmckH.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-DL-RL9jQ.cjs';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-Dpgpk9cE.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-BV3zVPrh.js';
2
- export { A as AgeMethod, W as WebhookEventType } from '../client-C2VDmckH.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-B9XkmMMb.js';
2
+ export { A as AgeMethod, W as WebhookEventType } from '../client-Dpgpk9cE.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-80bgRkSI.cjs';
2
- import '../../client-C2VDmckH.cjs';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-DL-RL9jQ.cjs';
2
+ import '../../client-Dpgpk9cE.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-BV3zVPrh.js';
2
- import '../../client-C2VDmckH.js';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-B9XkmMMb.js';
2
+ import '../../client-Dpgpk9cE.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, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-C2VDmckH.js';
1
+ import { A as AgeMethod, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-Dpgpk9cE.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -1,4 +1,4 @@
1
- import { A as AgeMethod, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-C2VDmckH.cjs';
1
+ import { A as AgeMethod, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-Dpgpk9cE.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,personFromNationalRegistry:()=>personFromNationalRegistry,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.13";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}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}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&&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 requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id: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={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}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;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),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)),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 portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},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||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/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'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;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;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.subjects=this.people,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 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 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 subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,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){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.person_id??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;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 isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}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},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);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(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,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,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,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.14";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}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}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&&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 requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id: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={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}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;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),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)),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 portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},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||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/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'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},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)}},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;devices;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;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.devices=new DevicesApi(bound),this.subjects=this.people,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 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 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 subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,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){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.person_id??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;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 isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}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},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);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(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,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-C2VDmckH.cjs';
2
- export { m as AgeResult, n as AmlMatchFlaggedEventData, o as CameraUnavailableCause, p as CheckState, q as CheckType, r as ConnectorIdentity, s as CreateSessionInput, C as CreatedSession, t as CreatedSessionWarning, D as DEFAULT_BASE_URL, u as DEFAULT_TIMEOUT_MS, v as DecidedBy, w as DecisionReason, x as DeepPartial, y as DeletedPerson, z as DeletedSubject, B as DeliverOptions, E as DocumentSubstitutionSettings, G as EidResult, H as EligibilityReason, I as ExtendLinkInput, J as FlowOverridableSettings, K as FlowOverrides, M as FlowServiceSettings, N as FlowSummary, O as IdNumberReason, P as Identity, Q as IdentityBirthPlace, T as IdentityDocument, U as IdentityIdNumber, X as IdentityMethod, Y as IdentityName, Z as IdentityScalarKey, _ as IdentitySource, $ as IdentitySources, a0 as LevelTarget, a1 as ListPeopleQuery, a2 as ListScreeningsQuery, a3 as ListSessionsQuery, L as Locale, a4 as MatchReason, a5 as MediaBytes, a6 as MediaBytesOptions, a7 as MediaItem, a8 as MediaKind, a9 as MediaList, aa as NameForm, ab as Page, ac as PeopleApi, ad as Person, ae as PersonBirthPlaceInput, af as PersonDeletedEventData, ag as PersonDocumentInput, ah as PersonEnrolledEventData, ai as PersonSession, aj as PersonSessionInput, ak as PersonSessionTarget, al as PersonSuspiciousActivityEventData, am as PersonUpdatedEventData, an as PolicyFailureReason, ao as PortraitReportEntry, ap as PriorReviewReason, aq as ProbeBindingReason, ar as ProbeQuality, as as ProfileDocumentType, at as RequestOptions, au as ResultTokenResponse, av as ReviewOutcomeReason, aw as RevokePersonInput, ax as RevokeSubjectInput, ay as ScreenPersonInput, az as Screening, aA as ScreeningHit, aB as ScreeningHitSummary, aC as ScreeningList, aD as ScreeningStatus, aE as ScreeningTrigger, aF as ScreeningUnavailableReason, S as Sekyro, aG as SekyroOptions, aH as Session, aI as SessionDevice, aJ as SessionDeviceSignal, aK as SessionEventData, aL as SessionFailureReason, aM as SessionFlowRef, aN as SessionLifecycleEventData, aO as SessionLinkDelivery, aP as SessionLinkExpiry, aQ as SessionLinkInput, aR as SessionNetwork, aS as SessionNetworkEvent, aT as SessionPortraitLink, aU as SessionReviewDecidedEventData, aV as SessionScreening, aW as SessionStatus, aX as SessionStep, aY as SessionStepCompletedEventData, aZ as SessionStepDecision, a_ as SessionSubjectInput, a$ as SessionSupersededEventData, b0 as SessionsApi, b1 as Subject, b2 as SubjectAssurance, b3 as SubjectDeletedEventData, b4 as SubjectEnrolledEventData, b5 as SubjectIdNumber, b6 as SubjectName, b7 as SubjectReferenceSource, b8 as SubjectReuseDocument, b9 as SubjectReuseTarget, ba as SubjectSession, bb as SubjectSessionInput, bc as SubjectSessionTarget, bd as SubjectStatus, be as SubjectSuspiciousActivityEventData, bf as SubjectUpdatedEventData, bg as SubjectsApi, bh as SuppliedIdentityRecord, bi as UsageThresholdReachedEventData, bj as VerifiedContacts, bk as WebhookEnvelopeOf, bl as WebhookEventDataMap, W as WebhookEventType } from './client-C2VDmckH.cjs';
1
+ import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-Dpgpk9cE.cjs';
2
+ export { m as AgeResult, n as AmlMatchFlaggedEventData, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockReason, u as BlocksApi, v as CameraUnavailableCause, w as CheckState, x as CheckType, y as ConnectorIdentity, z as CreateBlockInput, D as CreateSessionInput, C as CreatedSession, E as CreatedSessionWarning, G as DEFAULT_BASE_URL, H as DEFAULT_TIMEOUT_MS, I as DecidedBy, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeletedSubject, O as DeliverOptions, P as Device, Q as DevicesApi, T as DocumentSubstitutionSettings, U as EidResult, X as EligibilityReason, Y as ExtendLinkInput, Z as FlowOverridableSettings, _ as FlowOverrides, $ as FlowServiceSettings, a0 as FlowSummary, 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, L as Locale, ah as MatchReason, ai as MediaBytes, aj as MediaBytesOptions, ak as MediaItem, al as MediaKind, am as MediaList, an as NameForm, ao as Page, ap as PeopleApi, aq as Person, ar as PersonBirthPlaceInput, as as PersonDeletedEventData, at as PersonDocumentInput, au as PersonEnrolledEventData, av as PersonSession, aw as PersonSessionInput, ax as PersonSessionTarget, ay as PersonSuspiciousActivityEventData, az as PersonUpdatedEventData, aA as PolicyFailureReason, aB as PortraitReportEntry, aC as PriorReviewReason, aD as ProbeBindingReason, aE as ProbeQuality, aF as ProfileDocumentType, aG as RequestOptions, aH as ResultTokenResponse, aI as ReviewOutcomeReason, aJ as RevokePersonInput, aK as RevokeSubjectInput, aL as ScreenPersonInput, aM as Screening, aN as ScreeningHit, aO as ScreeningHitSummary, aP as ScreeningList, aQ as ScreeningStatus, aR as ScreeningTrigger, aS as ScreeningUnavailableReason, S as Sekyro, aT as SekyroOptions, aU as Session, aV as SessionDevice, aW as SessionDeviceSignal, aX as SessionEventData, aY as SessionFailureReason, aZ as SessionFlowRef, a_ as SessionLifecycleEventData, a$ as SessionLinkDelivery, b0 as SessionLinkExpiry, b1 as SessionLinkInput, b2 as SessionNetwork, b3 as SessionNetworkEvent, b4 as SessionPortraitLink, b5 as SessionReviewDecidedEventData, b6 as SessionScreening, b7 as SessionStatus, b8 as SessionStep, b9 as SessionStepCompletedEventData, ba as SessionStepDecision, bb as SessionSubjectInput, bc as SessionSupersededEventData, bd as SessionsApi, be as Subject, bf as SubjectAssurance, bg as SubjectDeletedEventData, bh as SubjectEnrolledEventData, bi as SubjectIdNumber, bj as SubjectName, bk as SubjectReferenceSource, bl as SubjectReuseDocument, bm as SubjectReuseTarget, bn as SubjectSession, bo as SubjectSessionInput, bp as SubjectSessionTarget, bq as SubjectStatus, br as SubjectSuspiciousActivityEventData, bs as SubjectUpdatedEventData, bt as SubjectsApi, bu as SuppliedIdentityRecord, bv as UsageThresholdReachedEventData, bw as VerifiedContacts, bx as WebhookEnvelopeOf, by as WebhookEventDataMap, W as WebhookEventType } from './client-Dpgpk9cE.cjs';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-C2VDmckH.js';
2
- export { m as AgeResult, n as AmlMatchFlaggedEventData, o as CameraUnavailableCause, p as CheckState, q as CheckType, r as ConnectorIdentity, s as CreateSessionInput, C as CreatedSession, t as CreatedSessionWarning, D as DEFAULT_BASE_URL, u as DEFAULT_TIMEOUT_MS, v as DecidedBy, w as DecisionReason, x as DeepPartial, y as DeletedPerson, z as DeletedSubject, B as DeliverOptions, E as DocumentSubstitutionSettings, G as EidResult, H as EligibilityReason, I as ExtendLinkInput, J as FlowOverridableSettings, K as FlowOverrides, M as FlowServiceSettings, N as FlowSummary, O as IdNumberReason, P as Identity, Q as IdentityBirthPlace, T as IdentityDocument, U as IdentityIdNumber, X as IdentityMethod, Y as IdentityName, Z as IdentityScalarKey, _ as IdentitySource, $ as IdentitySources, a0 as LevelTarget, a1 as ListPeopleQuery, a2 as ListScreeningsQuery, a3 as ListSessionsQuery, L as Locale, a4 as MatchReason, a5 as MediaBytes, a6 as MediaBytesOptions, a7 as MediaItem, a8 as MediaKind, a9 as MediaList, aa as NameForm, ab as Page, ac as PeopleApi, ad as Person, ae as PersonBirthPlaceInput, af as PersonDeletedEventData, ag as PersonDocumentInput, ah as PersonEnrolledEventData, ai as PersonSession, aj as PersonSessionInput, ak as PersonSessionTarget, al as PersonSuspiciousActivityEventData, am as PersonUpdatedEventData, an as PolicyFailureReason, ao as PortraitReportEntry, ap as PriorReviewReason, aq as ProbeBindingReason, ar as ProbeQuality, as as ProfileDocumentType, at as RequestOptions, au as ResultTokenResponse, av as ReviewOutcomeReason, aw as RevokePersonInput, ax as RevokeSubjectInput, ay as ScreenPersonInput, az as Screening, aA as ScreeningHit, aB as ScreeningHitSummary, aC as ScreeningList, aD as ScreeningStatus, aE as ScreeningTrigger, aF as ScreeningUnavailableReason, S as Sekyro, aG as SekyroOptions, aH as Session, aI as SessionDevice, aJ as SessionDeviceSignal, aK as SessionEventData, aL as SessionFailureReason, aM as SessionFlowRef, aN as SessionLifecycleEventData, aO as SessionLinkDelivery, aP as SessionLinkExpiry, aQ as SessionLinkInput, aR as SessionNetwork, aS as SessionNetworkEvent, aT as SessionPortraitLink, aU as SessionReviewDecidedEventData, aV as SessionScreening, aW as SessionStatus, aX as SessionStep, aY as SessionStepCompletedEventData, aZ as SessionStepDecision, a_ as SessionSubjectInput, a$ as SessionSupersededEventData, b0 as SessionsApi, b1 as Subject, b2 as SubjectAssurance, b3 as SubjectDeletedEventData, b4 as SubjectEnrolledEventData, b5 as SubjectIdNumber, b6 as SubjectName, b7 as SubjectReferenceSource, b8 as SubjectReuseDocument, b9 as SubjectReuseTarget, ba as SubjectSession, bb as SubjectSessionInput, bc as SubjectSessionTarget, bd as SubjectStatus, be as SubjectSuspiciousActivityEventData, bf as SubjectUpdatedEventData, bg as SubjectsApi, bh as SuppliedIdentityRecord, bi as UsageThresholdReachedEventData, bj as VerifiedContacts, bk as WebhookEnvelopeOf, bl as WebhookEventDataMap, W as WebhookEventType } from './client-C2VDmckH.js';
1
+ import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-Dpgpk9cE.js';
2
+ export { m as AgeResult, n as AmlMatchFlaggedEventData, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockReason, u as BlocksApi, v as CameraUnavailableCause, w as CheckState, x as CheckType, y as ConnectorIdentity, z as CreateBlockInput, D as CreateSessionInput, C as CreatedSession, E as CreatedSessionWarning, G as DEFAULT_BASE_URL, H as DEFAULT_TIMEOUT_MS, I as DecidedBy, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeletedSubject, O as DeliverOptions, P as Device, Q as DevicesApi, T as DocumentSubstitutionSettings, U as EidResult, X as EligibilityReason, Y as ExtendLinkInput, Z as FlowOverridableSettings, _ as FlowOverrides, $ as FlowServiceSettings, a0 as FlowSummary, 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, L as Locale, ah as MatchReason, ai as MediaBytes, aj as MediaBytesOptions, ak as MediaItem, al as MediaKind, am as MediaList, an as NameForm, ao as Page, ap as PeopleApi, aq as Person, ar as PersonBirthPlaceInput, as as PersonDeletedEventData, at as PersonDocumentInput, au as PersonEnrolledEventData, av as PersonSession, aw as PersonSessionInput, ax as PersonSessionTarget, ay as PersonSuspiciousActivityEventData, az as PersonUpdatedEventData, aA as PolicyFailureReason, aB as PortraitReportEntry, aC as PriorReviewReason, aD as ProbeBindingReason, aE as ProbeQuality, aF as ProfileDocumentType, aG as RequestOptions, aH as ResultTokenResponse, aI as ReviewOutcomeReason, aJ as RevokePersonInput, aK as RevokeSubjectInput, aL as ScreenPersonInput, aM as Screening, aN as ScreeningHit, aO as ScreeningHitSummary, aP as ScreeningList, aQ as ScreeningStatus, aR as ScreeningTrigger, aS as ScreeningUnavailableReason, S as Sekyro, aT as SekyroOptions, aU as Session, aV as SessionDevice, aW as SessionDeviceSignal, aX as SessionEventData, aY as SessionFailureReason, aZ as SessionFlowRef, a_ as SessionLifecycleEventData, a$ as SessionLinkDelivery, b0 as SessionLinkExpiry, b1 as SessionLinkInput, b2 as SessionNetwork, b3 as SessionNetworkEvent, b4 as SessionPortraitLink, b5 as SessionReviewDecidedEventData, b6 as SessionScreening, b7 as SessionStatus, b8 as SessionStep, b9 as SessionStepCompletedEventData, ba as SessionStepDecision, bb as SessionSubjectInput, bc as SessionSupersededEventData, bd as SessionsApi, be as Subject, bf as SubjectAssurance, bg as SubjectDeletedEventData, bh as SubjectEnrolledEventData, bi as SubjectIdNumber, bj as SubjectName, bk as SubjectReferenceSource, bl as SubjectReuseDocument, bm as SubjectReuseTarget, bn as SubjectSession, bo as SubjectSessionInput, bp as SubjectSessionTarget, bq as SubjectStatus, br as SubjectSuspiciousActivityEventData, bs as SubjectUpdatedEventData, bt as SubjectsApi, bu as SuppliedIdentityRecord, bv as UsageThresholdReachedEventData, bw as VerifiedContacts, bx as WebhookEnvelopeOf, by as WebhookEventDataMap, W as WebhookEventType } from './client-Dpgpk9cE.js';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",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.13";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}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}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&&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 requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id: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={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}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;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),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)),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 portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},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||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/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'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;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;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.subjects=this.people,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 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 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 subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){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.person_id??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;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 isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}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},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);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(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(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))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
1
+ var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",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.14";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}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}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&&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 requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id: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={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}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;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),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)),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 portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},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||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/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'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},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)}},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;devices;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;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.devices=new DevicesApi(bound),this.subjects=this.people,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 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 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 subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){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.person_id??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;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 isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}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},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);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(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(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))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sekyro/node",
3
- "version": "0.1.0-rc.13",
3
+ "version": "0.1.0-rc.14",
4
4
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
package/sbom.cdx.json CHANGED
@@ -97,8 +97,8 @@
97
97
  "type": "application",
98
98
  "name": "node",
99
99
  "group": "@sekyro",
100
- "version": "0.1.0-rc.13",
101
- "bom-ref": "@sekyro/node@0.1.0-rc.13",
100
+ "version": "0.1.0-rc.14",
101
+ "bom-ref": "@sekyro/node@0.1.0-rc.14",
102
102
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
103
103
  "licenses": [
104
104
  {
@@ -108,7 +108,7 @@
108
108
  }
109
109
  }
110
110
  ],
111
- "purl": "pkg:npm/%40sekyro/node@0.1.0-rc.13?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
111
+ "purl": "pkg:npm/%40sekyro/node@0.1.0-rc.14?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
112
112
  "externalReferences": [
113
113
  {
114
114
  "url": "https://github.com/IBTIKAR-Technologies/ibtikar-identity/issues",
@@ -149,7 +149,7 @@
149
149
  "type": "library",
150
150
  "name": "jose",
151
151
  "version": "5.10.0",
152
- "bom-ref": "@sekyro/node@0.1.0-rc.13|jose@5.10.0",
152
+ "bom-ref": "@sekyro/node@0.1.0-rc.14|jose@5.10.0",
153
153
  "licenses": [
154
154
  {
155
155
  "license": {
@@ -182,13 +182,13 @@
182
182
  ],
183
183
  "dependencies": [
184
184
  {
185
- "ref": "@sekyro/node@0.1.0-rc.13",
185
+ "ref": "@sekyro/node@0.1.0-rc.14",
186
186
  "dependsOn": [
187
- "@sekyro/node@0.1.0-rc.13|jose@5.10.0"
187
+ "@sekyro/node@0.1.0-rc.14|jose@5.10.0"
188
188
  ]
189
189
  },
190
190
  {
191
- "ref": "@sekyro/node@0.1.0-rc.13|jose@5.10.0"
191
+ "ref": "@sekyro/node@0.1.0-rc.14|jose@5.10.0"
192
192
  }
193
193
  ]
194
194
  }