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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SuppliedIdentityRecord, c as WebhookEnvelope, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, R as ResultRisk, i as ResultCheckProofs, j as ResultDuplicate, A as AgeMethod, F as FetchLike } from './client-CcZfrjW1.cjs';
2
- export { k as AgeResult, l as CameraUnavailableCause, m as CheckState, n as CheckType, o as CreateSessionInput, C as CreatedSession, D as DEFAULT_BASE_URL, p as DEFAULT_TIMEOUT_MS, q as DecisionReason, r as DeepPartial, s as DeletedSubject, t as DeliverOptions, u as DocumentSubstitutionSettings, E as EidResult, v as EligibilityReason, w as FlowOverridableSettings, x as FlowOverrides, y as FlowServiceSettings, z as FlowSummary, I as IdentityMethod, B as LevelTarget, G as ListSessionsQuery, L as Locale, M as MatchReason, P as PolicyFailureReason, H as PortraitReportEntry, J as ProbeBindingReason, K as ProbeQuality, N as ProfileDocumentType, O as RequestOptions, Q as ResultTokenResponse, T as RevokeSubjectInput, S as Sekyro, U as SekyroOptions, X as Session, Y as SessionDevice, Z as SessionDeviceSignal, _ as SessionEventData, $ as SessionFailureReason, a0 as SessionFlowRef, a1 as SessionLifecycleEventData, a2 as SessionLinkInput, a3 as SessionNetwork, a4 as SessionNetworkEvent, a5 as SessionPortraitLink, a6 as SessionReviewDecidedEventData, a7 as SessionStatus, a8 as SessionStep, a9 as SessionStepCompletedEventData, aa as SessionSubjectInput, ab as SessionsApi, ac as Subject, ad as SubjectAssurance, ae as SubjectDeletedEventData, af as SubjectEnrolledEventData, ag as SubjectReferenceSource, ah as SubjectReuseDocument, ai as SubjectReuseTarget, aj as SubjectSession, ak as SubjectSessionInput, al as SubjectSessionTarget, am as SubjectStatus, an as SubjectSuspiciousActivityEventData, ao as SubjectUpdatedEventData, ap as SubjectsApi, aq as UsageThresholdReachedEventData, ar as VerifiedContacts, as as WebhookEnvelopeOf, at as WebhookEventDataMap, W as WebhookEventType } from './client-CcZfrjW1.cjs';
1
+ import { a as ServiceId, b as SessionSubjectInput, c as WebhookEnvelope, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, R as ResultRisk, i as ResultCheckProofs, j as ResultDuplicate, A as AgeMethod, F as FetchLike } from './client-BYoo67F-.cjs';
2
+ export { k as AgeResult, l as CameraUnavailableCause, m as CheckState, n as CheckType, o as CreateSessionInput, C as CreatedSession, p as CreatedSessionWarning, D as DEFAULT_BASE_URL, q as DEFAULT_TIMEOUT_MS, r as DecisionReason, s as DeepPartial, t as DeletedSubject, u as DeliverOptions, v as DocumentSubstitutionSettings, E as EidResult, w as EligibilityReason, x as FlowOverridableSettings, y as FlowOverrides, z as FlowServiceSettings, B as FlowSummary, I as IdNumberReason, G as IdentityMethod, H as LevelTarget, J as ListSessionsQuery, L as Locale, M as MatchReason, P as PolicyFailureReason, K as PortraitReportEntry, N as ProbeBindingReason, O as ProbeQuality, Q as ProfileDocumentType, T as RequestOptions, U as ResultTokenResponse, X as RevokeSubjectInput, S as Sekyro, Y as SekyroOptions, Z as Session, _ as SessionDevice, $ as SessionDeviceSignal, a0 as SessionEventData, a1 as SessionFailureReason, a2 as SessionFlowRef, a3 as SessionLifecycleEventData, a4 as SessionLinkInput, a5 as SessionNetwork, a6 as SessionNetworkEvent, a7 as SessionPortraitLink, a8 as SessionReviewDecidedEventData, a9 as SessionStatus, aa as SessionStep, ab as SessionStepCompletedEventData, ac as SessionsApi, ad as Subject, ae as SubjectAssurance, af as SubjectDeletedEventData, ag as SubjectEnrolledEventData, ah as SubjectIdNumber, ai as SubjectName, aj as SubjectReferenceSource, ak as SubjectReuseDocument, al as SubjectReuseTarget, am as SubjectSession, an as SubjectSessionInput, ao as SubjectSessionTarget, ap as SubjectStatus, aq as SubjectSuspiciousActivityEventData, ar as SubjectUpdatedEventData, as as SubjectsApi, at as SuppliedIdentityRecord, au as UsageThresholdReachedEventData, av as VerifiedContacts, aw as WebhookEnvelopeOf, ax as WebhookEventDataMap, W as WebhookEventType } from './client-BYoo67F-.cjs';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
@@ -37,9 +37,10 @@ declare class SekyroResultTokenError extends Error {
37
37
  constructor(code: SekyroResultTokenErrorCode, message?: string, cause?: unknown);
38
38
  }
39
39
  /** Why the {@link Sekyro} constructor rejected its options. @public */
40
- type SekyroConfigErrorCode = "missing_api_key" | "invalid_base_url" | "invalid_registry_record";
40
+ type SekyroConfigErrorCode = "missing_api_key" | "invalid_base_url" | "invalid_registry_record" | "registry_country_unsupported" | "registry_nationality_unmapped";
41
41
  /**
42
- * Thrown synchronously by `new Sekyro(...)` for an unusable configuration —
42
+ * Thrown synchronously by `new Sekyro(...)` for an unusable configuration, and by
43
+ * {@link subjectFromNationalRegistry} for an unusable registry answer:
43
44
  * before any request is made. Extends `TypeError` so existing
44
45
  * `instanceof TypeError` guards keep working.
45
46
  * @public
@@ -149,6 +150,8 @@ interface SekyroApiErrorInit {
149
150
  details?: unknown;
150
151
  /** Underlying error (network failures, abort reasons, JSON parse errors). */
151
152
  cause?: unknown;
153
+ /** Seconds to wait before retrying, from the response's `Retry-After` header. */
154
+ retryAfterSeconds?: number;
152
155
  }
153
156
  /** Error codes the SDK itself produces (as opposed to codes from the API). @public */
154
157
  type SekyroClientErrorCode = "network" | "timeout" | "http_error" | "malformed_response";
@@ -173,6 +176,12 @@ declare class SekyroApiError extends Error {
173
176
  */
174
177
  readonly details: unknown;
175
178
  readonly retryable: boolean;
179
+ /**
180
+ * Seconds to wait before retrying, from the response's `Retry-After` header
181
+ * (a number of seconds, or an HTTP date rounded up to whole seconds from now).
182
+ * `undefined` when the response had no usable header.
183
+ */
184
+ readonly retryAfterSeconds: number | undefined;
176
185
  constructor(init: SekyroApiErrorInit);
177
186
  }
178
187
  /**
@@ -221,33 +230,59 @@ interface AnrptsPersonneResponse {
221
230
  datePhoto?: string | undefined;
222
231
  [key: string]: unknown;
223
232
  }
224
- /** Options of {@link registryFromAnrpts}. @public */
225
- interface RegistryFromAnrptsOptions {
233
+ /**
234
+ * Registry answer formats Sekyro AI can map, by ISO 3166-1 alpha-2 country.
235
+ * @public
236
+ */
237
+ interface NationalRegistryResponses {
238
+ /** Mauritania: the ANRPTS `getPersonne` answer `{ personne, photo, datePhoto? }`. */
239
+ MR: AnrptsPersonneResponse;
240
+ }
241
+ /** A country {@link subjectFromNationalRegistry} can map. @public */
242
+ type NationalRegistryCountry = keyof NationalRegistryResponses;
243
+ /** Options of {@link subjectFromNationalRegistry}. @public */
244
+ interface SubjectFromRegistryOptions {
226
245
  /**
227
- * When YOUR system received this ANRPTS answer (not "now" when you map a cached
246
+ * When YOUR system received this answer (not "now" when you map a cached
228
247
  * answer). Required: records older than 24 h are refused at session create.
229
248
  */
230
249
  fetchedAt: Date | string;
250
+ /**
251
+ * The person's nationality (ISO 3166-1 alpha-2) when you map the registry's
252
+ * nationality text yourself; it replaces the SDK's mapping. Needed when the answer
253
+ * states a nationality the SDK cannot map (`registry_nationality_unmapped`).
254
+ */
255
+ nationality?: string;
231
256
  }
232
257
  /**
233
- * Convert an ANRPTS `getPersonne` answer that YOUR server already received,
234
- * with your own access, into the `input.suppliedIdentity` record of
235
- * `sessions.create` (partner-supplied identity data). A pure, local mapping:
236
- * it makes no network call, and Sekyro AI never sees, receives or stores any
237
- * ANRPTS key — only the record and photo you pass.
258
+ * The `subject` keys of a reference record, ready to spread into
259
+ * `sessions.create({ subject })`.
260
+ * @public
261
+ */
262
+ type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionSubjectInput, "fullName" | "names" | "birthPlace" | "sex" | "nationality" | "photoDate">;
263
+ /**
264
+ * Convert a national registry answer that YOUR server already received, with
265
+ * your own access, into the `subject` reference keys of `sessions.create`. A
266
+ * pure, local mapping: it makes no network call, and Sekyro AI never sees,
267
+ * receives or stores any registry key, only the record and photo you pass.
238
268
  *
239
269
  * ```ts
240
- * const anrpts = await myAnrptsClient.getPersonne(nni); // your call, your key
241
- * const suppliedIdentity = registryFromAnrpts(anrpts, { fetchedAt: receivedAt });
242
- * await sekyro.sessions.create({ input: { nni, suppliedIdentity } });
270
+ * const answer = await myRegistryClient.lookup(number); // your call, your key
271
+ * await sekyro.sessions.create({
272
+ * subject: { externalRef, ...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
273
+ * });
243
274
  * ```
244
275
  *
245
- * Throws {@link SekyroConfigError} (`invalid_registry_record`) when a required
246
- * field (NNI, French and Arabic first and last names, birth date, photo) is
247
- * missing. The message names the field, never its value.
276
+ * Throws {@link SekyroConfigError}: `invalid_registry_record` when a required
277
+ * field (the number, a given and family name in at least one script, the birth
278
+ * date, the photo) is missing or `fetchedAt` is not a date (the message names
279
+ * the field, never its value); `registry_country_unsupported` for a country
280
+ * without an adapter; `registry_nationality_unmapped` when the answer states a
281
+ * nationality and none of its values maps to an ISO code (map it yourself and pass
282
+ * `options.nationality`; the message never carries the value).
248
283
  * @public
249
284
  */
250
- declare function registryFromAnrpts(response: AnrptsPersonneResponse, options: RegistryFromAnrptsOptions): SuppliedIdentityRecord;
285
+ declare function subjectFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: SubjectFromRegistryOptions): SubjectRecord;
251
286
 
252
287
  /**
253
288
  * The HTTP header carrying the webhook signature:
@@ -395,4 +430,4 @@ interface VerifiedResult {
395
430
  */
396
431
  declare function verifyResultToken(token: string, opts: VerifyResultTokenOptions): Promise<VerifiedResult>;
397
432
 
398
- export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, RESULT_TOKEN_JWKS_PATH, type RegistryFromAnrptsOptions, ResultCheckProofs, ResultDuplicate, ResultRisk, SEKYRO_SIGNATURE_HEADER, SekyroApiError, type SekyroApiErrorCode, type SekyroApiErrorInit, type SekyroClientErrorCode, SekyroConfigError, type SekyroConfigErrorCode, SekyroEnvironment, type SekyroFlowError, type SekyroFlowErrorCode, type SekyroFlowErrorDetailsMap, SekyroResultTokenError, type SekyroResultTokenErrorCode, SekyroWebhookError, type SekyroWebhookErrorCode, ServiceId, SessionOutcome, SubjectReuseMode, SuppliedIdentityRecord, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, registryFromAnrpts, signatureFromHeaders, verifyResultToken, verifyWebhook };
433
+ export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, ResultDuplicate, ResultRisk, SEKYRO_SIGNATURE_HEADER, SekyroApiError, type SekyroApiErrorCode, type SekyroApiErrorInit, type SekyroClientErrorCode, SekyroConfigError, type SekyroConfigErrorCode, SekyroEnvironment, type SekyroFlowError, type SekyroFlowErrorCode, type SekyroFlowErrorDetailsMap, SekyroResultTokenError, type SekyroResultTokenErrorCode, SekyroWebhookError, type SekyroWebhookErrorCode, ServiceId, SessionOutcome, SessionSubjectInput, type SubjectFromRegistryOptions, type SubjectRecord, SubjectReuseMode, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, signatureFromHeaders, subjectFromNationalRegistry, verifyResultToken, verifyWebhook };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SuppliedIdentityRecord, c as WebhookEnvelope, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, R as ResultRisk, i as ResultCheckProofs, j as ResultDuplicate, A as AgeMethod, F as FetchLike } from './client-CcZfrjW1.js';
2
- export { k as AgeResult, l as CameraUnavailableCause, m as CheckState, n as CheckType, o as CreateSessionInput, C as CreatedSession, D as DEFAULT_BASE_URL, p as DEFAULT_TIMEOUT_MS, q as DecisionReason, r as DeepPartial, s as DeletedSubject, t as DeliverOptions, u as DocumentSubstitutionSettings, E as EidResult, v as EligibilityReason, w as FlowOverridableSettings, x as FlowOverrides, y as FlowServiceSettings, z as FlowSummary, I as IdentityMethod, B as LevelTarget, G as ListSessionsQuery, L as Locale, M as MatchReason, P as PolicyFailureReason, H as PortraitReportEntry, J as ProbeBindingReason, K as ProbeQuality, N as ProfileDocumentType, O as RequestOptions, Q as ResultTokenResponse, T as RevokeSubjectInput, S as Sekyro, U as SekyroOptions, X as Session, Y as SessionDevice, Z as SessionDeviceSignal, _ as SessionEventData, $ as SessionFailureReason, a0 as SessionFlowRef, a1 as SessionLifecycleEventData, a2 as SessionLinkInput, a3 as SessionNetwork, a4 as SessionNetworkEvent, a5 as SessionPortraitLink, a6 as SessionReviewDecidedEventData, a7 as SessionStatus, a8 as SessionStep, a9 as SessionStepCompletedEventData, aa as SessionSubjectInput, ab as SessionsApi, ac as Subject, ad as SubjectAssurance, ae as SubjectDeletedEventData, af as SubjectEnrolledEventData, ag as SubjectReferenceSource, ah as SubjectReuseDocument, ai as SubjectReuseTarget, aj as SubjectSession, ak as SubjectSessionInput, al as SubjectSessionTarget, am as SubjectStatus, an as SubjectSuspiciousActivityEventData, ao as SubjectUpdatedEventData, ap as SubjectsApi, aq as UsageThresholdReachedEventData, ar as VerifiedContacts, as as WebhookEnvelopeOf, at as WebhookEventDataMap, W as WebhookEventType } from './client-CcZfrjW1.js';
1
+ import { a as ServiceId, b as SessionSubjectInput, c as WebhookEnvelope, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, R as ResultRisk, i as ResultCheckProofs, j as ResultDuplicate, A as AgeMethod, F as FetchLike } from './client-BYoo67F-.js';
2
+ export { k as AgeResult, l as CameraUnavailableCause, m as CheckState, n as CheckType, o as CreateSessionInput, C as CreatedSession, p as CreatedSessionWarning, D as DEFAULT_BASE_URL, q as DEFAULT_TIMEOUT_MS, r as DecisionReason, s as DeepPartial, t as DeletedSubject, u as DeliverOptions, v as DocumentSubstitutionSettings, E as EidResult, w as EligibilityReason, x as FlowOverridableSettings, y as FlowOverrides, z as FlowServiceSettings, B as FlowSummary, I as IdNumberReason, G as IdentityMethod, H as LevelTarget, J as ListSessionsQuery, L as Locale, M as MatchReason, P as PolicyFailureReason, K as PortraitReportEntry, N as ProbeBindingReason, O as ProbeQuality, Q as ProfileDocumentType, T as RequestOptions, U as ResultTokenResponse, X as RevokeSubjectInput, S as Sekyro, Y as SekyroOptions, Z as Session, _ as SessionDevice, $ as SessionDeviceSignal, a0 as SessionEventData, a1 as SessionFailureReason, a2 as SessionFlowRef, a3 as SessionLifecycleEventData, a4 as SessionLinkInput, a5 as SessionNetwork, a6 as SessionNetworkEvent, a7 as SessionPortraitLink, a8 as SessionReviewDecidedEventData, a9 as SessionStatus, aa as SessionStep, ab as SessionStepCompletedEventData, ac as SessionsApi, ad as Subject, ae as SubjectAssurance, af as SubjectDeletedEventData, ag as SubjectEnrolledEventData, ah as SubjectIdNumber, ai as SubjectName, aj as SubjectReferenceSource, ak as SubjectReuseDocument, al as SubjectReuseTarget, am as SubjectSession, an as SubjectSessionInput, ao as SubjectSessionTarget, ap as SubjectStatus, aq as SubjectSuspiciousActivityEventData, ar as SubjectUpdatedEventData, as as SubjectsApi, at as SuppliedIdentityRecord, au as UsageThresholdReachedEventData, av as VerifiedContacts, aw as WebhookEnvelopeOf, ax as WebhookEventDataMap, W as WebhookEventType } from './client-BYoo67F-.js';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
@@ -37,9 +37,10 @@ declare class SekyroResultTokenError extends Error {
37
37
  constructor(code: SekyroResultTokenErrorCode, message?: string, cause?: unknown);
38
38
  }
39
39
  /** Why the {@link Sekyro} constructor rejected its options. @public */
40
- type SekyroConfigErrorCode = "missing_api_key" | "invalid_base_url" | "invalid_registry_record";
40
+ type SekyroConfigErrorCode = "missing_api_key" | "invalid_base_url" | "invalid_registry_record" | "registry_country_unsupported" | "registry_nationality_unmapped";
41
41
  /**
42
- * Thrown synchronously by `new Sekyro(...)` for an unusable configuration —
42
+ * Thrown synchronously by `new Sekyro(...)` for an unusable configuration, and by
43
+ * {@link subjectFromNationalRegistry} for an unusable registry answer:
43
44
  * before any request is made. Extends `TypeError` so existing
44
45
  * `instanceof TypeError` guards keep working.
45
46
  * @public
@@ -149,6 +150,8 @@ interface SekyroApiErrorInit {
149
150
  details?: unknown;
150
151
  /** Underlying error (network failures, abort reasons, JSON parse errors). */
151
152
  cause?: unknown;
153
+ /** Seconds to wait before retrying, from the response's `Retry-After` header. */
154
+ retryAfterSeconds?: number;
152
155
  }
153
156
  /** Error codes the SDK itself produces (as opposed to codes from the API). @public */
154
157
  type SekyroClientErrorCode = "network" | "timeout" | "http_error" | "malformed_response";
@@ -173,6 +176,12 @@ declare class SekyroApiError extends Error {
173
176
  */
174
177
  readonly details: unknown;
175
178
  readonly retryable: boolean;
179
+ /**
180
+ * Seconds to wait before retrying, from the response's `Retry-After` header
181
+ * (a number of seconds, or an HTTP date rounded up to whole seconds from now).
182
+ * `undefined` when the response had no usable header.
183
+ */
184
+ readonly retryAfterSeconds: number | undefined;
176
185
  constructor(init: SekyroApiErrorInit);
177
186
  }
178
187
  /**
@@ -221,33 +230,59 @@ interface AnrptsPersonneResponse {
221
230
  datePhoto?: string | undefined;
222
231
  [key: string]: unknown;
223
232
  }
224
- /** Options of {@link registryFromAnrpts}. @public */
225
- interface RegistryFromAnrptsOptions {
233
+ /**
234
+ * Registry answer formats Sekyro AI can map, by ISO 3166-1 alpha-2 country.
235
+ * @public
236
+ */
237
+ interface NationalRegistryResponses {
238
+ /** Mauritania: the ANRPTS `getPersonne` answer `{ personne, photo, datePhoto? }`. */
239
+ MR: AnrptsPersonneResponse;
240
+ }
241
+ /** A country {@link subjectFromNationalRegistry} can map. @public */
242
+ type NationalRegistryCountry = keyof NationalRegistryResponses;
243
+ /** Options of {@link subjectFromNationalRegistry}. @public */
244
+ interface SubjectFromRegistryOptions {
226
245
  /**
227
- * When YOUR system received this ANRPTS answer (not "now" when you map a cached
246
+ * When YOUR system received this answer (not "now" when you map a cached
228
247
  * answer). Required: records older than 24 h are refused at session create.
229
248
  */
230
249
  fetchedAt: Date | string;
250
+ /**
251
+ * The person's nationality (ISO 3166-1 alpha-2) when you map the registry's
252
+ * nationality text yourself; it replaces the SDK's mapping. Needed when the answer
253
+ * states a nationality the SDK cannot map (`registry_nationality_unmapped`).
254
+ */
255
+ nationality?: string;
231
256
  }
232
257
  /**
233
- * Convert an ANRPTS `getPersonne` answer that YOUR server already received,
234
- * with your own access, into the `input.suppliedIdentity` record of
235
- * `sessions.create` (partner-supplied identity data). A pure, local mapping:
236
- * it makes no network call, and Sekyro AI never sees, receives or stores any
237
- * ANRPTS key — only the record and photo you pass.
258
+ * The `subject` keys of a reference record, ready to spread into
259
+ * `sessions.create({ subject })`.
260
+ * @public
261
+ */
262
+ type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionSubjectInput, "fullName" | "names" | "birthPlace" | "sex" | "nationality" | "photoDate">;
263
+ /**
264
+ * Convert a national registry answer that YOUR server already received, with
265
+ * your own access, into the `subject` reference keys of `sessions.create`. A
266
+ * pure, local mapping: it makes no network call, and Sekyro AI never sees,
267
+ * receives or stores any registry key, only the record and photo you pass.
238
268
  *
239
269
  * ```ts
240
- * const anrpts = await myAnrptsClient.getPersonne(nni); // your call, your key
241
- * const suppliedIdentity = registryFromAnrpts(anrpts, { fetchedAt: receivedAt });
242
- * await sekyro.sessions.create({ input: { nni, suppliedIdentity } });
270
+ * const answer = await myRegistryClient.lookup(number); // your call, your key
271
+ * await sekyro.sessions.create({
272
+ * subject: { externalRef, ...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
273
+ * });
243
274
  * ```
244
275
  *
245
- * Throws {@link SekyroConfigError} (`invalid_registry_record`) when a required
246
- * field (NNI, French and Arabic first and last names, birth date, photo) is
247
- * missing. The message names the field, never its value.
276
+ * Throws {@link SekyroConfigError}: `invalid_registry_record` when a required
277
+ * field (the number, a given and family name in at least one script, the birth
278
+ * date, the photo) is missing or `fetchedAt` is not a date (the message names
279
+ * the field, never its value); `registry_country_unsupported` for a country
280
+ * without an adapter; `registry_nationality_unmapped` when the answer states a
281
+ * nationality and none of its values maps to an ISO code (map it yourself and pass
282
+ * `options.nationality`; the message never carries the value).
248
283
  * @public
249
284
  */
250
- declare function registryFromAnrpts(response: AnrptsPersonneResponse, options: RegistryFromAnrptsOptions): SuppliedIdentityRecord;
285
+ declare function subjectFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: SubjectFromRegistryOptions): SubjectRecord;
251
286
 
252
287
  /**
253
288
  * The HTTP header carrying the webhook signature:
@@ -395,4 +430,4 @@ interface VerifiedResult {
395
430
  */
396
431
  declare function verifyResultToken(token: string, opts: VerifyResultTokenOptions): Promise<VerifiedResult>;
397
432
 
398
- export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, RESULT_TOKEN_JWKS_PATH, type RegistryFromAnrptsOptions, ResultCheckProofs, ResultDuplicate, ResultRisk, SEKYRO_SIGNATURE_HEADER, SekyroApiError, type SekyroApiErrorCode, type SekyroApiErrorInit, type SekyroClientErrorCode, SekyroConfigError, type SekyroConfigErrorCode, SekyroEnvironment, type SekyroFlowError, type SekyroFlowErrorCode, type SekyroFlowErrorDetailsMap, SekyroResultTokenError, type SekyroResultTokenErrorCode, SekyroWebhookError, type SekyroWebhookErrorCode, ServiceId, SessionOutcome, SubjectReuseMode, SuppliedIdentityRecord, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, registryFromAnrpts, signatureFromHeaders, verifyResultToken, verifyWebhook };
433
+ export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, ResultDuplicate, ResultRisk, SEKYRO_SIGNATURE_HEADER, SekyroApiError, type SekyroApiErrorCode, type SekyroApiErrorInit, type SekyroClientErrorCode, SekyroConfigError, type SekyroConfigErrorCode, SekyroEnvironment, type SekyroFlowError, type SekyroFlowErrorCode, type SekyroFlowErrorDetailsMap, SekyroResultTokenError, type SekyroResultTokenErrorCode, SekyroWebhookError, type SekyroWebhookErrorCode, ServiceId, SessionOutcome, SessionSubjectInput, type SubjectFromRegistryOptions, type SubjectRecord, SubjectReuseMode, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, signatureFromHeaders, subjectFromNationalRegistry, verifyResultToken, verifyWebhook };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the ANRPTS answer can't be used as a registry record"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code)}},FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.8";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4;function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{}}}var SUBJECT_ID_RE=/^[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch}async call(method,path,body,idempotencyKey){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey);let init={method,headers,signal:AbortSignal.timeout(this.timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${this.timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init2.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init2.details=parsed.error.details),new SekyroApiError(init2)}throw new SekyroApiError({status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`})}if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport))}async listFlows(){return this.#transport.call("GET","/flows")}};function registryFromAnrpts(response,options){let p=response?.personne??{},required=(field,value)=>{let s=text(value);if(s===void 0)throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the ANRPTS answer has no usable \`${field}\``);return s},birthDate=isoDay(p.dateNaissance);if(birthDate===void 0)throw new SekyroConfigError("invalid_registry_record","Sekyro AI: the ANRPTS answer has no usable `personne.dateNaissance`");let photo=required("photo",response?.photo).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the ANRPTS answer) is missing or not a valid date");let record={nni:required("personne.nni",p.nni),firstNameFr:required("personne.prenomFr",p.prenomFr),lastNameFr:required("personne.patronymeFr",p.patronymeFr),firstNameAr:required("personne.prenomAr",p.prenomAr),lastNameAr:required("personne.patronymeAr",p.patronymeAr),birthDate,photo,fetchedAt:fetchedAt.toISOString()},optional=[["fatherNameFr",p.perePrenomFr],["fatherNameAr",p.perePrenomAr],["birthPlaceFr",p.lieuNaissanceFr],["birthPlaceAr",p.lieuNaissanceAr]];for(let[key,value]of optional){let s=text(value);s!==void 0&&(record[key]=s)}let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let nationalities=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0).slice(0,5):[];nationalities.length>0&&(record.nationalities=nationalities);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.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 jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,registryFromAnrpts,signatureFromHeaders,verifyResultToken,verifyWebhook};
1
+ var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.9";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4;function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{}}}var SUBJECT_ID_RE=/^[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch}async call(method,path,body,idempotencyKey){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey);let init={method,headers,signal:AbortSignal.timeout(this.timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${this.timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init3={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init3.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init3.details=parsed.error.details),retryAfterSeconds!==void 0&&(init3.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init3)}let init2={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};throw retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport))}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function subjectFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationality=nationality);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.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 jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sekyro/node",
3
- "version": "0.1.0-rc.8",
3
+ "version": "0.1.0-rc.9",
4
4
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
package/sbom.cdx.json CHANGED
@@ -97,8 +97,8 @@
97
97
  "type": "application",
98
98
  "name": "node",
99
99
  "group": "@sekyro",
100
- "version": "0.1.0-rc.8",
101
- "bom-ref": "@sekyro/node@0.1.0-rc.8",
100
+ "version": "0.1.0-rc.9",
101
+ "bom-ref": "@sekyro/node@0.1.0-rc.9",
102
102
  "description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
103
103
  "licenses": [
104
104
  {
@@ -108,7 +108,7 @@
108
108
  }
109
109
  }
110
110
  ],
111
- "purl": "pkg:npm/%40sekyro/node@0.1.0-rc.8?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
111
+ "purl": "pkg:npm/%40sekyro/node@0.1.0-rc.9?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FIBTIKAR-Technologies%2Fibtikar-identity.git%23packages%2Fsekyro-node",
112
112
  "externalReferences": [
113
113
  {
114
114
  "url": "https://github.com/IBTIKAR-Technologies/ibtikar-identity/issues",
@@ -149,7 +149,7 @@
149
149
  "type": "library",
150
150
  "name": "jose",
151
151
  "version": "5.10.0",
152
- "bom-ref": "@sekyro/node@0.1.0-rc.8|jose@5.10.0",
152
+ "bom-ref": "@sekyro/node@0.1.0-rc.9|jose@5.10.0",
153
153
  "licenses": [
154
154
  {
155
155
  "license": {
@@ -182,13 +182,13 @@
182
182
  ],
183
183
  "dependencies": [
184
184
  {
185
- "ref": "@sekyro/node@0.1.0-rc.8",
185
+ "ref": "@sekyro/node@0.1.0-rc.9",
186
186
  "dependsOn": [
187
- "@sekyro/node@0.1.0-rc.8|jose@5.10.0"
187
+ "@sekyro/node@0.1.0-rc.9|jose@5.10.0"
188
188
  ]
189
189
  },
190
190
  {
191
- "ref": "@sekyro/node@0.1.0-rc.8|jose@5.10.0"
191
+ "ref": "@sekyro/node@0.1.0-rc.9|jose@5.10.0"
192
192
  }
193
193
  ]
194
194
  }