@sekyro/node 0.1.0-rc.10 → 0.1.0-rc.11

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.
@@ -11,9 +11,12 @@ type SessionStatus = "created" | "in_progress" | "review_pending" | "completed"
11
11
  /**
12
12
  * Terminal verdict, orthogonal to {@link SessionStatus}. `null` until the session
13
13
  * reaches a terminal status; `review` when a human reviewer must adjudicate.
14
+ * `superseded` (status `completed`): the session waited for a review and a newer
15
+ * attempt of the same person took that review over (`session.superseded`); read
16
+ * the newer session for the verdict.
14
17
  * @public
15
18
  */
16
- type SessionOutcome = "approved" | "review" | "rejected";
19
+ type SessionOutcome = "approved" | "review" | "rejected" | "superseded";
17
20
  /**
18
21
  * What a finished session proved: `1` a live, real person (human), `2` that
19
22
  * person's identity (document, chip, registry or supplied data bound to the
@@ -191,6 +194,92 @@ type CameraUnavailableCause = "denied" | "no_camera";
191
194
  * @public
192
195
  */
193
196
  type MatchReason = "name_mismatch" | "birth_date_mismatch" | "nationality_mismatch" | "document_number_mismatch";
197
+ /**
198
+ * Reasons a `face_match` {@link SessionStep.reason} carries when an earlier
199
+ * human review of the same person, reference photo and face settled the match
200
+ * score instead of a new review: `prior_review_approved` (the step passed;
201
+ * final) and `prior_review_rejected` (the step failed; retryable, a better
202
+ * capture sends the session to a reviewer again). Both are billed like
203
+ * `review_band`. The step's {@link SessionStep.decision} has
204
+ * `source: "prior_review"` and names your earlier session.
205
+ * @public
206
+ */
207
+ type PriorReviewReason = "prior_review_approved" | "prior_review_rejected";
208
+ /**
209
+ * Review outcome reasons any reviewable step may carry: `superseded_by_retry`
210
+ * (a newer attempt of the same person took the review over; the session ends
211
+ * with outcome `superseded`) and `review_split` (two reviewers disagreed and
212
+ * nobody settled it before the review deadline; the session is rejected).
213
+ * Both are billed and retryable: the person may verify again. Neither counts
214
+ * toward the device cooldown.
215
+ * @public
216
+ */
217
+ type ReviewOutcomeReason = "superseded_by_retry" | "review_split";
218
+ /**
219
+ * What a review decision is about, on {@link SessionStepDecision.reasons}: the
220
+ * part that failed on a rejection (several may apply), or the check the
221
+ * reviewer overrode on an approval.
222
+ * @public
223
+ */
224
+ type ReviewReason = "document_authenticity" | "liveness" | "face_match" | "data_mismatch" | "other";
225
+ /**
226
+ * How a person decided a step: a reviewer (`source: "review"`), or an earlier
227
+ * review of the same person, reference photo and face that was reused
228
+ * (`source: "prior_review"`). Counts and enums only: never a reviewer's
229
+ * identity and never an individual vote.
230
+ * @public
231
+ */
232
+ interface SessionStepDecision {
233
+ source: "review" | "prior_review";
234
+ /** One reviewer (`single`) or two independent reviewers (`dual`). */
235
+ mode: "single" | "dual";
236
+ /** How many reviewer votes formed the decision (a third vote settles a dual split). */
237
+ votes: 1 | 2 | 3;
238
+ /** Dual review only: whether the first two reviewers agreed. */
239
+ agreement?: boolean;
240
+ /** What the decision was about ({@link ReviewReason}). */
241
+ reasons: ReviewReason[];
242
+ /** ISO 8601: when the decision was made. */
243
+ decidedAt: string;
244
+ /** `prior_review` only: your earlier session whose review decided this one. */
245
+ sessionId?: string;
246
+ }
247
+ /**
248
+ * A failure identification match (terminal sessions, when the flow's
249
+ * identify-failures setting is on and the search found one): who the face
250
+ * matches when the face match did not prove the claimed identity against a
251
+ * registry portrait. A signal, never a decision: the session state is
252
+ * unchanged. Ids, enums and numbers only, never a name or an ID number.
253
+ *
254
+ * `kind`: `presenter` (the live person is most likely the matched record),
255
+ * `shown_face` (the photo or screen shown carries the matched record, a
256
+ * possible victim) or `other_identity`. `other_identity` is informational
257
+ * only: the registry also knows this face under another record. The person may
258
+ * legitimately hold more than one identity document, for example a foreign
259
+ * passport, an older document, a second nationality or a residence permit. Do
260
+ * not treat this signal alone as fraud: use it as a lead for your own process.
261
+ * @public
262
+ */
263
+ interface FailureIdentification {
264
+ kind: "presenter" | "shown_face" | "other_identity";
265
+ /** The search scope: your verified persons (`org`) or the whole registry index (`registry`). */
266
+ scope: "org" | "registry";
267
+ match: {
268
+ /** Your verified subject for the matched person, when you hold one. */
269
+ subjectId?: string;
270
+ /** An opaque reference of the matched person when you hold no verified subject for it, scoped to your organisation. */
271
+ reference?: string;
272
+ /** The registry photo that matched (an opaque id, scoped to your organisation). */
273
+ photoId?: string;
274
+ /** The grade of that photo: `1` or `2` registry, `3` an older bulk import photo. */
275
+ tier: 1 | 2 | 3;
276
+ /** Calibrated similarity on the face match scale, in [0, 1]. */
277
+ score: number;
278
+ band: "strong" | "moderate";
279
+ };
280
+ /** With `other_identity`: the reference the session passed against. */
281
+ referenceSource?: "registry" | "chip" | "document" | "subject" | "org_supplied";
282
+ }
194
283
  /**
195
284
  * Face-match probe-binding reason a `face_match` {@link SessionStep.reason} may
196
285
  * carry (SDK spec §4.10): `probe_not_from_liveness` — the face image isn't the
@@ -241,6 +330,11 @@ interface SessionStep {
241
330
  * information only: it never changes the step's state or reason.
242
331
  */
243
332
  probeQuality?: ProbeQuality;
333
+ /**
334
+ * How a person decided this step ({@link SessionStepDecision}); absent when
335
+ * no person decided it.
336
+ */
337
+ decision?: SessionStepDecision;
244
338
  }
245
339
  /**
246
340
  * The probe-quality measurement on a `face_match` step. Numbers only; `null`
@@ -1094,6 +1188,12 @@ interface Session {
1094
1188
  * fetched with {@link SessionsApi.portrait}.
1095
1189
  */
1096
1190
  portraitAvailable?: boolean;
1191
+ /**
1192
+ * Terminal sessions: a failure identification match
1193
+ * ({@link FailureIdentification}), present only for a match and only when the
1194
+ * setting is on. A signal, never a decision.
1195
+ */
1196
+ failureIdentification?: FailureIdentification;
1097
1197
  }
1098
1198
  /**
1099
1199
  * `data` of the terminal / review-pending session lifecycle events
@@ -1128,8 +1228,11 @@ interface SessionLifecycleEventData {
1128
1228
  * result tokens are not enabled.
1129
1229
  */
1130
1230
  resultToken?: string;
1131
- /** The checks on the session's path (checks of a lane the person did not take are omitted). */
1132
- steps?: Array<Pick<SessionStep, "checkType" | "state" | "nodeId" | "service">>;
1231
+ /**
1232
+ * The checks on the session's path (checks of a lane the person did not take
1233
+ * are omitted), each with its {@link SessionStepDecision} when a person decided it.
1234
+ */
1235
+ steps?: Array<Pick<SessionStep, "checkType" | "state" | "nodeId" | "service" | "decision">>;
1133
1236
  /** Sekyro flows: the flow version the session runs (absent on sessions created before flows). */
1134
1237
  flow?: SessionFlowRef;
1135
1238
  /** Machine-readable reason, when the transition has one. */
@@ -1189,6 +1292,12 @@ interface SessionLifecycleEventData {
1189
1292
  * with {@link SessionsApi.portrait} (the event never carries the image).
1190
1293
  */
1191
1294
  portraitAvailable?: boolean;
1295
+ /**
1296
+ * On `completed` / `failed`: a failure identification match
1297
+ * ({@link FailureIdentification}), when the setting is on and the search
1298
+ * found one before the event was sent. A signal, never a decision.
1299
+ */
1300
+ failureIdentification?: FailureIdentification;
1192
1301
  }
1193
1302
  /**
1194
1303
  * `data` of `subject.updated` — either a session linked to the subject reached
@@ -1383,16 +1492,60 @@ interface SessionStepCompletedEventData {
1383
1492
  verifiedContacts?: VerifiedContacts;
1384
1493
  }
1385
1494
  /**
1386
- * `data` of `session.review_decided` — a human (or the review-timeout sweep)
1387
- * decided a pending review. `outcome` speaks the REVIEW vocabulary
1388
- * (`pass` | `fail`), not the session outcome; `reason` is the reviewer's code
1389
- * (e.g. `review_timeout` for an expired review).
1495
+ * `data` of `session.review_decided`: a human (or the review deadline) decided
1496
+ * a pending review. `outcome` speaks the REVIEW vocabulary (`pass` | `fail`),
1497
+ * not the session outcome; `reason` is the reviewer's code, `review_timeout`
1498
+ * when the review expired, or `review_split` when two reviewers disagreed and
1499
+ * nobody settled it by the deadline. A reviewer's decision also carries
1500
+ * `reasons`, `decision` and the terminal fields of `session.completed` /
1501
+ * `session.failed`; a deadline carries the ids only.
1390
1502
  * @public
1391
1503
  */
1392
1504
  interface SessionReviewDecidedEventData {
1393
1505
  sessionId: string;
1394
1506
  outcome: "pass" | "fail";
1395
1507
  reason: string;
1508
+ /** A reviewer's decision: what it was about ({@link ReviewReason}). */
1509
+ reasons?: ReviewReason[];
1510
+ /** A reviewer's decision: how it was formed ({@link SessionStepDecision}; counts only). */
1511
+ decision?: SessionStepDecision;
1512
+ /** The app the session belongs to. */
1513
+ appId?: string;
1514
+ /** What the session proved ({@link VerificationLevel}). */
1515
+ level?: VerificationLevel | null;
1516
+ /** How the level was proved. */
1517
+ assurance?: VerificationAssurance | null;
1518
+ /** The billing unit the session consumed. */
1519
+ unit?: VerificationUnit | null;
1520
+ /** ISO 8601 terminal time. */
1521
+ verifiedAt?: string;
1522
+ /** Device and network risk facts, when recorded. */
1523
+ risk?: ResultRisk;
1524
+ /** Other subjects the face matched, when a duplicate search ran. */
1525
+ duplicates?: ResultDuplicate[];
1526
+ /** The duplicate search could not run. */
1527
+ dedupUnavailable?: true;
1528
+ /** The minimum age the session proved and how ({@link AgeResult}), when the flow sets one. */
1529
+ age?: AgeResult;
1530
+ /** A failure identification match ({@link FailureIdentification}), when the setting is on and the search found one. */
1531
+ failureIdentification?: FailureIdentification;
1532
+ /** The `link.state` the session was created with, echoed back; absent when the session had none. */
1533
+ link?: {
1534
+ state: string;
1535
+ };
1536
+ /** The signed result token (ES256 JWT, valid 10 minutes), when result tokens are enabled. */
1537
+ resultToken?: string;
1538
+ /** The agent reference sent as `assistedBy` at create, for assisted capture. */
1539
+ assistedBy?: {
1540
+ externalRef: string;
1541
+ };
1542
+ /** Dotted paths the session's create-time {@link CreateSessionInput.overrides} changed. */
1543
+ overriddenFields?: string[];
1544
+ /**
1545
+ * On a session created for an existing subject: `recheck` (the same person
1546
+ * again) or `step_up` (raised to identity level). Absent otherwise.
1547
+ */
1548
+ reuseMode?: SubjectReuseMode;
1396
1549
  /** Sekyro flows: the flow version the session runs (absent on sessions created before flows). */
1397
1550
  flow?: SessionFlowRef;
1398
1551
  /** The subject (person) the session is linked to, once that subject has passed a verification (absent before that). */
@@ -1411,6 +1564,24 @@ interface SessionReviewDecidedEventData {
1411
1564
  /** ID mode only: the ICAO portrait can be fetched with {@link SessionsApi.portrait}. */
1412
1565
  portraitAvailable?: boolean;
1413
1566
  }
1567
+ /**
1568
+ * `data` of `session.superseded`: a session that waited for a review closed
1569
+ * because a newer attempt of the same person took that review over. The
1570
+ * session ends with status `completed` and outcome `superseded`, its review
1571
+ * step failed with `superseded_by_retry`; nothing of it is deleted. Read the
1572
+ * newer session (`supersededBy`) for the verdict.
1573
+ * @public
1574
+ */
1575
+ interface SessionSupersededEventData {
1576
+ sessionId: string;
1577
+ /** The newer session of the same person that took the review over. */
1578
+ supersededBy: string;
1579
+ /** The review case both sessions belong to (an opaque id). */
1580
+ caseId: string;
1581
+ reason: "superseded_by_retry";
1582
+ /** Your own id for the person, from `subject.externalRef` at create. */
1583
+ externalRef?: string;
1584
+ }
1414
1585
  /**
1415
1586
  * `usage.threshold_reached`: a usage, credit or spend threshold of the organization's
1416
1587
  * plan was reached (sent once per threshold and period). `kind` is `tier` for a monthly
@@ -1446,6 +1617,7 @@ interface WebhookEventDataMap {
1446
1617
  "session.completed": SessionLifecycleEventData;
1447
1618
  "session.expired": SessionLifecycleEventData;
1448
1619
  "session.failed": SessionLifecycleEventData;
1620
+ "session.superseded": SessionSupersededEventData;
1449
1621
  "subject.enrolled": SubjectEnrolledEventData;
1450
1622
  "subject.updated": SubjectUpdatedEventData;
1451
1623
  "subject.suspicious_activity": SubjectSuspiciousActivityEventData;
@@ -1598,8 +1770,11 @@ declare class SessionsApi {
1598
1770
  * `sekyro.subjects` — read and manage subjects (the same person across your
1599
1771
  * apps). Reads need the `subjects:read` scope, `revoke` / `delete` the
1600
1772
  * `subjects:write` scope (keys minted from the dashboard carry both; an older
1601
- * key answers `403 insufficient_scope`). A foreign or unknown id answers
1602
- * `404 subject_not_found`.
1773
+ * key answers `403 insufficient_scope`). A subject is visible once the
1774
+ * person has passed a verification: a subject that never passed, an unknown
1775
+ * id and a subject of another organization or environment all answer the same
1776
+ * `404 subject_not_found` on `get`, `revoke` and `delete`, and `list` leaves
1777
+ * it out.
1603
1778
  *
1604
1779
  * Type-only export, like {@link SessionsApi}: obtained through
1605
1780
  * {@link Sekyro.subjects}.
@@ -1611,7 +1786,11 @@ declare class SubjectsApi {
1611
1786
  constructor(call: <T>(method: "GET" | "POST" | "DELETE", path: string, body?: unknown, idempotencyKey?: string) => Promise<T>);
1612
1787
  /** `GET /subjects/:id` — the subject, its sessions and its returning-user readiness. */
1613
1788
  get(id: string): Promise<Subject>;
1614
- /** `GET /subjects?externalRef=…` — the subjects carrying your own id (newest first, at most 50). */
1789
+ /**
1790
+ * `GET /subjects?externalRef=…`: the subjects carrying your own id that have
1791
+ * passed a verification (newest first, at most 50). The list can be empty
1792
+ * while sessions with this `externalRef` exist.
1793
+ */
1615
1794
  list(query: {
1616
1795
  externalRef: string;
1617
1796
  }): Promise<Subject[]>;
@@ -1666,4 +1845,4 @@ declare class Sekyro {
1666
1845
  listFlows(): Promise<FlowSummary[]>;
1667
1846
  }
1668
1847
 
1669
- export { type SessionDevice as $, type AgeMethod as A, type FlowServiceSettings as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type EidResult as E, type FetchLike as F, type FlowSummary as G, type IdentityMethod as H, type IdNumberReason as I, type LevelTarget as J, type ListSessionsQuery as K, type Locale as L, type MatchReason as M, type PortraitReportEntry as N, type ProbeBindingReason as O, type PolicyFailureReason as P, type ProbeQuality as Q, type ResultRisk as R, Sekyro as S, type ProfileDocumentType as T, type RequestOptions as U, type VerificationLevel as V, type WebhookEventType as W, type ResultTokenResponse as X, type RevokeSubjectInput as Y, type SekyroOptions as Z, type Session as _, type ServiceId as a, type SessionDeviceSignal as a0, type SessionEventData as a1, type SessionFailureReason as a2, type SessionFlowRef as a3, type SessionLifecycleEventData as a4, type SessionLinkInput as a5, type SessionNetwork as a6, type SessionNetworkEvent as a7, type SessionPortraitLink as a8, type SessionReviewDecidedEventData as a9, type SessionStatus as aa, type SessionStep as ab, type SessionStepCompletedEventData as ac, SessionsApi as ad, type Subject as ae, type SubjectAssurance as af, type SubjectDeletedEventData as ag, type SubjectEnrolledEventData as ah, type SubjectIdNumber as ai, type SubjectName as aj, type SubjectReferenceSource as ak, type SubjectReuseDocument as al, type SubjectReuseTarget as am, type SubjectSession as an, type SubjectSessionInput as ao, type SubjectSessionTarget as ap, type SubjectStatus as aq, type SubjectSuspiciousActivityEventData as ar, type SubjectUpdatedEventData as as, SubjectsApi as at, type SuppliedIdentityRecord as au, type UsageThresholdReachedEventData as av, type VerifiedContacts as aw, type WebhookEnvelopeOf as ax, type WebhookEventDataMap as ay, type SessionSubjectInput as b, type WebhookEnvelope as c, type SekyroEnvironment as d, type VerificationAssurance as e, type SessionOutcome as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultCheckProofs as i, type ResultDuplicate as j, type AgeResult as k, type CameraUnavailableCause as l, type CheckState as m, type CheckType as n, type ConnectorIdentity as o, type CreateSessionInput as p, type CreatedSessionWarning as q, DEFAULT_TIMEOUT_MS as r, type DecisionReason as s, type DeepPartial as t, type DeletedSubject as u, type DeliverOptions as v, type DocumentSubstitutionSettings as w, type EligibilityReason as x, type FlowOverridableSettings as y, type FlowOverrides as z };
1848
+ export { type ReviewOutcomeReason as $, type AgeMethod as A, type FlowOverridableSettings as B, type CreatedSession as C, DEFAULT_BASE_URL as D, type EidResult as E, type FetchLike as F, type FlowOverrides as G, type FlowServiceSettings as H, type FlowSummary as I, type IdNumberReason as J, type IdentityMethod as K, type Locale as L, type LevelTarget as M, type ListSessionsQuery as N, type MatchReason as O, type PolicyFailureReason as P, type PortraitReportEntry as Q, type ReviewReason as R, Sekyro as S, type PriorReviewReason as T, type ProbeBindingReason as U, type VerificationLevel as V, type WebhookEventType as W, type ProbeQuality as X, type ProfileDocumentType as Y, type RequestOptions as Z, type ResultTokenResponse as _, type ServiceId as a, type RevokeSubjectInput as a0, type SekyroOptions as a1, type Session as a2, type SessionDevice as a3, type SessionDeviceSignal as a4, type SessionEventData as a5, type SessionFailureReason as a6, type SessionFlowRef as a7, type SessionLifecycleEventData as a8, type SessionLinkInput as a9, type SuppliedIdentityRecord as aA, type UsageThresholdReachedEventData as aB, type VerifiedContacts as aC, type WebhookEnvelopeOf as aD, type WebhookEventDataMap as aE, type SessionNetwork as aa, type SessionNetworkEvent as ab, type SessionPortraitLink as ac, type SessionReviewDecidedEventData as ad, type SessionStatus as ae, type SessionStep as af, type SessionStepCompletedEventData as ag, type SessionStepDecision as ah, type SessionSupersededEventData as ai, SessionsApi as aj, type Subject as ak, type SubjectAssurance as al, type SubjectDeletedEventData as am, type SubjectEnrolledEventData as an, type SubjectIdNumber as ao, type SubjectName as ap, type SubjectReferenceSource as aq, type SubjectReuseDocument as ar, type SubjectReuseTarget as as, type SubjectSession as at, type SubjectSessionInput as au, type SubjectSessionTarget as av, type SubjectStatus as aw, type SubjectSuspiciousActivityEventData as ax, type SubjectUpdatedEventData as ay, SubjectsApi as az, type SessionSubjectInput as b, type WebhookEnvelope as c, type SekyroEnvironment as d, type VerificationAssurance as e, type SessionOutcome as f, type VerificationUnit as g, type SubjectReuseMode as h, type ResultRisk as i, type ResultCheckProofs as j, type ResultDuplicate as k, type FailureIdentification as l, type AgeResult as m, type CameraUnavailableCause as n, type CheckState as o, type CheckType as p, type ConnectorIdentity as q, type CreateSessionInput as r, type CreatedSessionWarning as s, DEFAULT_TIMEOUT_MS as t, type DecisionReason as u, type DeepPartial as v, type DeletedSubject as w, type DeliverOptions as x, type DocumentSubstitutionSettings as y, type EligibilityReason as z };
@@ -1,5 +1,5 @@
1
- import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-C4NuetEm.cjs';
2
- import '../../client-Hkxwn6ZA.cjs';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-S_99xkJf.cjs';
2
+ import '../../client-B7_KS_rG.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-BInF_yHb.js';
2
- import '../../client-Hkxwn6ZA.js';
1
+ import { C as Connector, P as ProviderAdapter, G as GatePolicy, a as GateResult } from '../../connector-DHK_cSbs.js';
2
+ import '../../client-B7_KS_rG.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/express`: a route gate for Express (and any
@@ -1 +1 @@
1
- import{sekyroGate}from"../../chunk-TAPXGI3Q.js";import"../../chunk-O5GJ3YJV.js";function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}export{requireLevel};
1
+ import{sekyroGate}from"../../chunk-H5TUZAV5.js";import"../../chunk-4JZXIGA6.js";function deny(res,result){let body={error:"sekyro_gate",reason:result.reason,action:result.action},r=res;if(typeof r.status=="function"){r.status(403).json(body);return}let n=res;n.statusCode=403,n.setHeader("content-type","application/json"),n.end(JSON.stringify(body))}function requireLevel(source,policy,opts){return(req,res,next)=>{Promise.resolve().then(()=>opts.claims(req)).then(claims=>{let result=sekyroGate(source,claims,policy);if(typeof req=="object"&&req!==null&&(req.sekyro=result),result.ok)return next();if(opts.onFail)return opts.onFail(result,req,res);deny(res,result)},err=>next(err))}}export{requireLevel};
@@ -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-C4NuetEm.cjs';
2
- import '../client-Hkxwn6ZA.cjs';
1
+ export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-S_99xkJf.cjs';
2
+ import '../client-B7_KS_rG.cjs';
3
3
 
4
4
  /**
5
5
  * Why a connector refused to act:
@@ -1,5 +1,5 @@
1
- export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-BInF_yHb.js';
2
- import '../client-Hkxwn6ZA.js';
1
+ export { b as CLAIM_VERSION, c as ClaimFlag, C as Connector, d as ConnectorLogEvent, e as ConnectorOptions, f as ConnectorStore, g as GateAction, G as GatePolicy, h as GateReason, a as GateResult, M as MemoryStore, i as MergeEvent, j as MergeOutcome, k as MergeRule, P as ProviderAdapter, R as RevocationUnresolvedEvent, S as SekyroClaim, l as StartOptions, V as VerificationResultInput, W as WebhookOutcome, m as WebhookSkipReason, n as createConnector, o as evaluateGate, p as memoryStore, q as mergeClaim, r as parseClaim } from '../connector-DHK_cSbs.js';
2
+ import '../client-B7_KS_rG.js';
3
3
 
4
4
  /**
5
5
  * Why a connector refused to act:
@@ -1 +1 @@
1
- import{CLAIM_VERSION,evaluateGate,mergeClaim,parseClaim}from"../chunk-O5GJ3YJV.js";import{decodeJwt}from"jose";import{verifyResultToken}from"@sekyro/node";import{signatureFromHeaders,verifyWebhook}from"@sekyro/node";var MESSAGES={token_session_mismatch:"The result token is for another session than the webhook",external_ref_mismatch:"The session belongs to another user",session_not_terminal:"The session has not finished yet",invalid_options:"Invalid connector options",unavailable:"The Sekyro AI public key set could not be fetched; try again"},SekyroConnectError=class extends Error{name="SekyroConnectError";code;constructor(code,message=MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}};function factsOf(d,tokenDuplicates){let out={};return d.returning===!0&&(out.returning=!0),d.subjectConflict===!0&&(out.subjectConflict=!0),(Array.isArray(d.duplicates)&&d.duplicates.length>0||(tokenDuplicates?.length??0)>0)&&(out.duplicates=!0),out}function fromVerifiedResult(v,d){let out={sessionId:v.sessionId,outcome:v.outcome,level:v.level,assurance:v.assurance,verifiedAt:v.verifiedAt,env:v.env,...factsOf(d,v.duplicates)};return v.subjectId!==void 0&&(out.subjectId=v.subjectId),v.reuseMode!==void 0&&(out.reuseMode=v.reuseMode),out}function fromWebhookData(d,env,nowMs){let out={sessionId:d.sessionId,outcome:d.outcome??null,level:d.level??null,assurance:d.assurance??null,verifiedAt:d.verifiedAt??new Date(nowMs).toISOString(),env,...factsOf(d)};return d.subjectId!==void 0&&(out.subjectId=d.subjectId),d.reuseMode!==void 0&&(out.reuseMode=d.reuseMode),out}function memoryStore(opts={}){let now=opts.now??Date.now,ids=new Map,subjects=new Map,evict=t=>{for(let[id,expiresAt]of ids)expiresAt<=t&&ids.delete(id)};return{async seen(id,ttlSec){let t=now();return evict(t),ids.has(id)?!0:(ids.set(id,t+ttlSec*1e3),!1)},async forget(id){ids.delete(id)},async setSubjectUser(subjectId,userId){subjects.delete(subjectId),subjects.set(subjectId,userId),subjects.size>1e5&&subjects.delete(subjects.keys().next().value)},async getSubjectUser(subjectId){return subjects.get(subjectId)},size(){return evict(now()),ids.size}}}var KNOWN_CONNECTOR_PROVIDERS=new Set(["auth0","clerk","firebase","keycloak","supabase","zitadel"]),CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),TELEMETRY_TIMEOUT_MS=2e3,TELEMETRY_BATCH_MAX=50,QUEUE_MAX=500;function hooksOf(sekyro){let h=sekyro[CONNECT_TELEMETRY];return h&&typeof h.setConnector=="function"&&typeof h.postEvents=="function"?h:void 0}var OFF={record(){}};function connectTelemetry(opts){let hooks=hooksOf(opts.sekyro);if(!hooks)return OFF;let name=opts.provider.name;if(!opts.enabled||!KNOWN_CONNECTOR_PROVIDERS.has(name))return opts.enabled||hooks.setConnector(null),OFF;hooks.setConnector({provider:name,version:opts.provider.version??"unknown"});let queue=[],scheduled=!1,flush=()=>{for(scheduled=!1;queue.length>0;){let batch=queue.splice(0,TELEMETRY_BATCH_MAX);hooks.postEvents(batch,TELEMETRY_TIMEOUT_MS).catch(()=>{})}};return{record(event){if(queue.length>=QUEUE_MAX)return;let e={type:event.type,provider:name,at:new Date(opts.now()).toISOString()};if(typeof event.sessionId=="string"&&event.sessionId.length>0&&(e.sessionId=event.sessionId),typeof event.subjectId=="string"&&event.subjectId.length>0&&(e.subjectId=event.subjectId),queue.push(e),scheduled)return;scheduled=!0,setTimeout(flush,0).unref?.()}}}var DEDUP_TTL_SEC=24*3600,JTI_TTL_SEC=600;function isApiStatus(err,statuses){if(typeof err!="object"||err===null)return!1;let e=err;return e.name==="SekyroApiError"&&typeof e.status=="number"&&statuses.includes(e.status)}function linkOf(o){if(o.returnUrl===void 0&&o.state===void 0)return;let link={};return o.returnUrl!==void 0&&(link.returnUrl=o.returnUrl),o.state!==void 0&&(link.state=o.state),link}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}function assertUserId(method,userId){if(typeof userId!="string"||userId.length===0)throw new TypeError(`connector.${method}: \`userId\` must be a non-empty string`)}function createConnector(opts){let appIds=[opts?.appId].flat();if(appIds.length===0||appIds.some(id=>typeof id!="string"||id.length===0))throw new SekyroConnectError("invalid_options","`appId` must be a non-empty string or a non-empty array of them");if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroConnectError("invalid_options","`env` must be 'live' or 'sandbox'");if(typeof opts.webhookSecret!="string"||opts.webhookSecret.length===0)throw new SekyroConnectError("invalid_options","`webhookSecret` is required");if(!opts.sekyro||!opts.provider)throw new SekyroConnectError("invalid_options","`sekyro` and `provider` are required");let{sekyro,provider,env}=opts,now=opts.now??Date.now,store=opts.store??memoryStore({now}),ids=Object.freeze([...appIds]),userLock=perKeyLock(),telemetry=connectTelemetry({sekyro,provider,enabled:opts.telemetry!==!1,now});function updateClaim(userId,fn){return typeof provider.update=="function"?provider.update(userId,fn):userLock(userId,async()=>{let out=fn(await provider.readUser(userId));return out.changed&&out.claim&&await provider.writeUser(userId,out.claim),out})}let log=event=>{if(opts.logger)try{opts.logger(event)}catch{}},notifyRevocationUnresolved=event=>{let handler=opts.onRevocationUnresolved;if(typeof handler!="function")return;let failed=()=>log({type:"revocation_handler_failed",subjectId:event.subjectId});queueMicrotask(()=>{try{Promise.resolve(handler(event)).catch(failed)}catch{failed()}})},tokenOptions={appId:[...ids],env,now};opts.issuer!==void 0&&(tokenOptions.issuer=opts.issuer),opts.jwksUrl!==void 0&&(tokenOptions.jwksUrl=opts.jwksUrl),opts.fetch!==void 0&&(tokenOptions.fetch=opts.fetch);async function verifiedFor(token,sessionId,userId){let v;try{v=await verifyResultToken(token,tokenOptions)}catch(err){let e=err;throw e?.name==="SekyroResultTokenError"&&e.code==="jwks_unavailable"?new SekyroConnectError("unavailable",void 0,err):err}if(v.sessionId!==sessionId)throw new SekyroConnectError("token_session_mismatch");if(v.externalRef!==void 0&&v.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");return v}async function applyResult(event,userId,result){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind:"result",result},{env,now}));return out.rule==="env_mismatch"?(log({type:"env_mismatch",sessionId:result.sessionId}),{handled:!1,event,reason:"env_mismatch"}):!out.changed||!out.claim?{handled:!0,event,userId,claim:out.claim,rule:out.rule}:(out.claim.subject_id!==void 0&&store.setSubjectUser&&await store.setSubjectUser(out.claim.subject_id,userId),log({type:"write",userId,sessionId:result.sessionId,rule:out.rule}),telemetry.record({type:"claim_written",sessionId:result.sessionId,subjectId:out.claim.subject_id}),{handled:!0,event,userId,claim:out.claim,rule:out.rule})}async function handleTerminal(event,d,envelopeEnv,remember){if(d.appId===void 0||!ids.includes(d.appId))return{handled:!1,event,reason:"other_app"};let userId=d.externalRef;if(typeof userId!="string"||userId.length===0)return{handled:!1,event,reason:"no_external_ref"};let result;if(typeof d.resultToken=="string"&&d.resultToken.length>0){let v=await verifiedFor(d.resultToken,d.sessionId,userId),jti=decodeJwt(d.resultToken).jti;if(typeof jti=="string"&&jti.length>0&&await remember(`jti:${jti}`,JTI_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};result=fromVerifiedResult(v,d)}else{if(opts.requireResultToken===!0)return{handled:!1,event,reason:"result_token_required"};log({type:"result_token_absent",sessionId:d.sessionId}),result=fromWebhookData(d,envelopeEnv,now())}return applyResult(event,userId,result)}async function resolveUsers(event,subjectId,refs){let clean=list=>Array.isArray(list)?[...new Set(list.filter(r=>typeof r=="string"&&r.length>0))]:[],fromEvent=clean(refs);if(fromEvent.length>0)return{users:fromEvent,fromRefs:!0};if(event==="subject.updated"){let fromApi=clean((await sekyro.subjects.get(subjectId)).externalRefs);if(fromApi.length>0)return{users:fromApi,fromRefs:!0}}let fromStore=await store.getSubjectUser?.(subjectId);return{users:fromStore?[fromStore]:[],fromRefs:!1}}async function handleSubjectGone(event,subjectId,refs){let{users,fromRefs}=await resolveUsers(event,subjectId,refs);if(users.length===0)return log({type:"revocation_unresolved",subjectId}),telemetry.record({type:"revocation_unresolved",subjectId}),notifyRevocationUnresolved({subjectId,provider:provider.name,reason:event==="subject.updated"?"revoked":"deleted"}),{handled:!1,event,reason:"revocation_unresolved"};let kind=event==="subject.updated"?"revoked":"deleted",first;for(let userId of users){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind,subjectId,userInExternalRefs:fromRefs},{env,now}));out.changed&&out.claim&&(log({type:"write",userId,rule:out.rule}),telemetry.record({type:"claim_written",subjectId})),first??={claim:out.claim,rule:out.rule}}return{handled:!0,event,userId:users[0],claim:first.claim,rule:first.rule}}async function routeEnvelope(envelope,remember){let event=envelope.event;switch(envelope.event){case"session.completed":case"session.failed":return await handleTerminal(envelope.event,envelope.data,envelope.env,remember);case"subject.updated":{let d=envelope.data;return d.status!=="revoked"||typeof d.subjectId!="string"?{handled:!1,event,reason:"ignored_event"}:await handleSubjectGone("subject.updated",d.subjectId,d.externalRefs)}case"subject.deleted":{let d=envelope.data;return typeof d.subjectId!="string"||d.subjectId.length===0?{handled:!1,event,reason:"ignored_event"}:await handleSubjectGone("subject.deleted",d.subjectId,d.externalRefs)}default:return{handled:!1,event,reason:"ignored_event"}}}async function handleEnvelope(envelope){let event=envelope.event,canForget=typeof store.forget=="function",recorded=[],deferred=[],remember=async(id,ttl)=>{if(!canForget)return deferred.push([id,ttl]),!1;let dup=await store.seen(id,ttl);return dup||recorded.push(id),dup};if(await remember(`wh:${envelope.id}`,DEDUP_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};let out;try{out=await routeEnvelope(envelope,remember)}catch(err){for(let id of recorded)await store.forget(id).catch(()=>{});throw err}for(let[id,ttl]of deferred)await store.seen(id,ttl);return out}async function createVia(userId,mode,o){assertUserId(mode==="recheck"?"recheck":"stepUp",userId);let input={mode};mode==="step_up"&&o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes);let link=linkOf(o);return link&&(input.link=link),sekyro.subjects.createSession({externalRef:userId},input)}return{env,appIds:ids,async webhook(rawBody,headers){let envelope=verifyWebhook(rawBody,signatureFromHeaders(headers),opts.webhookSecret,{now}),out=await handleEnvelope(envelope);if(!out.handled&&out.reason!=="env_mismatch"&&out.reason!=="revocation_unresolved"){let data=envelope.data,skip={type:"skip",reason:out.reason};typeof data.sessionId=="string"&&(skip.sessionId=data.sessionId),typeof data.subjectId=="string"&&(skip.subjectId=data.subjectId),log(skip)}return out},async sync(userId,sessionId){assertUserId("sync",userId);let s=await sekyro.sessions.get(sessionId);if(s.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");if(s.status!=="completed"&&s.status!=="failed")throw new SekyroConnectError("session_not_terminal");let{token}=await sekyro.sessions.resultToken(sessionId),v=await verifiedFor(token,sessionId,userId),out=await applyResult(s.status==="completed"?"session.completed":"session.failed",userId,fromVerifiedResult(v,s));return out.handled?{claim:out.claim,rule:out.rule}:{claim:null,rule:"env_mismatch"}},async start(userId,o={}){assertUserId("start",userId);let input={};o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes),input.subject={externalRef:userId};let link=linkOf(o);return link&&(input.link=link),sekyro.sessions.create(input)},recheck(userId,o={}){return createVia(userId,"recheck",o)},stepUp(userId,o){return createVia(userId,"step_up",o)},async userDeleted(userId){assertUserId("userDeleted",userId);let policy=opts.onUserDeleted??"ignore";if(policy==="ignore")return{policy,subjects:0};let subjects=await sekyro.subjects.list({externalRef:userId});for(let s of subjects)try{policy==="revoke"?await sekyro.subjects.revoke(s.id):await sekyro.subjects.delete(s.id)}catch(err){if(!isApiStatus(err,[404,409]))throw err}return{policy,subjects:subjects.length}},async claimOf(userId){return parseClaim(await provider.readUser(userId))},async clearFlag(userId,flag){let out=await updateClaim(userId,previous=>{let claim=parseClaim(previous);return!claim||claim.v>1||!claim.flags?.includes(flag)?{claim,changed:!1,rule:"no_change"}:{claim:parseClaim({...claim,flags:claim.flags.filter(f=>f!==flag)}),changed:!0,rule:"no_change"}});return out.changed&&log({type:"flag_cleared",userId,flag}),out.claim},gate(tokenClaims,policy){return evaluateGate(provider.readClaimFromToken(tokenClaims),{...policy,env:policy.env??env},Math.floor(now()/1e3))}}}export{CLAIM_VERSION,SekyroConnectError,createConnector,evaluateGate,memoryStore,mergeClaim,parseClaim};
1
+ import{CLAIM_VERSION,evaluateGate,mergeClaim,parseClaim}from"../chunk-4JZXIGA6.js";import{decodeJwt}from"jose";import{verifyResultToken}from"@sekyro/node";import{signatureFromHeaders,verifyWebhook}from"@sekyro/node";var MESSAGES={token_session_mismatch:"The result token is for another session than the webhook",external_ref_mismatch:"The session belongs to another user",session_not_terminal:"The session has not finished yet",invalid_options:"Invalid connector options",unavailable:"The Sekyro AI public key set could not be fetched; try again"},SekyroConnectError=class extends Error{name="SekyroConnectError";code;constructor(code,message=MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}};function factsOf(d,tokenDuplicates){let out={};return d.returning===!0&&(out.returning=!0),d.subjectConflict===!0&&(out.subjectConflict=!0),(Array.isArray(d.duplicates)&&d.duplicates.length>0||(tokenDuplicates?.length??0)>0)&&(out.duplicates=!0),out}function fromVerifiedResult(v,d){let out={sessionId:v.sessionId,outcome:v.outcome,level:v.level,assurance:v.assurance,verifiedAt:v.verifiedAt,env:v.env,...factsOf(d,v.duplicates)};return v.subjectId!==void 0&&(out.subjectId=v.subjectId),v.reuseMode!==void 0&&(out.reuseMode=v.reuseMode),out}function fromWebhookData(d,env,nowMs){let out={sessionId:d.sessionId,outcome:d.outcome??null,level:d.level??null,assurance:d.assurance??null,verifiedAt:d.verifiedAt??new Date(nowMs).toISOString(),env,...factsOf(d)};return d.subjectId!==void 0&&(out.subjectId=d.subjectId),d.reuseMode!==void 0&&(out.reuseMode=d.reuseMode),out}function memoryStore(opts={}){let now=opts.now??Date.now,ids=new Map,subjects=new Map,evict=t=>{for(let[id,expiresAt]of ids)expiresAt<=t&&ids.delete(id)};return{async seen(id,ttlSec){let t=now();return evict(t),ids.has(id)?!0:(ids.set(id,t+ttlSec*1e3),!1)},async forget(id){ids.delete(id)},async setSubjectUser(subjectId,userId){subjects.delete(subjectId),subjects.set(subjectId,userId),subjects.size>1e5&&subjects.delete(subjects.keys().next().value)},async getSubjectUser(subjectId){return subjects.get(subjectId)},size(){return evict(now()),ids.size}}}var KNOWN_CONNECTOR_PROVIDERS=new Set(["auth0","clerk","firebase","keycloak","supabase","zitadel"]),CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),TELEMETRY_TIMEOUT_MS=2e3,TELEMETRY_BATCH_MAX=50,QUEUE_MAX=500;function hooksOf(sekyro){let h=sekyro[CONNECT_TELEMETRY];return h&&typeof h.setConnector=="function"&&typeof h.postEvents=="function"?h:void 0}var OFF={record(){}};function connectTelemetry(opts){let hooks=hooksOf(opts.sekyro);if(!hooks)return OFF;let name=opts.provider.name;if(!opts.enabled||!KNOWN_CONNECTOR_PROVIDERS.has(name))return opts.enabled||hooks.setConnector(null),OFF;hooks.setConnector({provider:name,version:opts.provider.version??"unknown"});let queue=[],scheduled=!1,flush=()=>{for(scheduled=!1;queue.length>0;){let batch=queue.splice(0,TELEMETRY_BATCH_MAX);hooks.postEvents(batch,TELEMETRY_TIMEOUT_MS).catch(()=>{})}};return{record(event){if(queue.length>=QUEUE_MAX)return;let e={type:event.type,provider:name,at:new Date(opts.now()).toISOString()};if(typeof event.sessionId=="string"&&event.sessionId.length>0&&(e.sessionId=event.sessionId),typeof event.subjectId=="string"&&event.subjectId.length>0&&(e.subjectId=event.subjectId),queue.push(e),scheduled)return;scheduled=!0,setTimeout(flush,0).unref?.()}}}var DEDUP_TTL_SEC=24*3600,JTI_TTL_SEC=600;function isApiStatus(err,statuses){if(typeof err!="object"||err===null)return!1;let e=err;return e.name==="SekyroApiError"&&typeof e.status=="number"&&statuses.includes(e.status)}function linkOf(o){if(o.returnUrl===void 0&&o.state===void 0)return;let link={};return o.returnUrl!==void 0&&(link.returnUrl=o.returnUrl),o.state!==void 0&&(link.state=o.state),link}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}function assertUserId(method,userId){if(typeof userId!="string"||userId.length===0)throw new TypeError(`connector.${method}: \`userId\` must be a non-empty string`)}function createConnector(opts){let appIds=[opts?.appId].flat();if(appIds.length===0||appIds.some(id=>typeof id!="string"||id.length===0))throw new SekyroConnectError("invalid_options","`appId` must be a non-empty string or a non-empty array of them");if(opts.env!=="live"&&opts.env!=="sandbox")throw new SekyroConnectError("invalid_options","`env` must be 'live' or 'sandbox'");if(typeof opts.webhookSecret!="string"||opts.webhookSecret.length===0)throw new SekyroConnectError("invalid_options","`webhookSecret` is required");if(!opts.sekyro||!opts.provider)throw new SekyroConnectError("invalid_options","`sekyro` and `provider` are required");let{sekyro,provider,env}=opts,now=opts.now??Date.now,store=opts.store??memoryStore({now}),ids=Object.freeze([...appIds]),userLock=perKeyLock(),telemetry=connectTelemetry({sekyro,provider,enabled:opts.telemetry!==!1,now});function updateClaim(userId,fn){return typeof provider.update=="function"?provider.update(userId,fn):userLock(userId,async()=>{let out=fn(await provider.readUser(userId));return out.changed&&out.claim&&await provider.writeUser(userId,out.claim),out})}let log=event=>{if(opts.logger)try{opts.logger(event)}catch{}},notifyRevocationUnresolved=event=>{let handler=opts.onRevocationUnresolved;if(typeof handler!="function")return;let failed=()=>log({type:"revocation_handler_failed",subjectId:event.subjectId});queueMicrotask(()=>{try{Promise.resolve(handler(event)).catch(failed)}catch{failed()}})},tokenOptions={appId:[...ids],env,now};opts.issuer!==void 0&&(tokenOptions.issuer=opts.issuer),opts.jwksUrl!==void 0&&(tokenOptions.jwksUrl=opts.jwksUrl),opts.fetch!==void 0&&(tokenOptions.fetch=opts.fetch);async function verifiedFor(token,sessionId,userId){let v;try{v=await verifyResultToken(token,tokenOptions)}catch(err){let e=err;throw e?.name==="SekyroResultTokenError"&&e.code==="jwks_unavailable"?new SekyroConnectError("unavailable",void 0,err):err}if(v.sessionId!==sessionId)throw new SekyroConnectError("token_session_mismatch");if(v.externalRef!==void 0&&v.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");return v}async function applyResult(event,userId,result){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind:"result",result},{env,now}));return out.rule==="env_mismatch"?(log({type:"env_mismatch",sessionId:result.sessionId}),{handled:!1,event,reason:"env_mismatch"}):!out.changed||!out.claim?{handled:!0,event,userId,claim:out.claim,rule:out.rule}:(out.claim.subject_id!==void 0&&store.setSubjectUser&&await store.setSubjectUser(out.claim.subject_id,userId),log({type:"write",userId,sessionId:result.sessionId,rule:out.rule}),telemetry.record({type:"claim_written",sessionId:result.sessionId,subjectId:out.claim.subject_id}),{handled:!0,event,userId,claim:out.claim,rule:out.rule})}async function handleTerminal(event,d,envelopeEnv,remember){if(d.appId===void 0||!ids.includes(d.appId))return{handled:!1,event,reason:"other_app"};let userId=d.externalRef;if(typeof userId!="string"||userId.length===0)return{handled:!1,event,reason:"no_external_ref"};let result;if(typeof d.resultToken=="string"&&d.resultToken.length>0){let v=await verifiedFor(d.resultToken,d.sessionId,userId),jti=decodeJwt(d.resultToken).jti;if(typeof jti=="string"&&jti.length>0&&await remember(`jti:${jti}`,JTI_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};result=fromVerifiedResult(v,d)}else{if(opts.requireResultToken===!0)return{handled:!1,event,reason:"result_token_required"};log({type:"result_token_absent",sessionId:d.sessionId}),result=fromWebhookData(d,envelopeEnv,now())}return applyResult(event,userId,result)}async function resolveUsers(event,subjectId,refs){let clean=list=>Array.isArray(list)?[...new Set(list.filter(r=>typeof r=="string"&&r.length>0))]:[],fromEvent=clean(refs);if(fromEvent.length>0)return{users:fromEvent,fromRefs:!0};if(event==="subject.updated"){let fromApi=clean((await sekyro.subjects.get(subjectId)).externalRefs);if(fromApi.length>0)return{users:fromApi,fromRefs:!0}}let fromStore=await store.getSubjectUser?.(subjectId);return{users:fromStore?[fromStore]:[],fromRefs:!1}}async function handleSubjectGone(event,subjectId,refs){let{users,fromRefs}=await resolveUsers(event,subjectId,refs);if(users.length===0)return log({type:"revocation_unresolved",subjectId}),telemetry.record({type:"revocation_unresolved",subjectId}),notifyRevocationUnresolved({subjectId,provider:provider.name,reason:event==="subject.updated"?"revoked":"deleted"}),{handled:!1,event,reason:"revocation_unresolved"};let kind=event==="subject.updated"?"revoked":"deleted",first;for(let userId of users){let out=await updateClaim(userId,previous=>mergeClaim(previous,{kind,subjectId,userInExternalRefs:fromRefs},{env,now}));out.changed&&out.claim&&(log({type:"write",userId,rule:out.rule}),telemetry.record({type:"claim_written",subjectId})),first??={claim:out.claim,rule:out.rule}}return{handled:!0,event,userId:users[0],claim:first.claim,rule:first.rule}}async function routeEnvelope(envelope,remember){let event=envelope.event;switch(envelope.event){case"session.completed":case"session.failed":return await handleTerminal(envelope.event,envelope.data,envelope.env,remember);case"subject.updated":{let d=envelope.data;return d.status!=="revoked"||typeof d.subjectId!="string"?{handled:!1,event,reason:"ignored_event"}:await handleSubjectGone("subject.updated",d.subjectId,d.externalRefs)}case"subject.deleted":{let d=envelope.data;return typeof d.subjectId!="string"||d.subjectId.length===0?{handled:!1,event,reason:"ignored_event"}:await handleSubjectGone("subject.deleted",d.subjectId,d.externalRefs)}default:return{handled:!1,event,reason:"ignored_event"}}}async function handleEnvelope(envelope){let event=envelope.event,canForget=typeof store.forget=="function",recorded=[],deferred=[],remember=async(id,ttl)=>{if(!canForget)return deferred.push([id,ttl]),!1;let dup=await store.seen(id,ttl);return dup||recorded.push(id),dup};if(await remember(`wh:${envelope.id}`,DEDUP_TTL_SEC))return{handled:!1,event,reason:"duplicate_delivery"};let out;try{out=await routeEnvelope(envelope,remember)}catch(err){for(let id of recorded)await store.forget(id).catch(()=>{});throw err}for(let[id,ttl]of deferred)await store.seen(id,ttl);return out}async function createVia(userId,mode,o){assertUserId(mode==="recheck"?"recheck":"stepUp",userId);let input={mode};mode==="step_up"&&o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes);let link=linkOf(o);return link&&(input.link=link),sekyro.subjects.createSession({externalRef:userId},input)}return{env,appIds:ids,async webhook(rawBody,headers){let envelope=verifyWebhook(rawBody,signatureFromHeaders(headers),opts.webhookSecret,{now}),out=await handleEnvelope(envelope);if(!out.handled&&out.reason!=="env_mismatch"&&out.reason!=="revocation_unresolved"){let data=envelope.data,skip={type:"skip",reason:out.reason};typeof data.sessionId=="string"&&(skip.sessionId=data.sessionId),typeof data.subjectId=="string"&&(skip.subjectId=data.subjectId),log(skip)}return out},async sync(userId,sessionId){assertUserId("sync",userId);let s=await sekyro.sessions.get(sessionId);if(s.externalRef!==userId)throw new SekyroConnectError("external_ref_mismatch");if(s.status!=="completed"&&s.status!=="failed")throw new SekyroConnectError("session_not_terminal");let{token}=await sekyro.sessions.resultToken(sessionId),v=await verifiedFor(token,sessionId,userId),out=await applyResult(s.status==="completed"?"session.completed":"session.failed",userId,fromVerifiedResult(v,s));return out.handled?{claim:out.claim,rule:out.rule}:{claim:null,rule:"env_mismatch"}},async start(userId,o={}){assertUserId("start",userId);let input={};o.flow!==void 0&&(input.flow=o.flow),o.locale!==void 0&&(input.locale=o.locale),o.ttlMinutes!==void 0&&(input.ttlMinutes=o.ttlMinutes),input.subject={externalRef:userId};let link=linkOf(o);return link&&(input.link=link),sekyro.sessions.create(input)},recheck(userId,o={}){return createVia(userId,"recheck",o)},stepUp(userId,o){return createVia(userId,"step_up",o)},async userDeleted(userId){assertUserId("userDeleted",userId);let policy=opts.onUserDeleted??"ignore";if(policy==="ignore")return{policy,subjects:0};let subjects=await sekyro.subjects.list({externalRef:userId});for(let s of subjects)try{policy==="revoke"?await sekyro.subjects.revoke(s.id):await sekyro.subjects.delete(s.id)}catch(err){if(!isApiStatus(err,[404,409]))throw err}return{policy,subjects:subjects.length}},async claimOf(userId){return parseClaim(await provider.readUser(userId))},async clearFlag(userId,flag){let out=await updateClaim(userId,previous=>{let claim=parseClaim(previous);return!claim||claim.v>1||!claim.flags?.includes(flag)?{claim,changed:!1,rule:"no_change"}:{claim:parseClaim({...claim,flags:claim.flags.filter(f=>f!==flag)}),changed:!0,rule:"no_change"}});return out.changed&&log({type:"flag_cleared",userId,flag}),out.claim},gate(tokenClaims,policy){return evaluateGate(provider.readClaimFromToken(tokenClaims),{...policy,env:policy.env??env},Math.floor(now()/1e3))}}}export{CLAIM_VERSION,SekyroConnectError,createConnector,evaluateGate,memoryStore,mergeClaim,parseClaim};
@@ -1,5 +1,5 @@
1
- import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-C4NuetEm.cjs';
2
- import '../../client-Hkxwn6ZA.cjs';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-S_99xkJf.cjs';
2
+ import '../../client-B7_KS_rG.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-BInF_yHb.js';
2
- import '../../client-Hkxwn6ZA.js';
1
+ import { a as GateResult, C as Connector, P as ProviderAdapter, G as GatePolicy } from '../../connector-DHK_cSbs.js';
2
+ import '../../client-B7_KS_rG.js';
3
3
 
4
4
  /**
5
5
  * `@sekyro/node/connect/next`: gate helpers for Next.js middleware, route
@@ -1 +1 @@
1
- import{gateRoute,sekyroGate}from"../../chunk-TAPXGI3Q.js";import"../../chunk-O5GJ3YJV.js";export{gateRoute,sekyroGate};
1
+ import{gateRoute,sekyroGate}from"../../chunk-H5TUZAV5.js";import"../../chunk-4JZXIGA6.js";export{gateRoute,sekyroGate};
@@ -1,4 +1,4 @@
1
- import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-Hkxwn6ZA.js';
1
+ import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-B7_KS_rG.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -47,7 +47,8 @@ interface SekyroClaim {
47
47
  */
48
48
  interface VerificationResultInput {
49
49
  sessionId: string;
50
- outcome: "approved" | "rejected" | "review" | null;
50
+ /** `superseded` (a newer attempt took the review over) is never approved: the claim stays as it was. */
51
+ outcome: "approved" | "rejected" | "review" | "superseded" | null;
51
52
  level: 0 | 1 | 2 | 3 | null;
52
53
  assurance: string | null;
53
54
  /** ISO 8601. */
@@ -1,4 +1,4 @@
1
- import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-Hkxwn6ZA.cjs';
1
+ import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-B7_KS_rG.cjs';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
@@ -47,7 +47,8 @@ interface SekyroClaim {
47
47
  */
48
48
  interface VerificationResultInput {
49
49
  sessionId: string;
50
- outcome: "approved" | "rejected" | "review" | null;
50
+ /** `superseded` (a newer attempt took the review over) is never approved: the claim stays as it was. */
51
+ outcome: "approved" | "rejected" | "review" | "superseded" | null;
51
52
  level: 0 | 1 | 2 | 3 | null;
52
53
  assurance: string | null;
53
54
  /** ISO 8601. */
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,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.10";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{}}}var SUBJECT_ID_RE=/^[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;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 call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init3={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init3.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init3.details=parsed.error.details),retryAfterSeconds!==void 0&&(init3.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init3)}let init2={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};throw retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport)),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function subjectFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationality=nationality);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;return age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.11";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{}}}var SUBJECT_ID_RE=/^[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;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 call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init3={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init3.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init3.details=parsed.error.details),retryAfterSeconds!==void 0&&(init3.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init3)}let init2={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};throw retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport)),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function subjectFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationality=nationality);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},subjectId=str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});