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

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.
@@ -1,10 +1,11 @@
1
- import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-B7_KS_rG.js';
1
+ import { A as AgeMethod, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-C2VDmckH.js';
2
2
 
3
3
  /**
4
4
  * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
5
5
  * 2026-10-29 §4). Pure: no I/O, no `jose`, no `node:` built-ins, so it runs in
6
6
  * an edge runtime as well as on Node.
7
7
  */
8
+
8
9
  /** The claim contract version this SDK writes and reads. @public */
9
10
  declare const CLAIM_VERSION = 1;
10
11
  /**
@@ -17,7 +18,8 @@ type ClaimFlag = "face_mismatch" | "duplicate" | "revoked";
17
18
  /**
18
19
  * The small object a connector stores on the auth provider's user and the
19
20
  * session token carries (spec §4.1). Timestamps are unix seconds. It never
20
- * carries a name, a document number, a photo, a score or the risk block.
21
+ * carries a name, a document number, a photo, a score, the risk block, a
22
+ * birth date or an estimated age.
21
23
  * @public
22
24
  */
23
25
  interface SekyroClaim {
@@ -39,6 +41,17 @@ interface SekyroClaim {
39
41
  env: "live" | "sandbox";
40
42
  /** Sorted and deduplicated; absent when empty. */
41
43
  flags?: ClaimFlag[];
44
+ /**
45
+ * The minimum age the person proved: the threshold of the flow that proved
46
+ * it, never the person's age. Present together with `age_method`, absent
47
+ * until a session of a flow with a minimum age proved it.
48
+ */
49
+ age_over?: number;
50
+ /**
51
+ * How `age_over` was proved: `estimated` (the age check (selfie) step), or
52
+ * `document`, `chip`, `registry` or `eid` (a birth date from identity data).
53
+ */
54
+ age_method?: AgeMethod;
42
55
  }
43
56
  /**
44
57
  * A terminal session result in the shape {@link mergeClaim} reads, built from
@@ -60,6 +73,11 @@ interface VerificationResultInput {
60
73
  subjectConflict?: boolean;
61
74
  /** `true` when the session reported at least one duplicate subject. */
62
75
  duplicates?: boolean;
76
+ /** The minimum age the session proved and how (the result token's `sekyro.age`); absent when it proved none. */
77
+ age?: {
78
+ over: number;
79
+ method: AgeMethod;
80
+ };
63
81
  }
64
82
  /**
65
83
  * What happened, as {@link mergeClaim} sees it. On a revocation or deletion,
@@ -81,7 +99,7 @@ type MergeEvent = {
81
99
  userInExternalRefs?: boolean;
82
100
  };
83
101
  /** The rule {@link mergeClaim} applied. @public */
84
- type MergeRule = "created" | "raised" | "renewed" | "rechecked" | "face_mismatch" | "revoked" | "revoked_ignored" | "not_approved" | "stale_ignored" | "env_mismatch" | "unsupported_version" | "subject_mismatch" | "no_change";
102
+ type MergeRule = "created" | "raised" | "renewed" | "rechecked" | "face_mismatch" | "revoked" | "revoked_ignored" | "not_approved" | "stale_ignored" | "env_mismatch" | "unsupported_version" | "subject_mismatch" | "age_proved" | "no_change";
85
103
  /** Result of {@link mergeClaim}: write `claim` only when `changed`. @public */
86
104
  interface MergeOutcome {
87
105
  claim: SekyroClaim | null;
@@ -103,7 +121,10 @@ declare function parseClaim(value: unknown): SekyroClaim | null;
103
121
  * failed attempt never erases a proof, a weaker proof never lowers the level,
104
122
  * a result from another environment is refused, and a revoked claim stays
105
123
  * revoked (`revoked_ignored`) until a session of another, known subject
106
- * proves a level again.
124
+ * proves a level again. The age (`age_over`, `age_method`) keeps the stronger
125
+ * proof of the same person: a birth date from identity data beats an
126
+ * estimate, then the higher threshold wins; a session at a lower level that
127
+ * proved a stronger age writes it alone (`age_proved`); a revocation clears it.
107
128
  *
108
129
  * @param previous - The stored value (object, JSON string or nothing).
109
130
  * @param event - A session result, or a revocation or deletion of a subject.
@@ -138,9 +159,20 @@ interface GatePolicy {
138
159
  env?: "live" | "sandbox";
139
160
  /** Flags that block. Default `["revoked", "face_mismatch"]`. */
140
161
  denyFlags?: ClaimFlag[];
162
+ /**
163
+ * The minimum age the person must have proved: the claim's `age_over` must
164
+ * be this or higher. Off when omitted.
165
+ */
166
+ minAge?: number;
167
+ /**
168
+ * The age methods that pass, for example `["document", "chip", "registry", "eid"]`
169
+ * when the route needs a birth date from identity data rather than an
170
+ * estimate; any when omitted. Applies only with `minAge`.
171
+ */
172
+ ageMethods?: AgeMethod[];
141
173
  }
142
174
  /** Why a gate failed. @public */
143
- type GateReason = "no_claim" | "unsupported_version" | "wrong_env" | "flagged" | "level_too_low" | "stale" | "recheck_stale" | "assurance_not_allowed";
175
+ type GateReason = "no_claim" | "unsupported_version" | "wrong_env" | "flagged" | "level_too_low" | "stale" | "recheck_stale" | "assurance_not_allowed" | "age_not_proven" | "age_method_not_allowed";
144
176
  /**
145
177
  * What the app should do about a failed gate: start a verification
146
178
  * (`verify`), a step-up (`step_up`), a re-check (`recheck`), or refuse
@@ -161,7 +193,8 @@ type GateResult = {
161
193
  /**
162
194
  * Check a claim (as read from the session token, an object or its JSON
163
195
  * string) against a policy. The checks run in this order: present, version,
164
- * environment, flags, level, age, re-check age, assurance.
196
+ * environment, flags, level, freshness (`maxAgeDays`), re-check freshness,
197
+ * assurance, minimum age, age method.
165
198
  *
166
199
  * @param claim - The claim value, or anything else (`no_claim`).
167
200
  * @param policy - What the route requires.
@@ -273,16 +306,21 @@ type ConnectorLogEvent = {
273
306
  };
274
307
  /**
275
308
  * Passed to {@link ConnectorOptions.onRevocationUnresolved}: Sekyro revoked or
276
- * deleted a subject and the connector found no user to clear the claim on.
309
+ * deleted a person and the connector found no user to clear the claim on.
277
310
  * Ids only: never provider data, a claim body or a token.
278
311
  * @public
279
312
  */
280
313
  interface RevocationUnresolvedEvent {
281
- /** The Sekyro subject that was revoked or deleted. */
314
+ /** The Sekyro person that was revoked or deleted, bare (24 hexadecimal characters). */
282
315
  subjectId: string;
316
+ /** The same person as `per_...`. */
317
+ personId: string;
283
318
  /** The provider adapter's name, for example `zitadel` or `supabase`. */
284
319
  provider: string;
285
- /** `revoked` for `subject.updated` with status `revoked`, `deleted` for `subject.deleted`. */
320
+ /**
321
+ * `revoked` for `person.updated` (or `subject.updated`) with status
322
+ * `revoked`, `deleted` for `person.deleted` (or `subject.deleted`).
323
+ */
286
324
  reason: "revoked" | "deleted";
287
325
  }
288
326
  /** Options of {@link createConnector}. @public */
@@ -297,9 +335,9 @@ interface ConnectorOptions {
297
335
  webhookSecret: string;
298
336
  /** Where the claim is stored. */
299
337
  provider: ProviderAdapter;
300
- /** What {@link Connector.userDeleted} does with the person's subjects. Default `ignore`. */
338
+ /** What {@link Connector.userDeleted} does with the user's Sekyro people. Default `ignore`. */
301
339
  onUserDeleted?: "ignore" | "revoke" | "delete";
302
- /** Delivery de-duplication and the subject-to-user map. Default {@link memoryStore}. */
340
+ /** Delivery de-duplication and the person-to-user map. Default {@link memoryStore}. */
303
341
  store?: ConnectorStore;
304
342
  /** Refuse to write a terminal webhook without a result token. Default `false`. */
305
343
  requireResultToken?: boolean;
@@ -314,9 +352,9 @@ interface ConnectorOptions {
314
352
  /** Receives every {@link ConnectorLogEvent}; the connector never writes to the console. */
315
353
  logger?: (event: ConnectorLogEvent) => void;
316
354
  /**
317
- * Called when Sekyro revokes or deletes a subject and the connector cannot
355
+ * Called when Sekyro revokes or deletes a person and the connector cannot
318
356
  * find the user (no `externalRefs`, no store entry), so no claim was
319
- * cleared. Find the user for `event.subjectId` and remove their access.
357
+ * cleared. Find the user for `event.personId` and remove their access.
320
358
  * Runs after the `revocation_unresolved` log line and telemetry event, in the
321
359
  * background: the webhook does not wait for it, and a throw or rejection is
322
360
  * caught and reported to `logger` as `revocation_handler_failed`.
@@ -327,7 +365,7 @@ interface ConnectorOptions {
327
365
  * Default `true`: every API call carries the `x-sekyro-connector` header
328
366
  * (`<provider>/<version>`), and after each claim write (and each
329
367
  * `revocation_unresolved`) the connector posts an event with ids only (type,
330
- * provider, session id, subject id, time; never the claim, a token or user
368
+ * provider, session id, person id, time; never the claim, a token or user
331
369
  * data), in the background with a 2-second timeout and no retry. Only the
332
370
  * six Sekyro provider packages send it. `false` sends neither.
333
371
  */
@@ -384,15 +422,18 @@ interface Connector {
384
422
  claim: SekyroClaim | null;
385
423
  rule: MergeRule;
386
424
  }>;
387
- /** Create a verification session for your user (`subject.externalRef` = `userId`). */
425
+ /** Create a verification session for your user (`person.externalRef` = `userId`). */
388
426
  start(userId: string, opts?: StartOptions): Promise<CreatedSession>;
389
- /** Create a re-check session for your user's subject. */
427
+ /** Create a re-check session for your user's Sekyro person. */
390
428
  recheck(userId: string, opts?: Omit<StartOptions, "flow">): Promise<CreatedSession>;
391
- /** Create a step-up session for your user's subject with an identity flow. */
429
+ /** Create a step-up session for your user's Sekyro person with an identity flow. */
392
430
  stepUp(userId: string, opts: StartOptions & {
393
431
  flow: string;
394
432
  }): Promise<CreatedSession>;
395
- /** Your app deleted the user: apply the `onUserDeleted` policy to the person's subjects. */
433
+ /**
434
+ * Your app deleted the user: apply the `onUserDeleted` policy to every
435
+ * Sekyro person carrying the user's id. `subjects` is how many it touched.
436
+ */
396
437
  userDeleted(userId: string): Promise<{
397
438
  policy: "ignore" | "revoke" | "delete";
398
439
  subjects: number;
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.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});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.13";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1&&v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&("personId"in target||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/sessions")}else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.subjects=this.people,Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.person_id??d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SessionSubjectInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-B7_KS_rG.cjs';
2
- export { m as AgeResult, n as CameraUnavailableCause, o as CheckState, p as CheckType, q as ConnectorIdentity, r as CreateSessionInput, C as CreatedSession, s as CreatedSessionWarning, D as DEFAULT_BASE_URL, t as DEFAULT_TIMEOUT_MS, u as DecisionReason, v as DeepPartial, w as DeletedSubject, x as DeliverOptions, y as DocumentSubstitutionSettings, E as EidResult, z as EligibilityReason, B as FlowOverridableSettings, G as FlowOverrides, H as FlowServiceSettings, I as FlowSummary, J as IdNumberReason, K as IdentityMethod, M as LevelTarget, N as ListSessionsQuery, L as Locale, O as MatchReason, P as PolicyFailureReason, Q as PortraitReportEntry, T as PriorReviewReason, U as ProbeBindingReason, X as ProbeQuality, Y as ProfileDocumentType, Z as RequestOptions, _ as ResultTokenResponse, $ as ReviewOutcomeReason, a0 as RevokeSubjectInput, S as Sekyro, a1 as SekyroOptions, a2 as Session, a3 as SessionDevice, a4 as SessionDeviceSignal, a5 as SessionEventData, a6 as SessionFailureReason, a7 as SessionFlowRef, a8 as SessionLifecycleEventData, a9 as SessionLinkInput, aa as SessionNetwork, ab as SessionNetworkEvent, ac as SessionPortraitLink, ad as SessionReviewDecidedEventData, ae as SessionStatus, af as SessionStep, ag as SessionStepCompletedEventData, ah as SessionStepDecision, ai as SessionSupersededEventData, aj as SessionsApi, ak as Subject, al as SubjectAssurance, am as SubjectDeletedEventData, an as SubjectEnrolledEventData, ao as SubjectIdNumber, ap as SubjectName, aq as SubjectReferenceSource, ar as SubjectReuseDocument, as as SubjectReuseTarget, at as SubjectSession, au as SubjectSessionInput, av as SubjectSessionTarget, aw as SubjectStatus, ax as SubjectSuspiciousActivityEventData, ay as SubjectUpdatedEventData, az as SubjectsApi, aA as SuppliedIdentityRecord, aB as UsageThresholdReachedEventData, aC as VerifiedContacts, aD as WebhookEnvelopeOf, aE as WebhookEventDataMap, W as WebhookEventType } from './client-B7_KS_rG.cjs';
1
+ import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-C2VDmckH.cjs';
2
+ export { m as AgeResult, n as AmlMatchFlaggedEventData, o as CameraUnavailableCause, p as CheckState, q as CheckType, r as ConnectorIdentity, s as CreateSessionInput, C as CreatedSession, t as CreatedSessionWarning, D as DEFAULT_BASE_URL, u as DEFAULT_TIMEOUT_MS, v as DecidedBy, w as DecisionReason, x as DeepPartial, y as DeletedPerson, z as DeletedSubject, B as DeliverOptions, E as DocumentSubstitutionSettings, G as EidResult, H as EligibilityReason, I as ExtendLinkInput, J as FlowOverridableSettings, K as FlowOverrides, M as FlowServiceSettings, N as FlowSummary, O as IdNumberReason, P as Identity, Q as IdentityBirthPlace, T as IdentityDocument, U as IdentityIdNumber, X as IdentityMethod, Y as IdentityName, Z as IdentityScalarKey, _ as IdentitySource, $ as IdentitySources, a0 as LevelTarget, a1 as ListPeopleQuery, a2 as ListScreeningsQuery, a3 as ListSessionsQuery, L as Locale, a4 as MatchReason, a5 as MediaBytes, a6 as MediaBytesOptions, a7 as MediaItem, a8 as MediaKind, a9 as MediaList, aa as NameForm, ab as Page, ac as PeopleApi, ad as Person, ae as PersonBirthPlaceInput, af as PersonDeletedEventData, ag as PersonDocumentInput, ah as PersonEnrolledEventData, ai as PersonSession, aj as PersonSessionInput, ak as PersonSessionTarget, al as PersonSuspiciousActivityEventData, am as PersonUpdatedEventData, an as PolicyFailureReason, ao as PortraitReportEntry, ap as PriorReviewReason, aq as ProbeBindingReason, ar as ProbeQuality, as as ProfileDocumentType, at as RequestOptions, au as ResultTokenResponse, av as ReviewOutcomeReason, aw as RevokePersonInput, ax as RevokeSubjectInput, ay as ScreenPersonInput, az as Screening, aA as ScreeningHit, aB as ScreeningHitSummary, aC as ScreeningList, aD as ScreeningStatus, aE as ScreeningTrigger, aF as ScreeningUnavailableReason, S as Sekyro, aG as SekyroOptions, aH as Session, aI as SessionDevice, aJ as SessionDeviceSignal, aK as SessionEventData, aL as SessionFailureReason, aM as SessionFlowRef, aN as SessionLifecycleEventData, aO as SessionLinkDelivery, aP as SessionLinkExpiry, aQ as SessionLinkInput, aR as SessionNetwork, aS as SessionNetworkEvent, aT as SessionPortraitLink, aU as SessionReviewDecidedEventData, aV as SessionScreening, aW as SessionStatus, aX as SessionStep, aY as SessionStepCompletedEventData, aZ as SessionStepDecision, a_ as SessionSubjectInput, a$ as SessionSupersededEventData, b0 as SessionsApi, b1 as Subject, b2 as SubjectAssurance, b3 as SubjectDeletedEventData, b4 as SubjectEnrolledEventData, b5 as SubjectIdNumber, b6 as SubjectName, b7 as SubjectReferenceSource, b8 as SubjectReuseDocument, b9 as SubjectReuseTarget, ba as SubjectSession, bb as SubjectSessionInput, bc as SubjectSessionTarget, bd as SubjectStatus, be as SubjectSuspiciousActivityEventData, bf as SubjectUpdatedEventData, bg as SubjectsApi, bh as SuppliedIdentityRecord, bi as UsageThresholdReachedEventData, bj as VerifiedContacts, bk as WebhookEnvelopeOf, bl as WebhookEventDataMap, W as WebhookEventType } from './client-C2VDmckH.cjs';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
@@ -144,7 +144,7 @@ interface SekyroApiErrorInit {
144
144
  /** API error code, or `network` | `timeout` | `http_error` | `malformed_response`. */
145
145
  code: SekyroApiErrorCode;
146
146
  message: string;
147
- /** The API's `request_id`, when the response carried one. */
147
+ /** The API's `requestId` (or the older `request_id`), when the response carried one. */
148
148
  requestId?: string;
149
149
  /** The API's `error.details`, when the response carried them (the flow codes: {@link SekyroFlowErrorDetailsMap}). */
150
150
  details?: unknown;
@@ -157,8 +157,9 @@ interface SekyroApiErrorInit {
157
157
  type SekyroClientErrorCode = "network" | "timeout" | "http_error" | "malformed_response";
158
158
  /**
159
159
  * Any failed call through {@link Sekyro}: a non-2xx partner envelope
160
- * `{ status: 'error', error: { code, message, request_id } }`, a non-JSON
161
- * response, a network failure or a timeout.
160
+ * `{ success: false, error: { code, message, requestId, details? } }` (the
161
+ * older `{ status: 'error', error: { ..., request_id } }` is read too), a
162
+ * non-JSON response, a network failure or a timeout.
162
163
  *
163
164
  * `retryable` is `true` for `network`, `timeout`, HTTP 429, HTTP 5xx and the
164
165
  * `idempotency_in_progress` code — retry with the SAME idempotency key.
@@ -238,10 +239,10 @@ interface NationalRegistryResponses {
238
239
  /** Mauritania: the ANRPTS `getPersonne` answer `{ personne, photo, datePhoto? }`. */
239
240
  MR: AnrptsPersonneResponse;
240
241
  }
241
- /** A country {@link subjectFromNationalRegistry} can map. @public */
242
+ /** A country {@link personFromNationalRegistry} can map. @public */
242
243
  type NationalRegistryCountry = keyof NationalRegistryResponses;
243
- /** Options of {@link subjectFromNationalRegistry}. @public */
244
- interface SubjectFromRegistryOptions {
244
+ /** Options of {@link personFromNationalRegistry}. @public */
245
+ interface PersonFromRegistryOptions {
245
246
  /**
246
247
  * When YOUR system received this answer (not "now" when you map a cached
247
248
  * answer). Required: records older than 24 h are refused at session create.
@@ -255,21 +256,34 @@ interface SubjectFromRegistryOptions {
255
256
  nationality?: string;
256
257
  }
257
258
  /**
258
- * The `subject` keys of a reference record, ready to spread into
259
- * `sessions.create({ subject })`.
259
+ * The former name of {@link PersonFromRegistryOptions}.
260
+ * @deprecated Use {@link PersonFromRegistryOptions}.
260
261
  * @public
261
262
  */
262
- type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionSubjectInput, "fullName" | "names" | "birthPlace" | "sex" | "nationality" | "photoDate">;
263
+ type SubjectFromRegistryOptions = PersonFromRegistryOptions;
264
+ /**
265
+ * The `person` keys of a reference record, ready to spread into
266
+ * `sessions.create({ person })`.
267
+ * @public
268
+ */
269
+ type PersonRecord = Required<Pick<SessionPersonInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionPersonInput, "fullName" | "names" | "birthPlace" | "sex" | "nationalities" | "photoDate">;
270
+ /**
271
+ * The former name of {@link PersonRecord}.
272
+ * @deprecated Use {@link PersonRecord}. The record now carries
273
+ * `nationalities: [code]` (not `nationality`).
274
+ * @public
275
+ */
276
+ type SubjectRecord = PersonRecord;
263
277
  /**
264
278
  * Convert a national registry answer that YOUR server already received, with
265
- * your own access, into the `subject` reference keys of `sessions.create`. A
279
+ * your own access, into the `person` reference keys of `sessions.create`. A
266
280
  * pure, local mapping: it makes no network call, and Sekyro AI never sees,
267
281
  * receives or stores any registry key, only the record and photo you pass.
268
282
  *
269
283
  * ```ts
270
284
  * const answer = await myRegistryClient.lookup(number); // your call, your key
271
285
  * await sekyro.sessions.create({
272
- * subject: { externalRef, ...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
286
+ * person: { externalRef, ...personFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
273
287
  * });
274
288
  * ```
275
289
  *
@@ -282,6 +296,13 @@ type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate"
282
296
  * `options.nationality`; the message never carries the value).
283
297
  * @public
284
298
  */
299
+ declare function personFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: PersonFromRegistryOptions): PersonRecord;
300
+ /**
301
+ * The former name of {@link personFromNationalRegistry}: the same mapping.
302
+ * @deprecated Use {@link personFromNationalRegistry}, the same mapping under the
303
+ * `person` name (spread the result into `person`, not `subject`).
304
+ * @public
305
+ */
285
306
  declare function subjectFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: SubjectFromRegistryOptions): SubjectRecord;
286
307
 
287
308
  /**
@@ -456,4 +477,4 @@ interface VerifiedResult {
456
477
  */
457
478
  declare function verifyResultToken(token: string, opts: VerifyResultTokenOptions): Promise<VerifiedResult>;
458
479
 
459
- export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FailureIdentification, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, type ResultDecision, ResultDuplicate, ResultRisk, ReviewReason, 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 };
480
+ export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FailureIdentification, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, type PersonFromRegistryOptions, type PersonRecord, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, type ResultDecision, ResultDuplicate, ResultRisk, ReviewReason, 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, SessionPersonInput, type SubjectFromRegistryOptions, type SubjectRecord, SubjectReuseMode, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, personFromNationalRegistry, signatureFromHeaders, subjectFromNationalRegistry, verifyResultToken, verifyWebhook };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServiceId, b as SessionSubjectInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-B7_KS_rG.js';
2
- export { m as AgeResult, n as CameraUnavailableCause, o as CheckState, p as CheckType, q as ConnectorIdentity, r as CreateSessionInput, C as CreatedSession, s as CreatedSessionWarning, D as DEFAULT_BASE_URL, t as DEFAULT_TIMEOUT_MS, u as DecisionReason, v as DeepPartial, w as DeletedSubject, x as DeliverOptions, y as DocumentSubstitutionSettings, E as EidResult, z as EligibilityReason, B as FlowOverridableSettings, G as FlowOverrides, H as FlowServiceSettings, I as FlowSummary, J as IdNumberReason, K as IdentityMethod, M as LevelTarget, N as ListSessionsQuery, L as Locale, O as MatchReason, P as PolicyFailureReason, Q as PortraitReportEntry, T as PriorReviewReason, U as ProbeBindingReason, X as ProbeQuality, Y as ProfileDocumentType, Z as RequestOptions, _ as ResultTokenResponse, $ as ReviewOutcomeReason, a0 as RevokeSubjectInput, S as Sekyro, a1 as SekyroOptions, a2 as Session, a3 as SessionDevice, a4 as SessionDeviceSignal, a5 as SessionEventData, a6 as SessionFailureReason, a7 as SessionFlowRef, a8 as SessionLifecycleEventData, a9 as SessionLinkInput, aa as SessionNetwork, ab as SessionNetworkEvent, ac as SessionPortraitLink, ad as SessionReviewDecidedEventData, ae as SessionStatus, af as SessionStep, ag as SessionStepCompletedEventData, ah as SessionStepDecision, ai as SessionSupersededEventData, aj as SessionsApi, ak as Subject, al as SubjectAssurance, am as SubjectDeletedEventData, an as SubjectEnrolledEventData, ao as SubjectIdNumber, ap as SubjectName, aq as SubjectReferenceSource, ar as SubjectReuseDocument, as as SubjectReuseTarget, at as SubjectSession, au as SubjectSessionInput, av as SubjectSessionTarget, aw as SubjectStatus, ax as SubjectSuspiciousActivityEventData, ay as SubjectUpdatedEventData, az as SubjectsApi, aA as SuppliedIdentityRecord, aB as UsageThresholdReachedEventData, aC as VerifiedContacts, aD as WebhookEnvelopeOf, aE as WebhookEventDataMap, W as WebhookEventType } from './client-B7_KS_rG.js';
1
+ import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-C2VDmckH.js';
2
+ export { m as AgeResult, n as AmlMatchFlaggedEventData, o as CameraUnavailableCause, p as CheckState, q as CheckType, r as ConnectorIdentity, s as CreateSessionInput, C as CreatedSession, t as CreatedSessionWarning, D as DEFAULT_BASE_URL, u as DEFAULT_TIMEOUT_MS, v as DecidedBy, w as DecisionReason, x as DeepPartial, y as DeletedPerson, z as DeletedSubject, B as DeliverOptions, E as DocumentSubstitutionSettings, G as EidResult, H as EligibilityReason, I as ExtendLinkInput, J as FlowOverridableSettings, K as FlowOverrides, M as FlowServiceSettings, N as FlowSummary, O as IdNumberReason, P as Identity, Q as IdentityBirthPlace, T as IdentityDocument, U as IdentityIdNumber, X as IdentityMethod, Y as IdentityName, Z as IdentityScalarKey, _ as IdentitySource, $ as IdentitySources, a0 as LevelTarget, a1 as ListPeopleQuery, a2 as ListScreeningsQuery, a3 as ListSessionsQuery, L as Locale, a4 as MatchReason, a5 as MediaBytes, a6 as MediaBytesOptions, a7 as MediaItem, a8 as MediaKind, a9 as MediaList, aa as NameForm, ab as Page, ac as PeopleApi, ad as Person, ae as PersonBirthPlaceInput, af as PersonDeletedEventData, ag as PersonDocumentInput, ah as PersonEnrolledEventData, ai as PersonSession, aj as PersonSessionInput, ak as PersonSessionTarget, al as PersonSuspiciousActivityEventData, am as PersonUpdatedEventData, an as PolicyFailureReason, ao as PortraitReportEntry, ap as PriorReviewReason, aq as ProbeBindingReason, ar as ProbeQuality, as as ProfileDocumentType, at as RequestOptions, au as ResultTokenResponse, av as ReviewOutcomeReason, aw as RevokePersonInput, ax as RevokeSubjectInput, ay as ScreenPersonInput, az as Screening, aA as ScreeningHit, aB as ScreeningHitSummary, aC as ScreeningList, aD as ScreeningStatus, aE as ScreeningTrigger, aF as ScreeningUnavailableReason, S as Sekyro, aG as SekyroOptions, aH as Session, aI as SessionDevice, aJ as SessionDeviceSignal, aK as SessionEventData, aL as SessionFailureReason, aM as SessionFlowRef, aN as SessionLifecycleEventData, aO as SessionLinkDelivery, aP as SessionLinkExpiry, aQ as SessionLinkInput, aR as SessionNetwork, aS as SessionNetworkEvent, aT as SessionPortraitLink, aU as SessionReviewDecidedEventData, aV as SessionScreening, aW as SessionStatus, aX as SessionStep, aY as SessionStepCompletedEventData, aZ as SessionStepDecision, a_ as SessionSubjectInput, a$ as SessionSupersededEventData, b0 as SessionsApi, b1 as Subject, b2 as SubjectAssurance, b3 as SubjectDeletedEventData, b4 as SubjectEnrolledEventData, b5 as SubjectIdNumber, b6 as SubjectName, b7 as SubjectReferenceSource, b8 as SubjectReuseDocument, b9 as SubjectReuseTarget, ba as SubjectSession, bb as SubjectSessionInput, bc as SubjectSessionTarget, bd as SubjectStatus, be as SubjectSuspiciousActivityEventData, bf as SubjectUpdatedEventData, bg as SubjectsApi, bh as SuppliedIdentityRecord, bi as UsageThresholdReachedEventData, bj as VerifiedContacts, bk as WebhookEnvelopeOf, bl as WebhookEventDataMap, W as WebhookEventType } from './client-C2VDmckH.js';
3
3
 
4
4
  /** Why {@link verifyWebhook} rejected a delivery. @public */
5
5
  type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
@@ -144,7 +144,7 @@ interface SekyroApiErrorInit {
144
144
  /** API error code, or `network` | `timeout` | `http_error` | `malformed_response`. */
145
145
  code: SekyroApiErrorCode;
146
146
  message: string;
147
- /** The API's `request_id`, when the response carried one. */
147
+ /** The API's `requestId` (or the older `request_id`), when the response carried one. */
148
148
  requestId?: string;
149
149
  /** The API's `error.details`, when the response carried them (the flow codes: {@link SekyroFlowErrorDetailsMap}). */
150
150
  details?: unknown;
@@ -157,8 +157,9 @@ interface SekyroApiErrorInit {
157
157
  type SekyroClientErrorCode = "network" | "timeout" | "http_error" | "malformed_response";
158
158
  /**
159
159
  * Any failed call through {@link Sekyro}: a non-2xx partner envelope
160
- * `{ status: 'error', error: { code, message, request_id } }`, a non-JSON
161
- * response, a network failure or a timeout.
160
+ * `{ success: false, error: { code, message, requestId, details? } }` (the
161
+ * older `{ status: 'error', error: { ..., request_id } }` is read too), a
162
+ * non-JSON response, a network failure or a timeout.
162
163
  *
163
164
  * `retryable` is `true` for `network`, `timeout`, HTTP 429, HTTP 5xx and the
164
165
  * `idempotency_in_progress` code — retry with the SAME idempotency key.
@@ -238,10 +239,10 @@ interface NationalRegistryResponses {
238
239
  /** Mauritania: the ANRPTS `getPersonne` answer `{ personne, photo, datePhoto? }`. */
239
240
  MR: AnrptsPersonneResponse;
240
241
  }
241
- /** A country {@link subjectFromNationalRegistry} can map. @public */
242
+ /** A country {@link personFromNationalRegistry} can map. @public */
242
243
  type NationalRegistryCountry = keyof NationalRegistryResponses;
243
- /** Options of {@link subjectFromNationalRegistry}. @public */
244
- interface SubjectFromRegistryOptions {
244
+ /** Options of {@link personFromNationalRegistry}. @public */
245
+ interface PersonFromRegistryOptions {
245
246
  /**
246
247
  * When YOUR system received this answer (not "now" when you map a cached
247
248
  * answer). Required: records older than 24 h are refused at session create.
@@ -255,21 +256,34 @@ interface SubjectFromRegistryOptions {
255
256
  nationality?: string;
256
257
  }
257
258
  /**
258
- * The `subject` keys of a reference record, ready to spread into
259
- * `sessions.create({ subject })`.
259
+ * The former name of {@link PersonFromRegistryOptions}.
260
+ * @deprecated Use {@link PersonFromRegistryOptions}.
260
261
  * @public
261
262
  */
262
- type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionSubjectInput, "fullName" | "names" | "birthPlace" | "sex" | "nationality" | "photoDate">;
263
+ type SubjectFromRegistryOptions = PersonFromRegistryOptions;
264
+ /**
265
+ * The `person` keys of a reference record, ready to spread into
266
+ * `sessions.create({ person })`.
267
+ * @public
268
+ */
269
+ type PersonRecord = Required<Pick<SessionPersonInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionPersonInput, "fullName" | "names" | "birthPlace" | "sex" | "nationalities" | "photoDate">;
270
+ /**
271
+ * The former name of {@link PersonRecord}.
272
+ * @deprecated Use {@link PersonRecord}. The record now carries
273
+ * `nationalities: [code]` (not `nationality`).
274
+ * @public
275
+ */
276
+ type SubjectRecord = PersonRecord;
263
277
  /**
264
278
  * Convert a national registry answer that YOUR server already received, with
265
- * your own access, into the `subject` reference keys of `sessions.create`. A
279
+ * your own access, into the `person` reference keys of `sessions.create`. A
266
280
  * pure, local mapping: it makes no network call, and Sekyro AI never sees,
267
281
  * receives or stores any registry key, only the record and photo you pass.
268
282
  *
269
283
  * ```ts
270
284
  * const answer = await myRegistryClient.lookup(number); // your call, your key
271
285
  * await sekyro.sessions.create({
272
- * subject: { externalRef, ...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
286
+ * person: { externalRef, ...personFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
273
287
  * });
274
288
  * ```
275
289
  *
@@ -282,6 +296,13 @@ type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate"
282
296
  * `options.nationality`; the message never carries the value).
283
297
  * @public
284
298
  */
299
+ declare function personFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: PersonFromRegistryOptions): PersonRecord;
300
+ /**
301
+ * The former name of {@link personFromNationalRegistry}: the same mapping.
302
+ * @deprecated Use {@link personFromNationalRegistry}, the same mapping under the
303
+ * `person` name (spread the result into `person`, not `subject`).
304
+ * @public
305
+ */
285
306
  declare function subjectFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: SubjectFromRegistryOptions): SubjectRecord;
286
307
 
287
308
  /**
@@ -456,4 +477,4 @@ interface VerifiedResult {
456
477
  */
457
478
  declare function verifyResultToken(token: string, opts: VerifyResultTokenOptions): Promise<VerifiedResult>;
458
479
 
459
- export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FailureIdentification, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, type ResultDecision, ResultDuplicate, ResultRisk, ReviewReason, 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 };
480
+ export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FailureIdentification, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, type PersonFromRegistryOptions, type PersonRecord, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, type ResultDecision, ResultDuplicate, ResultRisk, ReviewReason, 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, SessionPersonInput, type SubjectFromRegistryOptions, type SubjectRecord, SubjectReuseMode, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, personFromNationalRegistry, signatureFromHeaders, subjectFromNationalRegistry, verifyResultToken, verifyWebhook };