@sekyro/node 0.1.0-rc.12 → 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.
- package/CHANGELOG.md +9 -0
- package/README.md +27 -22
- package/dist/{chunk-SZQEL3LK.js → chunk-IM3UCVDB.js} +1 -1
- package/dist/chunk-J6U2QY7M.js +1 -0
- package/dist/{client-edr9f2Ec.d.cts → client-C2VDmckH.d.cts} +166 -11
- package/dist/{client-edr9f2Ec.d.ts → client-C2VDmckH.d.ts} +166 -11
- package/dist/connect/express/index.cjs +1 -1
- package/dist/connect/express/index.d.cts +2 -2
- package/dist/connect/express/index.d.ts +2 -2
- package/dist/connect/express/index.js +1 -1
- package/dist/connect/index.cjs +1 -1
- package/dist/connect/index.d.cts +2 -2
- package/dist/connect/index.d.ts +2 -2
- package/dist/connect/index.js +1 -1
- package/dist/connect/next/index.cjs +1 -1
- package/dist/connect/next/index.d.cts +2 -2
- package/dist/connect/next/index.d.ts +2 -2
- package/dist/connect/next/index.js +1 -1
- package/dist/{connector-DKP_ebGH.d.ts → connector-80bgRkSI.d.cts} +39 -6
- package/dist/{connector-C0M4NWwZ.d.cts → connector-BV3zVPrh.d.ts} +39 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
- package/dist/chunk-D53NUEJ6.js +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-
|
|
1
|
+
import { A as AgeMethod, W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-C2VDmckH.cjs';
|
|
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
|
|
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,
|
|
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.
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-
|
|
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
|
|
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,
|
|
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.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.12";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 delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&("personId"in target||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/sessions")}else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.subjects=this.people,Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}var import_node_crypto=require("crypto");var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=(0,import_node_crypto.createHmac)("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&(0,import_node_crypto.timingSafeEqual)(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}var import_jose=require("jose");var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return(0,import_jose.createLocalJWKSet)(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof import_jose.errors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof import_jose.errors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.person_id??d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await(0,import_jose.jwtVerify)(token,keys,verifyOpts)}catch(err){if(!(err instanceof import_jose.errors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await(0,import_jose.jwtVerify)(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}0&&(module.exports={DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook});
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{DEFAULT_BASE_URL:()=>DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER:()=>DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS:()=>DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER:()=>LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH:()=>RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER:()=>SEKYRO_SIGNATURE_HEADER,Sekyro:()=>Sekyro,SekyroApiError:()=>SekyroApiError,SekyroConfigError:()=>SekyroConfigError,SekyroResultTokenError:()=>SekyroResultTokenError,SekyroWebhookError:()=>SekyroWebhookError,isFlowError:()=>isFlowError,personFromNationalRegistry:()=>personFromNationalRegistry,signatureFromHeaders:()=>signatureFromHeaders,subjectFromNationalRegistry:()=>subjectFromNationalRegistry,verifyResultToken:()=>verifyResultToken,verifyWebhook:()=>verifyWebhook});module.exports=__toCommonJS(src_exports);var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.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 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-
|
|
2
|
-
export { m as AgeResult, n as
|
|
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";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as ServiceId, b as SessionPersonInput, c as WebhookEnvelope, R as ReviewReason, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, i as ResultRisk, j as ResultCheckProofs, k as ResultDuplicate, A as AgeMethod, l as FailureIdentification, F as FetchLike } from './client-
|
|
2
|
-
export { m as AgeResult, n as
|
|
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";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.12";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 delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&("personId"in target||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/sessions")}else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.subjects=this.people,Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.person_id??d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
|
|
1
|
+
var WEBHOOK_MESSAGES={invalid_signature:"No v1 signature in the header matches this body and secret",stale:"Delivery timestamp is outside the tolerance window",malformed:"Signature header or body is not in the expected format"},SekyroWebhookError=class extends Error{name="SekyroWebhookError";code;constructor(code,message=WEBHOOK_MESSAGES[code]){super(message),this.code=code}},RESULT_TOKEN_MESSAGES={invalid_token:"The result token is not a valid Sekyro AI token",expired:"The result token has expired",wrong_audience:"The result token was issued for another app",wrong_issuer:"The result token was not issued by the expected issuer",wrong_env:"The result token is for another environment",key_env_mismatch:"The result token environment does not match its signing key",jwks_unavailable:"The Sekyro AI public key set could not be fetched",invalid_options:"Invalid options for verifyResultToken"},SekyroResultTokenError=class extends Error{name="SekyroResultTokenError";code;constructor(code,message=RESULT_TOKEN_MESSAGES[code],cause){super(message,cause===void 0?void 0:{cause}),this.code=code}},CONFIG_MESSAGES={missing_api_key:"Sekyro AI: `apiKey` is required",invalid_base_url:"Sekyro AI: `baseUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])",invalid_registry_record:"Sekyro AI: the registry answer can't be used as a registry record",registry_country_unsupported:"Sekyro AI: no national registry format for this country",registry_nationality_unmapped:"Sekyro AI: the registry answer has a nationality the SDK cannot map"},SekyroConfigError=class extends TypeError{name="SekyroConfigError";code;constructor(code,message=CONFIG_MESSAGES[code]){super(message),this.code=code}},SekyroApiError=class extends Error{name="SekyroApiError";status;code;requestId;details;retryable;retryAfterSeconds;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause}),this.status=init.status,this.code=init.code,this.requestId=init.requestId,this.details=init.details,this.retryable=isRetryable(init.status,init.code),this.retryAfterSeconds=init.retryAfterSeconds}};function retryAfterSecondsOf(header,now=Date.now()){if(header===null)return;let value=header.trim();if(/^\d+$/.test(value))return Number(value);if(!/[a-z]/i.test(value))return;let at=Date.parse(value);if(!Number.isNaN(at))return Math.max(0,Math.ceil((at-now)/1e3))}var FLOW_ERROR_CODES=new Set(["flow_not_found","flow_not_published","flow_archived","override_invalid","override_widens_flow","reuse_disabled","choice_not_found","choice_locked","choice_option_unavailable"]),FLOW_REF_CODES=new Set(["flow_not_published","flow_archived","reuse_disabled"]),isRecord=x=>typeof x=="object"&&x!==null&&!Array.isArray(x),isStringArray=x=>Array.isArray(x)&&x.every(s=>typeof s=="string");function isIssue(x){return isRecord(x)&&typeof x.code=="string"&&typeof x.message=="string"}function hasFlowDetails(code,details){if(!isRecord(details)||!Array.isArray(details.issues)||!details.issues.every(isIssue))return!1;if(code==="override_widens_flow")return isStringArray(details.fields);if(FLOW_REF_CODES.has(code)){let flow=details.flow;return isRecord(flow)&&typeof flow.id=="string"&&typeof flow.slug=="string"}return!0}function isFlowError(err,...codes){return!(err instanceof SekyroApiError)||!FLOW_ERROR_CODES.has(err.code)||codes.length>0&&!codes.includes(err.code)?!1:hasFlowDetails(err.code,err.details)}function isRetryable(status,code){return code==="network"||code==="timeout"||code==="idempotency_in_progress"||status===429?!0:status>=500&&status<=599}var SDK_VERSION="0.1.0-rc.13";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}function toCreatedSession(wire){let levelTarget=wire.levelTarget??wire.level_target;return{id:wire.id,status:wire.status,clientToken:wire.clientToken??wire.client_token,hostedUrl:wire.hostedUrl??wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...levelTarget!==void 0?{levelTarget}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{},...wire.delivery!==void 0?{delivery:wire.delivery}:{}}}var SUBJECT_ID_RE=/^(?:per_)?[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.success!==!1&&v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function requestIdOf(error){let id=error.requestId??error.request_id;return typeof id=="string"?id:void 0}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async send(method,path,o){let timeoutMs=o.timeoutMs??this.timeoutMs,headers={authorization:`Bearer ${this.apiKey}`,accept:o.accept??"application/json","user-agent":USER_AGENT};o.body!==void 0&&(headers["content-type"]="application/json"),o.idempotencyKey!==void 0&&(headers["x-idempotency-key"]=o.idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};o.body!==void 0&&(init.body=JSON.stringify(o.body));try{return await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}}errorOf(res,parsed){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init2={status:res.status,code:parsed.error.code,message:parsed.error.message},requestId=requestIdOf(parsed.error);return requestId!==void 0&&(init2.requestId=requestId),parsed.error.details!==void 0&&(init2.details=parsed.error.details),retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}let init={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};return retryAfterSeconds!==void 0&&(init.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init)}async envelope(method,path,o){let res=await this.send(method,path,o),text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok)throw this.errorOf(res,parsed);if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){return(await this.envelope(method,path,{body,idempotencyKey,timeoutMs})).data}async page(path){let env=await this.envelope("GET",path,{});if(!Array.isArray(env.data))throw new SekyroApiError({status:200,code:"malformed_response",message:"List response `data` is not an array"});let next=env.meta?.nextCursor;return typeof next=="string"&&next.length>0?{data:env.data,nextCursor:next}:{data:env.data}}async bytes(path){let res=await this.send("GET",path,{accept:"image/*, video/*"});if(!res.ok){let text2=await res.text().catch(()=>""),parsed;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch{parsed=void 0}throw this.errorOf(res,parsed)}return{contentType:res.headers.get("content-type")??"application/octet-stream",bytes:new Uint8Array(await res.arrayBuffer())}}};function assertId(method,id,name="id"){if(typeof id!="string"||id.length===0)throw new TypeError(`${method}: \`${name}\` must be a non-empty string`)}var path1=(prefix,id,rest="")=>`${prefix}/${encodeURIComponent(id)}${rest}`;function isoOf(method,name,v){if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new TypeError(`${method}: \`${name}\` is an invalid Date`);return v.toISOString()}if(typeof v!="string"||v.length===0)throw new TypeError(`${method}: \`${name}\` must be an ISO 8601 string or a Date`);return v}function setPaging(method,qs,q){if(q.limit!==void 0){if(!Number.isInteger(q.limit)||q.limit<1||q.limit>100)throw new TypeError(`${method}: \`limit\` must be an integer from 1 to 100`);qs.set("limit",String(q.limit))}if(q.cursor!==void 0){if(typeof q.cursor!="string"||q.cursor.length===0)throw new TypeError(`${method}: \`cursor\` must be a non-empty string`);qs.set("cursor",q.cursor)}}var withQuery=(path,qs)=>qs.size>0?`${path}?${qs.toString()}`:path;async function*follow(first,read){let cursor=first;for(;;){let page=await read(cursor);if(yield*page.data,page.nextCursor===void 0||page.nextCursor===cursor)return;cursor=page.nextCursor}}var SessionsApi=class{constructor(t){this.t=t}t;async create(input={},opts={}){let wire=await this.t.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){return assertId("sessions.selectMethod",id),this.t.call("POST",path1("/sessions",id,"/method"),{method})}async get(id){return assertId("sessions.get",id),this.t.call("GET",path1("/sessions",id))}async cancel(id,opts={}){return assertId("sessions.cancel",id),this.t.call("POST",path1("/sessions",id,"/cancel"),void 0,opts.idempotencyKey)}async resendLink(id,opts={}){return assertId("sessions.resendLink",id),this.t.call("POST",path1("/sessions",id,"/link/resend"),{},opts.idempotencyKey)}async extendLink(id,input,opts={}){assertId("sessions.extendLink",id);let body;if(input!==null&&typeof input=="object"&&"ttlMinutes"in input&&!("expiresAt"in input)){if(!Number.isInteger(input.ttlMinutes)||input.ttlMinutes<1)throw new TypeError("sessions.extendLink: `ttlMinutes` must be a positive integer");body={ttlMinutes:input.ttlMinutes}}else if(input!==null&&typeof input=="object"&&"expiresAt"in input&&!("ttlMinutes"in input))body={expiresAt:isoOf("sessions.extendLink","expiresAt",input.expiresAt)};else throw new TypeError("sessions.extendLink: pass exactly one of `ttlMinutes` or `expiresAt`");return this.t.call("POST",path1("/sessions",id,"/link/extend"),body,opts.idempotencyKey)}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let m="sessions.list",qs=new URLSearchParams;query.externalRef!==void 0&&(assertId(m,query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),query.status!==void 0&&qs.set("status",query.status),query.flow!==void 0&&(assertId(m,query.flow,"flow"),qs.set("flow",query.flow)),query.createdAfter!==void 0&&qs.set("createdAfter",isoOf(m,"createdAfter",query.createdAfter)),query.createdBefore!==void 0&&qs.set("createdBefore",isoOf(m,"createdBefore",query.createdBefore)),setPaging(m,qs,query);let page=await this.t.page(withQuery("/sessions",qs)),data=page.data.filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async media(id){return assertId("sessions.media",id),this.t.call("GET",path1("/sessions",id,"/media"))}async mediaBytes(id,kind,opts={}){let m="sessions.mediaBytes";if(assertId(m,id),assertId(m,kind,"kind"),opts.attempt!==void 0&&opts.reference!==void 0)throw new TypeError(`${m}: \`attempt\` and \`reference\` cannot be combined`);let qs=new URLSearchParams;if(opts.attempt!==void 0){if(!Number.isInteger(opts.attempt)||opts.attempt<1)throw new TypeError(`${m}: \`attempt\` must be a positive integer`);qs.set("attempt",String(opts.attempt))}if(opts.reference!==void 0){if(opts.reference!=="first")throw new TypeError(`${m}: \`reference\` must be "first"`);qs.set("reference","first")}return this.t.bytes(withQuery(path1("/sessions",id,`/media/${encodeURIComponent(kind)}`),qs))}async portrait(id){return assertId("sessions.portrait",id),this.t.call("GET",`${path1("/sessions",id,"/portrait")}?format=url`)}async resultToken(id){return assertId("sessions.resultToken",id),this.t.call("GET",path1("/sessions",id,"/result-token"))}},PeopleApi=class{constructor(t){this.t=t}t;async get(id){return assertId("people.get",id),this.t.call("GET",path1("/people",id))}async list(query={}){return(await this.listPage(query)).data}async listPage(query={}){let qs=new URLSearchParams;query?.externalRef!==void 0&&(assertId("people.list",query.externalRef,"externalRef"),qs.set("externalRef",query.externalRef)),setPaging("people.list",qs,query??{});let page=await this.t.page(withQuery("/people",qs)),ref=query?.externalRef;if(ref===void 0)return page;let data=page.data.filter(p=>Array.isArray(p?.externalRefs)&&p.externalRefs.includes(ref));return page.nextCursor!==void 0?{data,nextCursor:page.nextCursor}:{data}}iterate(query={}){return follow(query.cursor,cursor=>this.listPage(cursor===void 0?{...query}:{...query,cursor}))}async revoke(id,input={},opts={}){return assertId("people.revoke",id),this.t.call("POST",path1("/people",id,"/revoke"),input,opts.idempotencyKey)}async screen(id,input={},opts={}){return assertId("people.screen",id),this.t.call("POST",path1("/people",id,"/screen"),input,opts.idempotencyKey)}async screenings(id,query={}){return(await this.screeningsPage(id,query)).data}async screeningsPage(id,query={}){let m="people.screenings";if(assertId(m,id),query?.limit!==void 0&&(!Number.isInteger(query.limit)||query.limit<1||query.limit>50))throw new TypeError(`${m}: \`limit\` must be an integer from 1 to 50`);let qs=new URLSearchParams;return setPaging(m,qs,query??{}),this.t.page(withQuery(path1("/people",id,"/screenings"),qs))}iterateScreenings(id,query={}){return follow(query.cursor,cursor=>this.screeningsPage(id,cursor===void 0?{...query}:{...query,cursor}))}async delete(id){return assertId("people.delete",id),this.t.call("DELETE",path1("/people",id))}async createSession(target,input,opts={}){let m="people.createSession",path;if(typeof target=="string")assertId(m,target),path=SUBJECT_ID_RE.test(target)?path1("/people",target,"/sessions"):path1("/people/by-external-ref",target,"/sessions");else if(target!==null&&typeof target=="object"&&("personId"in target||"subjectId"in target)){let id="personId"in target?target.personId:target.subjectId;assertId(m,id),path=path1("/people",id,"/sessions")}else{let ref=target?.externalRef;assertId(m,ref),path=path1("/people/by-external-ref",ref,"/sessions")}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError(`${m}: \`mode\` must be 'recheck' or 'step_up'`);let wire=await this.t.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;people;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport;let bound={call:transport.call.bind(transport),page:transport.page.bind(transport),bytes:transport.bytes.bind(transport)};this.sessions=new SessionsApi(bound),this.people=new PeopleApi(bound),this.subjects=this.people,Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function personFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function subjectFromNationalRegistry(country,response,options){return personFromNationalRegistry(country,response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationalities=[nationality]);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.person_id??d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method});let decision=decisionOf(claim.decision);decision!==void 0&&(out.decision=decision);let fi=failureIdentificationOf(claim.failure_identification);return fi!==void 0&&(out.failureIdentification=fi),out}function isRecord2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function decisionOf(raw){if(!isRecord2(raw))return;let{source,mode,votes}=raw;if(source!=="review"&&source!=="prior_review"||mode!=="single"&&mode!=="dual"||votes!==1&&votes!==2&&votes!==3)return;let out={source,mode,votes,reasons:Array.isArray(raw.reasons)?raw.reasons.filter(r=>typeof r=="string"):[],decidedAt:String(raw.decided_at??"")};typeof raw.agreement=="boolean"&&(out.agreement=raw.agreement);let sessionId=str(raw.session_id);return sessionId!==void 0&&(out.sessionId=sessionId),out}function failureIdentificationOf(raw){if(!isRecord2(raw)||!isRecord2(raw.match))return;let{kind,scope}=raw;if(kind!=="presenter"&&kind!=="shown_face"&&kind!=="other_identity"||scope!=="org"&&scope!=="registry")return;let m=raw.match;if(m.tier!==1&&m.tier!==2&&m.tier!==3||typeof m.score!="number"||m.band!=="strong"&&m.band!=="moderate")return;let match={tier:m.tier,score:m.score,band:m.band},subjectId=str(m.person_id)??str(m.subject_id);subjectId!==void 0&&(match.subjectId=subjectId);let reference=str(m.reference);reference!==void 0&&(match.reference=reference);let photoId=str(m.photo_id);photoId!==void 0&&(match.photoId=photoId);let out={kind,scope,match},source=str(raw.reference_source);return source!==void 0&&(out.referenceSource=source),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,personFromNationalRegistry,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sekyro/node",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.13",
|
|
4
4
|
"description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|