@sekyro/node 1.0.0-rc.18 → 1.0.0-rc.19
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 +6 -0
- package/README.md +7 -2
- package/dist/{client-B0zqD-HZ.d.cts → client-BSzMfacG.d.cts} +5 -17
- package/dist/{client-B0zqD-HZ.d.ts → client-BSzMfacG.d.ts} +5 -17
- package/dist/connect/express/index.d.cts +2 -2
- package/dist/connect/express/index.d.ts +2 -2
- package/dist/connect/index.d.cts +2 -2
- package/dist/connect/index.d.ts +2 -2
- package/dist/connect/next/index.d.cts +2 -2
- package/dist/connect/next/index.d.ts +2 -2
- package/dist/{connector-Cs-y1iL9.d.cts → connector-CyNFdiLv.d.cts} +1 -1
- package/dist/{connector-CPyS23b7.d.ts → connector-D0CDGAOJ.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @sekyro/node
|
|
2
2
|
|
|
3
|
+
## 1.0.0-rc.19
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 62987ea: Breaking: `person.suspicious_activity` is no longer sent. `PersonSuspiciousActivityEventData` and the `WebhookEventDataMap` entry are removed. A person rejected on a device they never used raises the `known_person_new_device` signal: subscribe to `signal.raised`.
|
|
8
|
+
|
|
3
9
|
## 1.0.0-rc.18
|
|
4
10
|
|
|
5
11
|
### Major Changes
|
package/README.md
CHANGED
|
@@ -26,6 +26,11 @@ Next.js and Express, billing). The hosted-flow path is in the
|
|
|
26
26
|
npm install @sekyro/node@next
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
+
Samples: [`node-express`](https://github.com/IBTIKAR-Technologies/sekyro-examples/tree/main/node-express) (create a session, receive and
|
|
30
|
+
verify webhooks, finish a Sandbox session in development) and
|
|
31
|
+
[`nextjs-app-router`](https://github.com/IBTIKAR-Technologies/sekyro-examples/tree/main/nextjs-app-router) (Server Action and webhook route
|
|
32
|
+
handler).
|
|
33
|
+
|
|
29
34
|
The SDK is licensed under the
|
|
30
35
|
[Sekyro AI SDK License](https://sekyro.ai/legal/sdk-license).
|
|
31
36
|
|
|
@@ -92,8 +97,8 @@ A session is open while its status is `created`, `in_progress` or
|
|
|
92
97
|
| `rejected` | a check decided against the person, or a reviewer did |
|
|
93
98
|
| `inconclusive` | no verdict could be reached: the model was unsure, the captures stayed unreadable, or a review was not decided by its deadline |
|
|
94
99
|
| `unavailable` | a check could not run |
|
|
95
|
-
| `abandoned` | the person
|
|
96
|
-
| `not_opened` |
|
|
100
|
+
| `abandoned` | the person started the verification but the session expired before a result |
|
|
101
|
+
| `not_opened` | the link was sent but the session expired before it was opened |
|
|
97
102
|
| `policy` | a flow rule stopped the session (location, anonymizer, device, eligibility, your blocks) |
|
|
98
103
|
| `cancelled` | you cancelled the session |
|
|
99
104
|
| `superseded` | a newer session of the same person took its review over (`supersededBy` names it) |
|
|
@@ -18,9 +18,10 @@ type SessionStatus = "created" | "in_progress" | "review_pending" | "verified" |
|
|
|
18
18
|
* Why a `not_verified` session was not verified: `rejected` (a check decided against the
|
|
19
19
|
* person, or a reviewer did), `inconclusive` (no verdict could be reached: the model was
|
|
20
20
|
* unsure, the captures stayed unreadable, or a review was not decided by its deadline),
|
|
21
|
-
* `unavailable` (the check could not run), `abandoned` (the person
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* `unavailable` (the check could not run), `abandoned` (the person started the verification but
|
|
22
|
+
* the session expired before a result), `not_opened` (the link was sent but the session expired
|
|
23
|
+
* before it was opened), `policy` (a flow rule stopped it), `cancelled` (you cancelled it) or
|
|
24
|
+
* `superseded` (a newer session of the same person took its review over).
|
|
24
25
|
* @public
|
|
25
26
|
*/
|
|
26
27
|
type SessionReason = "rejected" | "inconclusive" | "unavailable" | "abandoned" | "not_opened" | "policy" | "cancelled" | "superseded";
|
|
@@ -2423,18 +2424,6 @@ interface SessionLinkExpiry {
|
|
|
2423
2424
|
/** ISO 8601: the new expiry of the link and its session. */
|
|
2424
2425
|
expiresAt: string;
|
|
2425
2426
|
}
|
|
2426
|
-
/**
|
|
2427
|
-
* `data` of `person.suspicious_activity`: a device already linked to ANOTHER
|
|
2428
|
-
* person was used for a session of this person. `count` is the person's running
|
|
2429
|
-
* total of such events. Ids only.
|
|
2430
|
-
* @public
|
|
2431
|
-
*/
|
|
2432
|
-
interface PersonSuspiciousActivityEventData {
|
|
2433
|
-
/** The person (`per_...`). */
|
|
2434
|
-
personId: string;
|
|
2435
|
-
sessionId: string;
|
|
2436
|
-
count: number;
|
|
2437
|
-
}
|
|
2438
2427
|
/**
|
|
2439
2428
|
* `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
|
|
2440
2429
|
* plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
|
|
@@ -2487,7 +2476,6 @@ interface WebhookEventDataMap {
|
|
|
2487
2476
|
"signal.escalated": SignalEventData;
|
|
2488
2477
|
"person.enrolled": PersonEnrolledEventData;
|
|
2489
2478
|
"person.updated": PersonUpdatedEventData;
|
|
2490
|
-
"person.suspicious_activity": PersonSuspiciousActivityEventData;
|
|
2491
2479
|
"person.deleted": PersonDeletedEventData;
|
|
2492
2480
|
"aml.match_flagged": AmlMatchFlaggedEventData;
|
|
2493
2481
|
"payment.received": Record<string, unknown>;
|
|
@@ -2967,4 +2955,4 @@ declare class Sekyro {
|
|
|
2967
2955
|
readiness(): Promise<ReadinessReport>;
|
|
2968
2956
|
}
|
|
2969
2957
|
|
|
2970
|
-
export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type
|
|
2958
|
+
export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type SessionEventStep as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityBirthPlace as a3, type IdentityDocument as a4, type IdentityIdNumber as a5, type IdentityMethod as a6, type IdentityName as a7, type IdentityScalarKey as a8, type IdentitySource as a9, type PersonUpdatedEventData as aA, type PortraitReportEntry as aB, type PriorReviewReason as aC, type ProbeBindingReason as aD, type ProbeQuality as aE, type ProfileDocumentType as aF, type ReadinessProtection as aG, type ReadinessReport as aH, type RequestOptions as aI, type ResultTokenResponse as aJ, type ReviewOutcomeReason as aK, type RevokePersonInput as aL, type ScreenPersonInput as aM, type Screening as aN, type ScreeningHit as aO, type ScreeningHitSummary as aP, type ScreeningList as aQ, type ScreeningStatus as aR, type ScreeningTrigger as aS, type ScreeningUnavailableReason as aT, type SekyroOptions as aU, SekyroTestApi as aV, type Session as aW, type SessionClosedEventDataBase as aX, type SessionDecidingStep as aY, type SessionDevice as aZ, type SessionEventDataBase as a_, type IdentitySources as aa, type LevelTarget as ab, type LiftBlockInput as ac, type ListBlocksQuery as ad, type ListPeopleQuery as ae, type ListScreeningsQuery as af, type ListSessionsQuery as ag, type ListSignalsQuery as ah, type MatchReason as ai, type MediaBytes as aj, type MediaBytesOptions as ak, type MediaItem as al, type MediaKind as am, type MediaList as an, type NameForm as ao, type Page as ap, PeopleApi as aq, type Person as ar, type PersonBirthPlaceInput as as, type PersonDeletedEventData as at, type PersonDocumentInput as au, type PersonEnrolledEventData as av, type PersonRef as aw, type PersonSession as ax, type PersonSessionInput as ay, type PersonSessionTarget as az, type ServiceId as b, type SessionFailureReason as b0, type SessionFlowRef as b1, type SessionHandoff as b2, type SessionHandoffDevice as b3, type SessionLifecycleEventData as b4, type SessionLinkDelivery as b5, type SessionLinkExpiry as b6, type SessionLinkInput as b7, type SessionNetwork as b8, type SessionNetworkEvent as b9, type SubjectIdNumber as bA, type SubjectName as bB, type SubjectReferenceSource as bC, type SubjectReuseTarget as bD, type SubjectStatus as bE, type UpdateSignalInput as bF, type UsageThresholdReachedEventData as bG, type VerifiedContacts as bH, type WebhookEnvelopeOf as bI, type WebhookEventDataMap as bJ, type WebhookTestInput as bK, type WebhookTestResult as bL, WebhooksApi as bM, type SessionNotVerifiedEventData as ba, type SessionRetakeRequestedEventData as bb, type SessionReviewPendingEventData as bc, type SessionScreening as bd, type SessionStatus as be, type SessionStep as bf, type SessionStepAttempts as bg, type SessionStepBand as bh, type SessionStepDecision as bi, type SessionStepDocument as bj, type SessionStepPortrait as bk, SessionTestApi as bl, type SessionVerifiedEventData as bm, SessionsApi as bn, type Signal as bo, type SignalEventData as bp, type SignalEvidence as bq, type SignalGrade as br, type SignalKeyKind as bs, type SignalKind as bt, type SignalSeverity as bu, type SignalStatus as bv, SignalsApi as bw, type SimulateSessionInput as bx, type StepResult as by, type SubjectAssurance as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
|
|
@@ -18,9 +18,10 @@ type SessionStatus = "created" | "in_progress" | "review_pending" | "verified" |
|
|
|
18
18
|
* Why a `not_verified` session was not verified: `rejected` (a check decided against the
|
|
19
19
|
* person, or a reviewer did), `inconclusive` (no verdict could be reached: the model was
|
|
20
20
|
* unsure, the captures stayed unreadable, or a review was not decided by its deadline),
|
|
21
|
-
* `unavailable` (the check could not run), `abandoned` (the person
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* `unavailable` (the check could not run), `abandoned` (the person started the verification but
|
|
22
|
+
* the session expired before a result), `not_opened` (the link was sent but the session expired
|
|
23
|
+
* before it was opened), `policy` (a flow rule stopped it), `cancelled` (you cancelled it) or
|
|
24
|
+
* `superseded` (a newer session of the same person took its review over).
|
|
24
25
|
* @public
|
|
25
26
|
*/
|
|
26
27
|
type SessionReason = "rejected" | "inconclusive" | "unavailable" | "abandoned" | "not_opened" | "policy" | "cancelled" | "superseded";
|
|
@@ -2423,18 +2424,6 @@ interface SessionLinkExpiry {
|
|
|
2423
2424
|
/** ISO 8601: the new expiry of the link and its session. */
|
|
2424
2425
|
expiresAt: string;
|
|
2425
2426
|
}
|
|
2426
|
-
/**
|
|
2427
|
-
* `data` of `person.suspicious_activity`: a device already linked to ANOTHER
|
|
2428
|
-
* person was used for a session of this person. `count` is the person's running
|
|
2429
|
-
* total of such events. Ids only.
|
|
2430
|
-
* @public
|
|
2431
|
-
*/
|
|
2432
|
-
interface PersonSuspiciousActivityEventData {
|
|
2433
|
-
/** The person (`per_...`). */
|
|
2434
|
-
personId: string;
|
|
2435
|
-
sessionId: string;
|
|
2436
|
-
count: number;
|
|
2437
|
-
}
|
|
2438
2427
|
/**
|
|
2439
2428
|
* `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
|
|
2440
2429
|
* plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
|
|
@@ -2487,7 +2476,6 @@ interface WebhookEventDataMap {
|
|
|
2487
2476
|
"signal.escalated": SignalEventData;
|
|
2488
2477
|
"person.enrolled": PersonEnrolledEventData;
|
|
2489
2478
|
"person.updated": PersonUpdatedEventData;
|
|
2490
|
-
"person.suspicious_activity": PersonSuspiciousActivityEventData;
|
|
2491
2479
|
"person.deleted": PersonDeletedEventData;
|
|
2492
2480
|
"aml.match_flagged": AmlMatchFlaggedEventData;
|
|
2493
2481
|
"payment.received": Record<string, unknown>;
|
|
@@ -2967,4 +2955,4 @@ declare class Sekyro {
|
|
|
2967
2955
|
readiness(): Promise<ReadinessReport>;
|
|
2968
2956
|
}
|
|
2969
2957
|
|
|
2970
|
-
export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type
|
|
2958
|
+
export { type FlowSummary as $, type AgeMethod as A, type Block as B, type CreatedSession as C, type ConnectorIdentity as D, type CreateBlockInput as E, type FetchLike as F, type CreateSessionInput as G, DEFAULT_BASE_URL as H, DEFAULT_TIMEOUT_MS as I, type DecisionReason as J, type DeepPartial as K, type Locale as L, type DeletedPerson as M, type DeliverOptions as N, type Device as O, DevicesApi as P, type DocumentSubstitutionSettings as Q, type ReviewReason as R, type SessionReason as S, type EidResult as T, type EligibilityReason as U, type VerificationLevel as V, type WebhookEventType as W, type ExtendLinkInput as X, type FlowOverridableSettings as Y, type FlowOverrides as Z, type FlowServiceSettings as _, Sekyro as a, type SessionEventStep as a$, FlowsApi as a0, type IdNumberReason as a1, type Identity as a2, type IdentityBirthPlace as a3, type IdentityDocument as a4, type IdentityIdNumber as a5, type IdentityMethod as a6, type IdentityName as a7, type IdentityScalarKey as a8, type IdentitySource as a9, type PersonUpdatedEventData as aA, type PortraitReportEntry as aB, type PriorReviewReason as aC, type ProbeBindingReason as aD, type ProbeQuality as aE, type ProfileDocumentType as aF, type ReadinessProtection as aG, type ReadinessReport as aH, type RequestOptions as aI, type ResultTokenResponse as aJ, type ReviewOutcomeReason as aK, type RevokePersonInput as aL, type ScreenPersonInput as aM, type Screening as aN, type ScreeningHit as aO, type ScreeningHitSummary as aP, type ScreeningList as aQ, type ScreeningStatus as aR, type ScreeningTrigger as aS, type ScreeningUnavailableReason as aT, type SekyroOptions as aU, SekyroTestApi as aV, type Session as aW, type SessionClosedEventDataBase as aX, type SessionDecidingStep as aY, type SessionDevice as aZ, type SessionEventDataBase as a_, type IdentitySources as aa, type LevelTarget as ab, type LiftBlockInput as ac, type ListBlocksQuery as ad, type ListPeopleQuery as ae, type ListScreeningsQuery as af, type ListSessionsQuery as ag, type ListSignalsQuery as ah, type MatchReason as ai, type MediaBytes as aj, type MediaBytesOptions as ak, type MediaItem as al, type MediaKind as am, type MediaList as an, type NameForm as ao, type Page as ap, PeopleApi as aq, type Person as ar, type PersonBirthPlaceInput as as, type PersonDeletedEventData as at, type PersonDocumentInput as au, type PersonEnrolledEventData as av, type PersonRef as aw, type PersonSession as ax, type PersonSessionInput as ay, type PersonSessionTarget as az, type ServiceId as b, type SessionFailureReason as b0, type SessionFlowRef as b1, type SessionHandoff as b2, type SessionHandoffDevice as b3, type SessionLifecycleEventData as b4, type SessionLinkDelivery as b5, type SessionLinkExpiry as b6, type SessionLinkInput as b7, type SessionNetwork as b8, type SessionNetworkEvent as b9, type SubjectIdNumber as bA, type SubjectName as bB, type SubjectReferenceSource as bC, type SubjectReuseTarget as bD, type SubjectStatus as bE, type UpdateSignalInput as bF, type UsageThresholdReachedEventData as bG, type VerifiedContacts as bH, type WebhookEnvelopeOf as bI, type WebhookEventDataMap as bJ, type WebhookTestInput as bK, type WebhookTestResult as bL, WebhooksApi as bM, type SessionNotVerifiedEventData as ba, type SessionRetakeRequestedEventData as bb, type SessionReviewPendingEventData as bc, type SessionScreening as bd, type SessionStatus as be, type SessionStep as bf, type SessionStepAttempts as bg, type SessionStepBand as bh, type SessionStepDecision as bi, type SessionStepDocument as bj, type SessionStepPortrait as bk, SessionTestApi as bl, type SessionVerifiedEventData as bm, SessionsApi as bn, type Signal as bo, type SignalEventData as bp, type SignalEvidence as bq, type SignalGrade as br, type SignalKeyKind as bs, type SignalKind as bt, type SignalSeverity as bu, type SignalStatus as bv, SignalsApi as bw, type SimulateSessionInput as bx, type StepResult as by, type SubjectAssurance as bz, type SessionPersonInput as c, type WebhookEnvelope as d, type SekyroEnvironment as e, type VerificationAssurance as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type SessionSignal as j, type FailureIdentification as k, type AgeResult as l, type AmlMatchFlaggedEventData as m, type ApiKeyIdentity as n, type BlockCheck as o, type BlockCheckInput as p, type BlockDuration as q, type BlockIdNumber as r, type BlockKind as s, type BlockMatch as t, type BlockReason as u, BlocksApi as v, type CameraUnavailableCause as w, type CheckState as x, type CheckType as y, type ClosedBy as z };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-
|
|
2
|
-
import '../../client-
|
|
1
|
+
import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-CyNFdiLv.cjs';
|
|
2
|
+
import '../../client-BSzMfacG.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-
|
|
2
|
-
import '../../client-
|
|
1
|
+
import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-D0CDGAOJ.js';
|
|
2
|
+
import '../../client-BSzMfacG.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* `@sekyro/node/connect/express`: a route gate for Express (and any
|
package/dist/connect/index.d.cts
CHANGED
|
@@ -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-
|
|
2
|
-
export { A as AgeMethod, W as WebhookEventType } from '../client-
|
|
1
|
+
export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-CyNFdiLv.cjs';
|
|
2
|
+
export { A as AgeMethod, W as WebhookEventType } from '../client-BSzMfacG.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Why a connector refused to act:
|
package/dist/connect/index.d.ts
CHANGED
|
@@ -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-
|
|
2
|
-
export { A as AgeMethod, W as WebhookEventType } from '../client-
|
|
1
|
+
export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-D0CDGAOJ.js';
|
|
2
|
+
export { A as AgeMethod, W as WebhookEventType } from '../client-BSzMfacG.js';
|
|
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-
|
|
2
|
-
import '../../client-
|
|
1
|
+
import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-CyNFdiLv.cjs';
|
|
2
|
+
import '../../client-BSzMfacG.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-
|
|
2
|
-
import '../../client-
|
|
1
|
+
import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-D0CDGAOJ.js';
|
|
2
|
+
import '../../client-BSzMfacG.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* `@sekyro/node/connect/next`: gate helpers for Next.js middleware, route
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-
|
|
1
|
+
import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-BSzMfacG.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The Sekyro claim contract and its only state machine, `mergeClaim` (spec
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-
|
|
1
|
+
import { A as AgeMethod, S as SessionReason, W as WebhookEventType, L as Locale, C as CreatedSession, a as Sekyro, F as FetchLike } from './client-BSzMfacG.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The Sekyro claim contract and its only state machine, `mergeClaim` (spec
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.18";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook});
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.19";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-
|
|
2
|
-
export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as
|
|
1
|
+
import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-BSzMfacG.cjs';
|
|
2
|
+
export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as PersonUpdatedEventData, aB as PortraitReportEntry, aC as PriorReviewReason, aD as ProbeBindingReason, aE as ProbeQuality, aF as ProfileDocumentType, aG as ReadinessProtection, aH as ReadinessReport, aI as RequestOptions, aJ as ResultTokenResponse, aK as ReviewOutcomeReason, aL as RevokePersonInput, aM as ScreenPersonInput, aN as Screening, aO as ScreeningHit, aP as ScreeningHitSummary, aQ as ScreeningList, aR as ScreeningStatus, aS as ScreeningTrigger, aT as ScreeningUnavailableReason, a as Sekyro, aU as SekyroOptions, aV as SekyroTestApi, aW as Session, aX as SessionClosedEventDataBase, aY as SessionDecidingStep, aZ as SessionDevice, a_ as SessionEventDataBase, a$ as SessionEventStep, b0 as SessionFailureReason, b1 as SessionFlowRef, b2 as SessionHandoff, b3 as SessionHandoffDevice, b4 as SessionLifecycleEventData, b5 as SessionLinkDelivery, b6 as SessionLinkExpiry, b7 as SessionLinkInput, b8 as SessionNetwork, b9 as SessionNetworkEvent, ba as SessionNotVerifiedEventData, S as SessionReason, bb as SessionRetakeRequestedEventData, bc as SessionReviewPendingEventData, bd as SessionScreening, be as SessionStatus, bf as SessionStep, bg as SessionStepAttempts, bh as SessionStepBand, bi as SessionStepDecision, bj as SessionStepDocument, bk as SessionStepPortrait, bl as SessionTestApi, bm as SessionVerifiedEventData, bn as SessionsApi, bo as Signal, bp as SignalEventData, bq as SignalEvidence, br as SignalGrade, bs as SignalKeyKind, bt as SignalKind, bu as SignalSeverity, bv as SignalStatus, bw as SignalsApi, bx as SimulateSessionInput, by as StepResult, bz as SubjectAssurance, bA as SubjectIdNumber, bB as SubjectName, bC as SubjectReferenceSource, bD as SubjectReuseTarget, bE as SubjectStatus, bF as UpdateSignalInput, bG as UsageThresholdReachedEventData, bH as VerifiedContacts, bI as WebhookEnvelopeOf, bJ as WebhookEventDataMap, W as WebhookEventType, bK as WebhookTestInput, bL as WebhookTestResult, bM as WebhooksApi } from './client-BSzMfacG.cjs';
|
|
3
3
|
|
|
4
4
|
/** Why {@link verifyWebhook} rejected a delivery. @public */
|
|
5
5
|
type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-
|
|
2
|
-
export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as
|
|
1
|
+
import { b as ServiceId, c as SessionPersonInput, d as WebhookEnvelope, R as ReviewReason, e as SekyroEnvironment, V as VerificationLevel, f as VerificationAssurance, g as VerificationUnit, h as SubjectReuseMode, i as ResultCheckProofs, j as SessionSignal, A as AgeMethod, k as FailureIdentification, F as FetchLike } from './client-BSzMfacG.js';
|
|
2
|
+
export { l as AgeResult, m as AmlMatchFlaggedEventData, n as ApiKeyIdentity, B as Block, o as BlockCheck, p as BlockCheckInput, q as BlockDuration, r as BlockIdNumber, s as BlockKind, t as BlockMatch, u as BlockReason, v as BlocksApi, w as CameraUnavailableCause, x as CheckState, y as CheckType, z as ClosedBy, D as ConnectorIdentity, E as CreateBlockInput, G as CreateSessionInput, C as CreatedSession, H as DEFAULT_BASE_URL, I as DEFAULT_TIMEOUT_MS, J as DecisionReason, K as DeepPartial, M as DeletedPerson, N as DeliverOptions, O as Device, P as DevicesApi, Q as DocumentSubstitutionSettings, T as EidResult, U as EligibilityReason, X as ExtendLinkInput, Y as FlowOverridableSettings, Z as FlowOverrides, _ as FlowServiceSettings, $ as FlowSummary, a0 as FlowsApi, a1 as IdNumberReason, a2 as Identity, a3 as IdentityBirthPlace, a4 as IdentityDocument, a5 as IdentityIdNumber, a6 as IdentityMethod, a7 as IdentityName, a8 as IdentityScalarKey, a9 as IdentitySource, aa as IdentitySources, ab as LevelTarget, ac as LiftBlockInput, ad as ListBlocksQuery, ae as ListPeopleQuery, af as ListScreeningsQuery, ag as ListSessionsQuery, ah as ListSignalsQuery, L as Locale, ai as MatchReason, aj as MediaBytes, ak as MediaBytesOptions, al as MediaItem, am as MediaKind, an as MediaList, ao as NameForm, ap as Page, aq as PeopleApi, ar as Person, as as PersonBirthPlaceInput, at as PersonDeletedEventData, au as PersonDocumentInput, av as PersonEnrolledEventData, aw as PersonRef, ax as PersonSession, ay as PersonSessionInput, az as PersonSessionTarget, aA as PersonUpdatedEventData, aB as PortraitReportEntry, aC as PriorReviewReason, aD as ProbeBindingReason, aE as ProbeQuality, aF as ProfileDocumentType, aG as ReadinessProtection, aH as ReadinessReport, aI as RequestOptions, aJ as ResultTokenResponse, aK as ReviewOutcomeReason, aL as RevokePersonInput, aM as ScreenPersonInput, aN as Screening, aO as ScreeningHit, aP as ScreeningHitSummary, aQ as ScreeningList, aR as ScreeningStatus, aS as ScreeningTrigger, aT as ScreeningUnavailableReason, a as Sekyro, aU as SekyroOptions, aV as SekyroTestApi, aW as Session, aX as SessionClosedEventDataBase, aY as SessionDecidingStep, aZ as SessionDevice, a_ as SessionEventDataBase, a$ as SessionEventStep, b0 as SessionFailureReason, b1 as SessionFlowRef, b2 as SessionHandoff, b3 as SessionHandoffDevice, b4 as SessionLifecycleEventData, b5 as SessionLinkDelivery, b6 as SessionLinkExpiry, b7 as SessionLinkInput, b8 as SessionNetwork, b9 as SessionNetworkEvent, ba as SessionNotVerifiedEventData, S as SessionReason, bb as SessionRetakeRequestedEventData, bc as SessionReviewPendingEventData, bd as SessionScreening, be as SessionStatus, bf as SessionStep, bg as SessionStepAttempts, bh as SessionStepBand, bi as SessionStepDecision, bj as SessionStepDocument, bk as SessionStepPortrait, bl as SessionTestApi, bm as SessionVerifiedEventData, bn as SessionsApi, bo as Signal, bp as SignalEventData, bq as SignalEvidence, br as SignalGrade, bs as SignalKeyKind, bt as SignalKind, bu as SignalSeverity, bv as SignalStatus, bw as SignalsApi, bx as SimulateSessionInput, by as StepResult, bz as SubjectAssurance, bA as SubjectIdNumber, bB as SubjectName, bC as SubjectReferenceSource, bD as SubjectReuseTarget, bE as SubjectStatus, bF as UpdateSignalInput, bG as UsageThresholdReachedEventData, bH as VerifiedContacts, bI as WebhookEnvelopeOf, bJ as WebhookEventDataMap, W as WebhookEventType, bK as WebhookTestInput, bL as WebhookTestResult, bM as WebhooksApi } from './client-BSzMfacG.js';
|
|
3
3
|
|
|
4
4
|
/** Why {@link verifyWebhook} rejected a delivery. @public */
|
|
5
5
|
type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.18";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook};
|
|
1
|
+
var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",env_required:'`env` is required by verifyResultToken: pass "live" or "sandbox"',key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;fieldErrors;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.fieldErrors=fieldErrorsOf(init.details),this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function fieldErrorsOf(details){if(typeof details!="object"||details===null)return;let raw=details.fieldErrors;if(!Array.isArray(raw))return;let out=[];for(let entry of raw){if(typeof entry!="object"||entry===null)continue;let{field,code,expected}=entry;if(typeof field!="string"||typeof code!="string")continue;let item={field,code};typeof expected=="string"&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="1.0.0-rc.19";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){return typeof error.requestId=="string"?error.requestId:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){return this.t.call("POST","/sessions",input,opts.idempotencyKey)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;if(query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.reason!==void 0&&qs.set("reason",query.reason),query.closedBy!==void 0&&qs.set("closedBy",query.closedBy),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),query.deviceId!==void 0&&(assertId(m,query.deviceId,"deviceId"),qs.set("deviceId",query.deviceId)),query.signalKind!==void 0){let kinds=[...new Set(Array.isArray(query.signalKind)?query.signalKind:[query.signalKind])];if(kinds.length===0||kinds.some(k=>typeof k!="string"||k.length===0))throw new TypeError(`${m}: \`signalKind\` must be a kind or a non-empty list of kinds`);qs.set("signalKind",kinds.join(","))}query.signalSeverity!==void 0&&qs.set("signalSeverity",query.signalSeverity),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},FlowsApi=class{constructor(t){this.t=t}t;async list(){return this.t.call("GET","/flows")}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&"personId"in target)assertId(m,target.personId),path=path1("/people",target.personId,"/sessions");else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);return this.t.call("POST",path,input,opts.idempotencyKey)}},BlocksApi=class{constructor(t){this.t=t}t;async create(input,opts={}){return this.t.call("POST","/blocks",input,opts.idempotencyKey??globalThis.crypto.randomUUID())}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;return query?.kind!==void 0&&qs.set("kind",query.kind),query?.status!==void 0&&qs.set("status",query.status),setPaging("blocks.list",qs,query??{}),this.t.page(withQuery("/blocks",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("blocks.get",id),this.t.call("GET",path1("/blocks",id))}async lift(id,input={},opts={}){return assertId("blocks.lift",id),this.t.call("DELETE",path1("/blocks",id),input,opts.idempotencyKey)}async check(input){return this.t.call("POST","/blocks/check",input)}},SignalsApi=class{constructor(t){this.t=t}t;async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="signals.list",qs=new URLSearchParams;return query.kind!==void 0&&qs.set("kind",query.kind),query.severity!==void 0&&qs.set("severity",query.severity),query.status!==void 0&&qs.set("status",query.status),query.since!==void 0&&qs.set("since",isoOf(m,"since",query.since)),query.until!==void 0&&qs.set("until",isoOf(m,"until",query.until)),setPaging(m,qs,query),this.t.page(withQuery("/signals",qs))}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async get(id){return assertId("signals.get",id),this.t.call("GET",path1("/signals",id))}async update(id,input,opts={}){return assertId("signals.update",id),this.t.call("PATCH",path1("/signals",id),input,opts.idempotencyKey)}},DevicesApi=class{constructor(t){this.t=t}t;async get(deviceId){return assertId("devices.get",deviceId,"deviceId"),this.t.call("GET",path1("/devices",deviceId))}async update(deviceId,input,opts={}){return assertId("devices.update",deviceId,"deviceId"),this.t.call("PATCH",path1("/devices",deviceId),input,opts.idempotencyKey)}},WebhooksApi=class{constructor(t){this.t=t}t;async test(input={}){return this.t.call("POST","/webhooks/test",input)}},SessionTestApi=class{constructor(t){this.t=t}t;async simulate(id,input,opts={}){return assertId("test.sessions.simulate",id),this.t.call("POST",path1("/sessions",id,"/simulate"),input,opts.idempotencyKey)}},SekyroTestApi=class{sessions;constructor(t){this.sessions=new SessionTestApi(t)}},Sekyro=class{sessions;people;blocks;signals;devices;flows;webhooks;test;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.blocks=new BlocksApi(bound),this.signals=new SignalsApi(bound),this.devices=new DevicesApi(bound),this.flows=new FlowsApi(bound),this.webhooks=new WebhooksApi(bound),this.test=new SekyroTestApi(bound),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async me(){return this.#transport.call("GET","/me")}async readiness(){return this.#transport.call("GET","/readiness")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){if(claim.status!=="verified")throw new SekyroResultTokenError("invalid_token","The result token does not carry `status: verified`");let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,status:"verified",unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.personId=personIdOf(subjectId));let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals});let signals=signalsOf(claim.signals);signals!==void 0&&(out.signals=signals);let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function personIdOf(id){return id===""||id.startsWith("per_")?id:`per_${id}`}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}var SEVERITIES=new Set(["low","medium","high"]);function signalsOf(raw){if(!Array.isArray(raw))return;let out=[];for(let e of raw){if(!isRecord2(e)||typeof e.kind!="string"||e.kind===""||!SEVERITIES.has(e.severity))continue;let evidence=Array.isArray(e.evidence)?e.evidence.filter(c=>typeof c=="string"&&c!==""):[];if(evidence.length===0)continue;let entry={kind:e.kind,severity:e.severity,evidence};isRecord2(e.details)&&Array.isArray(e.details.people)&&(entry.details={people:e.details.people.filter(isRecord2).map(p=>{let person={personId:personIdOf(str(p.person_id)??"")},ref=str(p.external_ref);return ref!==void 0&&(person.externalRef=ref),person})});let signalId=str(e.signal_id);signalId!==void 0&&(entry.signalId=signalId),out.push(entry)}return out.length>0?out:void 0}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},person=str(m.person_id);person!==void 0&&(match.personId=personIdOf(person));let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroResultTokenError("env_required");if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,verifyResultToken,verifyWebhook};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sekyro/node",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.19",
|
|
4
4
|
"description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
package/sbom.cdx.json
CHANGED
|
@@ -97,8 +97,8 @@
|
|
|
97
97
|
"type": "application",
|
|
98
98
|
"name": "node",
|
|
99
99
|
"group": "@sekyro",
|
|
100
|
-
"version": "1.0.0-rc.
|
|
101
|
-
"bom-ref": "@sekyro/node@1.0.0-rc.
|
|
100
|
+
"version": "1.0.0-rc.19",
|
|
101
|
+
"bom-ref": "@sekyro/node@1.0.0-rc.19",
|
|
102
102
|
"description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
|
|
103
103
|
"licenses": [
|
|
104
104
|
{
|
|
@@ -108,7 +108,7 @@
|
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
],
|
|
111
|
-
"purl": "pkg:npm/%40sekyro/node@1.0.0-rc.
|
|
111
|
+
"purl": "pkg:npm/%40sekyro/node@1.0.0-rc.19?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
|
|
112
112
|
"externalReferences": [
|
|
113
113
|
{
|
|
114
114
|
"url": "https://github.com/IBTIKAR-Technologies/ibtikar-identity/issues",
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
"type": "library",
|
|
150
150
|
"name": "jose",
|
|
151
151
|
"version": "5.10.0",
|
|
152
|
-
"bom-ref": "@sekyro/node@1.0.0-rc.
|
|
152
|
+
"bom-ref": "@sekyro/node@1.0.0-rc.19|jose@5.10.0",
|
|
153
153
|
"licenses": [
|
|
154
154
|
{
|
|
155
155
|
"license": {
|
|
@@ -182,13 +182,13 @@
|
|
|
182
182
|
],
|
|
183
183
|
"dependencies": [
|
|
184
184
|
{
|
|
185
|
-
"ref": "@sekyro/node@1.0.0-rc.
|
|
185
|
+
"ref": "@sekyro/node@1.0.0-rc.19",
|
|
186
186
|
"dependsOn": [
|
|
187
|
-
"@sekyro/node@1.0.0-rc.
|
|
187
|
+
"@sekyro/node@1.0.0-rc.19|jose@5.10.0"
|
|
188
188
|
]
|
|
189
189
|
},
|
|
190
190
|
{
|
|
191
|
-
"ref": "@sekyro/node@1.0.0-rc.
|
|
191
|
+
"ref": "@sekyro/node@1.0.0-rc.19|jose@5.10.0"
|
|
192
192
|
}
|
|
193
193
|
]
|
|
194
194
|
}
|