@sekyro/node 0.0.0-stage → 0.1.0-rc.10
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 +127 -0
- package/LICENSE +29 -0
- package/README.md +532 -2
- package/dist/chunk-O5GJ3YJV.js +1 -0
- package/dist/chunk-TAPXGI3Q.js +1 -0
- package/dist/client-Hkxwn6ZA.d.cts +1669 -0
- package/dist/client-Hkxwn6ZA.d.ts +1669 -0
- package/dist/connect/express/index.cjs +1 -0
- package/dist/connect/express/index.d.cts +35 -0
- package/dist/connect/express/index.d.ts +35 -0
- package/dist/connect/express/index.js +1 -0
- package/dist/connect/index.cjs +1 -0
- package/dist/connect/index.d.cts +29 -0
- package/dist/connect/index.d.ts +29 -0
- package/dist/connect/index.js +1 -0
- package/dist/connect/next/index.cjs +1 -0
- package/dist/connect/next/index.d.cts +43 -0
- package/dist/connect/next/index.d.ts +43 -0
- package/dist/connect/next/index.js +1 -0
- package/dist/connector-BInF_yHb.d.ts +425 -0
- package/dist/connector-C4NuetEm.d.cts +425 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +433 -0
- package/dist/index.d.ts +433 -0
- package/dist/index.js +1 -0
- package/package.json +96 -4
- package/sbom.cdx.json +194 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import { a as ServiceId, b as SessionSubjectInput, c as WebhookEnvelope, d as SekyroEnvironment, V as VerificationLevel, e as VerificationAssurance, f as SessionOutcome, g as VerificationUnit, h as SubjectReuseMode, R as ResultRisk, i as ResultCheckProofs, j as ResultDuplicate, A as AgeMethod, F as FetchLike } from './client-Hkxwn6ZA.js';
|
|
2
|
+
export { k as AgeResult, l as CameraUnavailableCause, m as CheckState, n as CheckType, o as ConnectorIdentity, p as CreateSessionInput, C as CreatedSession, q as CreatedSessionWarning, D as DEFAULT_BASE_URL, r as DEFAULT_TIMEOUT_MS, s as DecisionReason, t as DeepPartial, u as DeletedSubject, v as DeliverOptions, w as DocumentSubstitutionSettings, E as EidResult, x as EligibilityReason, y as FlowOverridableSettings, z as FlowOverrides, B as FlowServiceSettings, G as FlowSummary, I as IdNumberReason, H as IdentityMethod, J as LevelTarget, K as ListSessionsQuery, L as Locale, M as MatchReason, P as PolicyFailureReason, N as PortraitReportEntry, O as ProbeBindingReason, Q as ProbeQuality, T as ProfileDocumentType, U as RequestOptions, X as ResultTokenResponse, Y as RevokeSubjectInput, S as Sekyro, Z as SekyroOptions, _ as Session, $ as SessionDevice, a0 as SessionDeviceSignal, a1 as SessionEventData, a2 as SessionFailureReason, a3 as SessionFlowRef, a4 as SessionLifecycleEventData, a5 as SessionLinkInput, a6 as SessionNetwork, a7 as SessionNetworkEvent, a8 as SessionPortraitLink, a9 as SessionReviewDecidedEventData, aa as SessionStatus, ab as SessionStep, ac as SessionStepCompletedEventData, ad as SessionsApi, ae as Subject, af as SubjectAssurance, ag as SubjectDeletedEventData, ah as SubjectEnrolledEventData, ai as SubjectIdNumber, aj as SubjectName, ak as SubjectReferenceSource, al as SubjectReuseDocument, am as SubjectReuseTarget, an as SubjectSession, ao as SubjectSessionInput, ap as SubjectSessionTarget, aq as SubjectStatus, ar as SubjectSuspiciousActivityEventData, as as SubjectUpdatedEventData, at as SubjectsApi, au as SuppliedIdentityRecord, av as UsageThresholdReachedEventData, aw as VerifiedContacts, ax as WebhookEnvelopeOf, ay as WebhookEventDataMap, W as WebhookEventType } from './client-Hkxwn6ZA.js';
|
|
3
|
+
|
|
4
|
+
/** Why {@link verifyWebhook} rejected a delivery. @public */
|
|
5
|
+
type SekyroWebhookErrorCode = "invalid_signature" | "stale" | "malformed";
|
|
6
|
+
/**
|
|
7
|
+
* Thrown by {@link verifyWebhook}. Respond with a 4xx and do not process the
|
|
8
|
+
* body; Sekyro AI retries deliveries that do not receive a 2xx.
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
declare class SekyroWebhookError extends Error {
|
|
12
|
+
readonly name = "SekyroWebhookError";
|
|
13
|
+
readonly code: SekyroWebhookErrorCode;
|
|
14
|
+
constructor(code: SekyroWebhookErrorCode, message?: string);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Why {@link verifyResultToken} rejected a result token:
|
|
18
|
+
* - `invalid_token`: not a JWT, a bad signature, an unknown key, or no `sekyro` claim;
|
|
19
|
+
* - `expired`: past its `exp` (tokens live 10 minutes; fetch a fresh one with
|
|
20
|
+
* {@link SessionsApi.resultToken});
|
|
21
|
+
* - `wrong_audience`: issued for another app;
|
|
22
|
+
* - `wrong_issuer`: not issued by the expected issuer;
|
|
23
|
+
* - `wrong_env`: a sandbox token when you asked for live, or the reverse;
|
|
24
|
+
* - `key_env_mismatch`: the environment claim does not match the key that signed it;
|
|
25
|
+
* - `jwks_unavailable`: the public key set could not be fetched;
|
|
26
|
+
* - `invalid_options`: a missing `appId` or an unsafe `jwksUrl`.
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
type SekyroResultTokenErrorCode = "invalid_token" | "expired" | "wrong_audience" | "wrong_issuer" | "wrong_env" | "key_env_mismatch" | "jwks_unavailable" | "invalid_options";
|
|
30
|
+
/**
|
|
31
|
+
* Thrown by {@link verifyResultToken}. Do not use the token's content.
|
|
32
|
+
* @public
|
|
33
|
+
*/
|
|
34
|
+
declare class SekyroResultTokenError extends Error {
|
|
35
|
+
readonly name = "SekyroResultTokenError";
|
|
36
|
+
readonly code: SekyroResultTokenErrorCode;
|
|
37
|
+
constructor(code: SekyroResultTokenErrorCode, message?: string, cause?: unknown);
|
|
38
|
+
}
|
|
39
|
+
/** Why the {@link Sekyro} constructor rejected its options. @public */
|
|
40
|
+
type SekyroConfigErrorCode = "missing_api_key" | "invalid_base_url" | "invalid_registry_record" | "registry_country_unsupported" | "registry_nationality_unmapped";
|
|
41
|
+
/**
|
|
42
|
+
* Thrown synchronously by `new Sekyro(...)` for an unusable configuration, and by
|
|
43
|
+
* {@link subjectFromNationalRegistry} for an unusable registry answer:
|
|
44
|
+
* before any request is made. Extends `TypeError` so existing
|
|
45
|
+
* `instanceof TypeError` guards keep working.
|
|
46
|
+
* @public
|
|
47
|
+
*/
|
|
48
|
+
declare class SekyroConfigError extends TypeError {
|
|
49
|
+
readonly name = "SekyroConfigError";
|
|
50
|
+
readonly code: SekyroConfigErrorCode;
|
|
51
|
+
constructor(code: SekyroConfigErrorCode, message?: string);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The flow codes of the partner API (Sekyro flows). Each carries
|
|
55
|
+
* {@link SekyroApiError.details} (see {@link SekyroFlowErrorDetailsMap} and
|
|
56
|
+
* {@link isFlowError}). On `sessions.create`:
|
|
57
|
+
* - `flow_not_found` (404): no flow with this slug or `flw_` id in the key's app;
|
|
58
|
+
* - `flow_not_published` (409): the flow has no published version yet;
|
|
59
|
+
* - `flow_archived` (409): the flow is archived;
|
|
60
|
+
* - `override_invalid` (400): an unknown key or value in `overrides`, or a
|
|
61
|
+
* result that is not a valid flow;
|
|
62
|
+
* - `override_widens_flow` (403): the override makes the flow less strict
|
|
63
|
+
* (e.g. a service turned `'off'`) and the flow does not allow widening;
|
|
64
|
+
* - `reuse_disabled` (409): `subject.reuse` on a flow whose returning-user
|
|
65
|
+
* sessions are turned off.
|
|
66
|
+
*
|
|
67
|
+
* On `sessions.selectMethod` (a flow session's identity-method choice):
|
|
68
|
+
* `choice_not_found` (409: the session's flow has no identity-method choice),
|
|
69
|
+
* `choice_locked` (409: it can no longer change) and
|
|
70
|
+
* `choice_option_unavailable` (409: that method is not offered).
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
type SekyroFlowErrorCode = "flow_not_found" | "flow_not_published" | "flow_archived" | "override_invalid" | "override_widens_flow" | "reuse_disabled" | "choice_not_found" | "choice_locked" | "choice_option_unavailable";
|
|
74
|
+
/**
|
|
75
|
+
* One machine-readable issue of a flow error. Never carries a value you sent.
|
|
76
|
+
* @public
|
|
77
|
+
*/
|
|
78
|
+
interface FlowErrorIssue {
|
|
79
|
+
/**
|
|
80
|
+
* A flow validation code (e.g. `face_match_needs_liveness`), `schema_invalid`,
|
|
81
|
+
* `schema_unknown_field`, `field_widens_flow`, or the error's own code.
|
|
82
|
+
*/
|
|
83
|
+
code: string;
|
|
84
|
+
/** A short plain English sentence. */
|
|
85
|
+
message: string;
|
|
86
|
+
/** The field of your request body, e.g. `overrides.services.liveness.attempts`, `flow`, `subject.reuse`. */
|
|
87
|
+
path?: string;
|
|
88
|
+
/** A node of your app's flow. */
|
|
89
|
+
nodeId?: string;
|
|
90
|
+
/** The service of that node (or of the `overrides.services` key). */
|
|
91
|
+
service?: ServiceId;
|
|
92
|
+
/** `override_widens_flow`: the widened field, e.g. `settings.eligibility.minAge`, `services.nfc`. */
|
|
93
|
+
field?: string;
|
|
94
|
+
}
|
|
95
|
+
/** `details` common to every flow error: at least one issue. @public */
|
|
96
|
+
interface FlowErrorDetails {
|
|
97
|
+
issues: FlowErrorIssue[];
|
|
98
|
+
}
|
|
99
|
+
/** `details` of `override_widens_flow`: the widened fields, plus one `field_widens_flow` issue each. @public */
|
|
100
|
+
interface FlowWidensErrorDetails extends FlowErrorDetails {
|
|
101
|
+
fields: string[];
|
|
102
|
+
}
|
|
103
|
+
/** `details` of `flow_not_published`, `flow_archived` and `reuse_disabled`: the flow concerned. @public */
|
|
104
|
+
interface FlowRefErrorDetails extends FlowErrorDetails {
|
|
105
|
+
flow: {
|
|
106
|
+
id: string;
|
|
107
|
+
slug: string;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* {@link SekyroFlowErrorCode} → the shape of its {@link SekyroApiError.details}.
|
|
112
|
+
* @public
|
|
113
|
+
*/
|
|
114
|
+
interface SekyroFlowErrorDetailsMap {
|
|
115
|
+
flow_not_found: FlowErrorDetails;
|
|
116
|
+
flow_not_published: FlowRefErrorDetails;
|
|
117
|
+
flow_archived: FlowRefErrorDetails;
|
|
118
|
+
override_invalid: FlowErrorDetails;
|
|
119
|
+
override_widens_flow: FlowWidensErrorDetails;
|
|
120
|
+
reuse_disabled: FlowRefErrorDetails;
|
|
121
|
+
choice_not_found: FlowErrorDetails;
|
|
122
|
+
choice_locked: FlowErrorDetails;
|
|
123
|
+
choice_option_unavailable: FlowErrorDetails;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* A {@link SekyroApiError} narrowed by {@link isFlowError}: `code` is a flow
|
|
127
|
+
* code and `details` has that code's shape.
|
|
128
|
+
* @public
|
|
129
|
+
*/
|
|
130
|
+
type SekyroFlowError<C extends SekyroFlowErrorCode = SekyroFlowErrorCode> = C extends SekyroFlowErrorCode ? SekyroApiError & {
|
|
131
|
+
readonly code: C;
|
|
132
|
+
readonly details: SekyroFlowErrorDetailsMap[C];
|
|
133
|
+
} : never;
|
|
134
|
+
/**
|
|
135
|
+
* {@link SekyroApiError.code}: an SDK code, a documented flow code, or any
|
|
136
|
+
* other API code (the union stays open so a new API code never breaks a build).
|
|
137
|
+
* @public
|
|
138
|
+
*/
|
|
139
|
+
type SekyroApiErrorCode = SekyroClientErrorCode | SekyroFlowErrorCode | (string & {});
|
|
140
|
+
/** Constructor input of {@link SekyroApiError}. @public */
|
|
141
|
+
interface SekyroApiErrorInit {
|
|
142
|
+
/** HTTP status; `0` when no response was received (network / timeout). */
|
|
143
|
+
status: number;
|
|
144
|
+
/** API error code, or `network` | `timeout` | `http_error` | `malformed_response`. */
|
|
145
|
+
code: SekyroApiErrorCode;
|
|
146
|
+
message: string;
|
|
147
|
+
/** The API's `request_id`, when the response carried one. */
|
|
148
|
+
requestId?: string;
|
|
149
|
+
/** The API's `error.details`, when the response carried them (the flow codes: {@link SekyroFlowErrorDetailsMap}). */
|
|
150
|
+
details?: unknown;
|
|
151
|
+
/** Underlying error (network failures, abort reasons, JSON parse errors). */
|
|
152
|
+
cause?: unknown;
|
|
153
|
+
/** Seconds to wait before retrying, from the response's `Retry-After` header. */
|
|
154
|
+
retryAfterSeconds?: number;
|
|
155
|
+
}
|
|
156
|
+
/** Error codes the SDK itself produces (as opposed to codes from the API). @public */
|
|
157
|
+
type SekyroClientErrorCode = "network" | "timeout" | "http_error" | "malformed_response";
|
|
158
|
+
/**
|
|
159
|
+
* Any failed call through {@link Sekyro}: a non-2xx partner envelope
|
|
160
|
+
* `{ status: 'error', error: { code, message, request_id } }`, a non-JSON
|
|
161
|
+
* response, a network failure or a timeout.
|
|
162
|
+
*
|
|
163
|
+
* `retryable` is `true` for `network`, `timeout`, HTTP 429, HTTP 5xx and the
|
|
164
|
+
* `idempotency_in_progress` code — retry with the SAME idempotency key.
|
|
165
|
+
* @public
|
|
166
|
+
*/
|
|
167
|
+
declare class SekyroApiError extends Error {
|
|
168
|
+
readonly name = "SekyroApiError";
|
|
169
|
+
readonly status: number;
|
|
170
|
+
readonly code: SekyroApiErrorCode;
|
|
171
|
+
readonly requestId: string | undefined;
|
|
172
|
+
/**
|
|
173
|
+
* The API's `error.details`, when the response carried them; `undefined`
|
|
174
|
+
* otherwise. Untyped here: narrow with {@link isFlowError} to read a flow
|
|
175
|
+
* code's documented shape ({@link SekyroFlowErrorDetailsMap}).
|
|
176
|
+
*/
|
|
177
|
+
readonly details: unknown;
|
|
178
|
+
readonly retryable: boolean;
|
|
179
|
+
/**
|
|
180
|
+
* Seconds to wait before retrying, from the response's `Retry-After` header
|
|
181
|
+
* (a number of seconds, or an HTTP date rounded up to whole seconds from now).
|
|
182
|
+
* `undefined` when the response had no usable header.
|
|
183
|
+
*/
|
|
184
|
+
readonly retryAfterSeconds: number | undefined;
|
|
185
|
+
constructor(init: SekyroApiErrorInit);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Narrow an error to a flow error, optionally to given codes: `true` only for
|
|
189
|
+
* a {@link SekyroApiError} with a flow code whose `details` have that code's
|
|
190
|
+
* documented shape, so `err.details` is typed after the check. An error whose
|
|
191
|
+
* `details` are missing or unexpected is not narrowed (read `err.code`).
|
|
192
|
+
*
|
|
193
|
+
* @example
|
|
194
|
+
* ```ts
|
|
195
|
+
* try {
|
|
196
|
+
* await sekyro.sessions.create({ flow, overrides });
|
|
197
|
+
* } catch (err) {
|
|
198
|
+
* if (isFlowError(err, "override_widens_flow")) err.details.fields; // string[]
|
|
199
|
+
* else if (isFlowError(err)) err.details.issues.map((i) => i.path);
|
|
200
|
+
* }
|
|
201
|
+
* ```
|
|
202
|
+
* @public
|
|
203
|
+
*/
|
|
204
|
+
declare function isFlowError<C extends SekyroFlowErrorCode = SekyroFlowErrorCode>(err: unknown, ...codes: C[]): err is SekyroFlowError<C>;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The raw ANRPTS `getPersonne` answer your server received with your own
|
|
208
|
+
* access: `{ personne, photo }`, where `photo` is a base64 JPEG (optionally
|
|
209
|
+
* data-URL prefixed). Only the fields the mapping reads are typed.
|
|
210
|
+
* @public
|
|
211
|
+
*/
|
|
212
|
+
interface AnrptsPersonneResponse {
|
|
213
|
+
personne?: {
|
|
214
|
+
nni?: string | undefined;
|
|
215
|
+
prenomFr?: string | undefined;
|
|
216
|
+
patronymeFr?: string | undefined;
|
|
217
|
+
perePrenomFr?: string | undefined;
|
|
218
|
+
prenomAr?: string | undefined;
|
|
219
|
+
patronymeAr?: string | undefined;
|
|
220
|
+
perePrenomAr?: string | undefined;
|
|
221
|
+
/** ISO date or date-time (`1990-01-01T00:00:00.000Z`), or `DD/MM/YYYY`. */
|
|
222
|
+
dateNaissance?: string | undefined;
|
|
223
|
+
lieuNaissanceFr?: string | undefined;
|
|
224
|
+
lieuNaissanceAr?: string | undefined;
|
|
225
|
+
sexeCode?: string | undefined;
|
|
226
|
+
nationalities?: string[] | undefined;
|
|
227
|
+
[key: string]: unknown;
|
|
228
|
+
};
|
|
229
|
+
photo?: string | undefined;
|
|
230
|
+
datePhoto?: string | undefined;
|
|
231
|
+
[key: string]: unknown;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Registry answer formats Sekyro AI can map, by ISO 3166-1 alpha-2 country.
|
|
235
|
+
* @public
|
|
236
|
+
*/
|
|
237
|
+
interface NationalRegistryResponses {
|
|
238
|
+
/** Mauritania: the ANRPTS `getPersonne` answer `{ personne, photo, datePhoto? }`. */
|
|
239
|
+
MR: AnrptsPersonneResponse;
|
|
240
|
+
}
|
|
241
|
+
/** A country {@link subjectFromNationalRegistry} can map. @public */
|
|
242
|
+
type NationalRegistryCountry = keyof NationalRegistryResponses;
|
|
243
|
+
/** Options of {@link subjectFromNationalRegistry}. @public */
|
|
244
|
+
interface SubjectFromRegistryOptions {
|
|
245
|
+
/**
|
|
246
|
+
* When YOUR system received this answer (not "now" when you map a cached
|
|
247
|
+
* answer). Required: records older than 24 h are refused at session create.
|
|
248
|
+
*/
|
|
249
|
+
fetchedAt: Date | string;
|
|
250
|
+
/**
|
|
251
|
+
* The person's nationality (ISO 3166-1 alpha-2) when you map the registry's
|
|
252
|
+
* nationality text yourself; it replaces the SDK's mapping. Needed when the answer
|
|
253
|
+
* states a nationality the SDK cannot map (`registry_nationality_unmapped`).
|
|
254
|
+
*/
|
|
255
|
+
nationality?: string;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The `subject` keys of a reference record, ready to spread into
|
|
259
|
+
* `sessions.create({ subject })`.
|
|
260
|
+
* @public
|
|
261
|
+
*/
|
|
262
|
+
type SubjectRecord = Required<Pick<SessionSubjectInput, "idNumber" | "birthDate" | "photo" | "fetchedAt">> & Pick<SessionSubjectInput, "fullName" | "names" | "birthPlace" | "sex" | "nationality" | "photoDate">;
|
|
263
|
+
/**
|
|
264
|
+
* Convert a national registry answer that YOUR server already received, with
|
|
265
|
+
* your own access, into the `subject` reference keys of `sessions.create`. A
|
|
266
|
+
* pure, local mapping: it makes no network call, and Sekyro AI never sees,
|
|
267
|
+
* receives or stores any registry key, only the record and photo you pass.
|
|
268
|
+
*
|
|
269
|
+
* ```ts
|
|
270
|
+
* const answer = await myRegistryClient.lookup(number); // your call, your key
|
|
271
|
+
* await sekyro.sessions.create({
|
|
272
|
+
* subject: { externalRef, ...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }) },
|
|
273
|
+
* });
|
|
274
|
+
* ```
|
|
275
|
+
*
|
|
276
|
+
* Throws {@link SekyroConfigError}: `invalid_registry_record` when a required
|
|
277
|
+
* field (the number, a given and family name in at least one script, the birth
|
|
278
|
+
* date, the photo) is missing or `fetchedAt` is not a date (the message names
|
|
279
|
+
* the field, never its value); `registry_country_unsupported` for a country
|
|
280
|
+
* without an adapter; `registry_nationality_unmapped` when the answer states a
|
|
281
|
+
* nationality and none of its values maps to an ISO code (map it yourself and pass
|
|
282
|
+
* `options.nationality`; the message never carries the value).
|
|
283
|
+
* @public
|
|
284
|
+
*/
|
|
285
|
+
declare function subjectFromNationalRegistry<C extends NationalRegistryCountry>(country: C, response: NationalRegistryResponses[C], options: SubjectFromRegistryOptions): SubjectRecord;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The HTTP header carrying the webhook signature:
|
|
289
|
+
* `t=<unix seconds>,v1=<hex>[,v1=<hex>]`.
|
|
290
|
+
* @public
|
|
291
|
+
*/
|
|
292
|
+
declare const SEKYRO_SIGNATURE_HEADER = "x-sekyro-signature";
|
|
293
|
+
/**
|
|
294
|
+
* The pre-rebrand name of the signature header. Sekyro AI sends BOTH headers with
|
|
295
|
+
* the same value during the transition; prefer {@link SEKYRO_SIGNATURE_HEADER}
|
|
296
|
+
* and use {@link signatureFromHeaders} to accept either.
|
|
297
|
+
* @public
|
|
298
|
+
*/
|
|
299
|
+
declare const LEGACY_SIGNATURE_HEADER = "x-ibtikar-signature";
|
|
300
|
+
/**
|
|
301
|
+
* Pick the signature header out of an incoming request's headers: the
|
|
302
|
+
* `x-sekyro-signature` value when present, else the legacy
|
|
303
|
+
* `x-ibtikar-signature`, else `undefined`. Accepts a Fetch `Headers` object or
|
|
304
|
+
* a Node-style plain record (lower- or mixed-case keys; a multi-valued header
|
|
305
|
+
* yields its first value).
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* ```ts
|
|
309
|
+
* verifyWebhook(rawBody, signatureFromHeaders(req.headers), secret);
|
|
310
|
+
* ```
|
|
311
|
+
* @public
|
|
312
|
+
*/
|
|
313
|
+
declare function signatureFromHeaders(headers: Headers | Record<string, string | string[] | undefined>): string | undefined;
|
|
314
|
+
/** Options of {@link verifyWebhook}. @public */
|
|
315
|
+
interface VerifyWebhookOptions {
|
|
316
|
+
/** Max |now − t| in seconds before a delivery is rejected as `stale`. Default 300. */
|
|
317
|
+
toleranceSec?: number;
|
|
318
|
+
/** Clock returning epoch milliseconds. Default `Date.now`. */
|
|
319
|
+
now?: () => number;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Verify a Sekyro AI webhook delivery and return its parsed envelope, discriminated
|
|
323
|
+
* on `event` (narrow with a `switch` to type `data`).
|
|
324
|
+
*
|
|
325
|
+
* - `rawBody` MUST be the request body exactly as received (before any JSON
|
|
326
|
+
* parsing / re-serialisation); the signature covers those bytes.
|
|
327
|
+
* - Accepts the delivery when ANY `v1` in the header matches, which is what
|
|
328
|
+
* makes secret rotation seamless (Sekyro AI signs with current + previous).
|
|
329
|
+
* - Uses `node:crypto` only; the digest compare is constant-time.
|
|
330
|
+
*
|
|
331
|
+
* Checks run in this order: header/secret present → header well-formed →
|
|
332
|
+
* timestamp within tolerance → signature → body is a JSON object.
|
|
333
|
+
*
|
|
334
|
+
* @param rawBody - The raw UTF-8 request body.
|
|
335
|
+
* @param header - The `x-sekyro-signature` header value (or the legacy
|
|
336
|
+
* `x-ibtikar-signature` — same format; see {@link signatureFromHeaders}).
|
|
337
|
+
* @param secret - The endpoint secret you hold (current or previous).
|
|
338
|
+
* @throws {@link SekyroWebhookError} with `code` `invalid_signature` | `stale` | `malformed`.
|
|
339
|
+
* @public
|
|
340
|
+
*/
|
|
341
|
+
declare function verifyWebhook(rawBody: string, header: string | null | undefined, secret: string, opts?: VerifyWebhookOptions): WebhookEnvelope;
|
|
342
|
+
|
|
343
|
+
/** Issuer of production result tokens. @public */
|
|
344
|
+
declare const DEFAULT_RESULT_TOKEN_ISSUER = "https://api.sekyro.ai";
|
|
345
|
+
/** Path of the public key set under the issuer origin. @public */
|
|
346
|
+
declare const RESULT_TOKEN_JWKS_PATH = "/.well-known/sekyro/jwks.json";
|
|
347
|
+
/** Options of {@link verifyResultToken}. @public */
|
|
348
|
+
interface VerifyResultTokenOptions {
|
|
349
|
+
/**
|
|
350
|
+
* Your app id, or every app id this server accepts. The token's `aud` must
|
|
351
|
+
* be one of them; {@link VerifiedResult.appId} says which.
|
|
352
|
+
*/
|
|
353
|
+
appId: string | string[];
|
|
354
|
+
/** Expected `iss`. Default {@link DEFAULT_RESULT_TOKEN_ISSUER}. */
|
|
355
|
+
issuer?: string;
|
|
356
|
+
/** Key set URL. Default `${issuer}/.well-known/sekyro/jwks.json`. Must be `https:` (plain `http:` only on a loopback host). */
|
|
357
|
+
jwksUrl?: string;
|
|
358
|
+
/**
|
|
359
|
+
* The environment you accept. A sandbox token is refused when you ask for
|
|
360
|
+
* `live`, and the reverse. Omit to accept both and read {@link VerifiedResult.env}.
|
|
361
|
+
*/
|
|
362
|
+
env?: SekyroEnvironment;
|
|
363
|
+
/** Custom `fetch` for the key set (tests, proxies). Default `globalThis.fetch`. */
|
|
364
|
+
fetch?: FetchLike;
|
|
365
|
+
/** Clock returning epoch milliseconds. Default `Date.now`. */
|
|
366
|
+
now?: () => number;
|
|
367
|
+
/** Allowed clock skew in seconds for `exp` / `iat`. Default 30. */
|
|
368
|
+
clockToleranceSec?: number;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The verified content of a result token, in camelCase.
|
|
372
|
+
* @public
|
|
373
|
+
*/
|
|
374
|
+
interface VerifiedResult {
|
|
375
|
+
sessionId: string;
|
|
376
|
+
orgId: string;
|
|
377
|
+
/** The app id the token was issued for (its `aud`), one of {@link VerifyResultTokenOptions.appId}. */
|
|
378
|
+
appId: string;
|
|
379
|
+
/** The subject (person) the session is linked to (`sub`), once that subject has passed a verification (absent before that). */
|
|
380
|
+
subjectId?: string;
|
|
381
|
+
/** Your own id for the person, from `subject.externalRef` at create. */
|
|
382
|
+
externalRef?: string;
|
|
383
|
+
env: SekyroEnvironment;
|
|
384
|
+
level: VerificationLevel | null;
|
|
385
|
+
assurance: VerificationAssurance | null;
|
|
386
|
+
outcome: SessionOutcome | null;
|
|
387
|
+
unit: VerificationUnit | null;
|
|
388
|
+
/** ISO 8601: when the session reached its terminal state. */
|
|
389
|
+
verifiedAt: string;
|
|
390
|
+
/** The flow version the session ran. */
|
|
391
|
+
flow?: {
|
|
392
|
+
slug: string;
|
|
393
|
+
version: number;
|
|
394
|
+
};
|
|
395
|
+
/** `recheck` or `step_up` on a session created for an existing subject; absent otherwise. */
|
|
396
|
+
reuseMode?: SubjectReuseMode;
|
|
397
|
+
risk?: ResultRisk;
|
|
398
|
+
checks?: ResultCheckProofs;
|
|
399
|
+
duplicates?: ResultDuplicate[];
|
|
400
|
+
/**
|
|
401
|
+
* The `sekyro.age` claim, when the flow sets a minimum age and the session
|
|
402
|
+
* proved it: `over` is the flow's minimum age, `method` how it was proved.
|
|
403
|
+
* The token never carries the estimated age.
|
|
404
|
+
*/
|
|
405
|
+
age?: {
|
|
406
|
+
over: number;
|
|
407
|
+
method: AgeMethod;
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Verify a Sekyro AI result token (the `resultToken` of a terminal webhook,
|
|
412
|
+
* or {@link SessionsApi.resultToken}) and return its content.
|
|
413
|
+
*
|
|
414
|
+
* Checks the ES256 signature against the public key set (fetched from
|
|
415
|
+
* `${issuer}/.well-known/sekyro/jwks.json` and cached for 10 minutes; an
|
|
416
|
+
* unknown key id fetches it again), the issuer, the audience (your app id),
|
|
417
|
+
* the expiry, and that the environment claim matches the key that signed it
|
|
418
|
+
* (sandbox keys have ids starting `sbx-`). Throws
|
|
419
|
+
* {@link SekyroResultTokenError} otherwise; never trust the token's content
|
|
420
|
+
* before this resolves.
|
|
421
|
+
*
|
|
422
|
+
* @example
|
|
423
|
+
* ```ts
|
|
424
|
+
* const result = await verifyResultToken(token, { appId: process.env.SEKYRO_APP_ID!, env: "live" });
|
|
425
|
+
* if (result.outcome === "approved" && (result.level ?? 0) >= 1) {
|
|
426
|
+
* // a verified real person
|
|
427
|
+
* }
|
|
428
|
+
* ```
|
|
429
|
+
* @public
|
|
430
|
+
*/
|
|
431
|
+
declare function verifyResultToken(token: string, opts: VerifyResultTokenOptions): Promise<VerifiedResult>;
|
|
432
|
+
|
|
433
|
+
export { AgeMethod, type AnrptsPersonneResponse, DEFAULT_RESULT_TOKEN_ISSUER, FetchLike, type FlowErrorDetails, type FlowErrorIssue, type FlowRefErrorDetails, type FlowWidensErrorDetails, LEGACY_SIGNATURE_HEADER, type NationalRegistryCountry, type NationalRegistryResponses, RESULT_TOKEN_JWKS_PATH, ResultCheckProofs, ResultDuplicate, ResultRisk, SEKYRO_SIGNATURE_HEADER, SekyroApiError, type SekyroApiErrorCode, type SekyroApiErrorInit, type SekyroClientErrorCode, SekyroConfigError, type SekyroConfigErrorCode, SekyroEnvironment, type SekyroFlowError, type SekyroFlowErrorCode, type SekyroFlowErrorDetailsMap, SekyroResultTokenError, type SekyroResultTokenErrorCode, SekyroWebhookError, type SekyroWebhookErrorCode, ServiceId, SessionOutcome, SessionSubjectInput, type SubjectFromRegistryOptions, type SubjectRecord, SubjectReuseMode, VerificationAssurance, VerificationLevel, VerificationUnit, type VerifiedResult, type VerifyResultTokenOptions, type VerifyWebhookOptions, WebhookEnvelope, isFlowError, signatureFromHeaders, subjectFromNationalRegistry, verifyResultToken, verifyWebhook };
|
package/dist/index.js
ADDED
|
@@ -0,0 +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.10";var USER_AGENT=`@sekyro/node/${SDK_VERSION}`,DEFAULT_BASE_URL="https://api.sekyro.ai/api/v2",DEFAULT_TIMEOUT_MS=3e4,CONNECT_TELEMETRY=Symbol.for("@sekyro/node.connect-telemetry"),CONNECTOR_PROVIDER_RE=/^[a-z0-9-]{1,32}$/,CONNECTOR_VERSION_RE=/^[0-9A-Za-z.+-]{1,64}$/;function connectorHeaderOf(identity){if(!identity||typeof identity!="object")return;let{provider,version}=identity;if(!(typeof provider!="string"||!CONNECTOR_PROVIDER_RE.test(provider))&&!(typeof version!="string"||!CONNECTOR_VERSION_RE.test(version)))return`${provider}/${version}`}function toCreatedSession(wire){return{id:wire.id,status:wire.status,clientToken:wire.client_token,hostedUrl:wire.hosted_url,...wire.flow!==void 0?{flow:wire.flow}:{},steps:wire.steps,expiresAt:wire.expiresAt,...wire.level_target!==void 0?{levelTarget:wire.level_target}:{},...wire.subjectUse!==void 0?{subjectUse:wire.subjectUse}:{},...wire.warnings!==void 0?{warnings:wire.warnings}:{}}}var SUBJECT_ID_RE=/^[0-9a-f]{24}$/i;function isSuccessEnvelope(value){return typeof value=="object"&&value!==null&&value.success===!0&&"data"in value}function isErrorEnvelope(value){if(typeof value!="object"||value===null)return!1;let v=value;if(v.status!=="error"||typeof v.error!="object"||v.error===null)return!1;let e=v.error;return typeof e.code=="string"&&typeof e.message=="string"}function isAbortLike(err){if(typeof err!="object"||err===null)return!1;let name=err.name;return name==="TimeoutError"||name==="AbortError"}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new SekyroConfigError("invalid_base_url")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname)))throw new SekyroConfigError("invalid_base_url")}var Transport=class{apiKey;baseUrl;timeoutMs;fetchImpl;connectorHeader;constructor(opts){let baseUrl=(opts.baseUrl??DEFAULT_BASE_URL).replace(/\/+$/,"");assertSafeBaseUrl(baseUrl),this.apiKey=opts.apiKey,this.baseUrl=baseUrl,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS,this.fetchImpl=opts.fetch??globalThis.fetch,this.connectorHeader=connectorHeaderOf(opts.connector)}async call(method,path,body,idempotencyKey,timeoutMs=this.timeoutMs){let headers={authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":USER_AGENT};body!==void 0&&(headers["content-type"]="application/json"),idempotencyKey!==void 0&&(headers["x-idempotency-key"]=idempotencyKey),this.connectorHeader!==void 0&&(headers["x-sekyro-connector"]=this.connectorHeader);let init={method,headers,signal:AbortSignal.timeout(timeoutMs)};body!==void 0&&(init.body=JSON.stringify(body));let res;try{res=await this.fetchImpl(`${this.baseUrl}${path}`,init)}catch(err){throw isAbortLike(err)?new SekyroApiError({status:0,code:"timeout",message:`Request timed out after ${timeoutMs}ms`,cause:err}):new SekyroApiError({status:0,code:"network",message:`Network error: ${err instanceof Error?err.message:String(err)}`,cause:err})}let text2=await res.text(),parsed,parseError;try{parsed=text2.length>0?JSON.parse(text2):void 0}catch(err){parseError=err}if(!res.ok){let retryAfterSeconds=retryAfterSecondsOf(res.headers.get("retry-after"));if(isErrorEnvelope(parsed)){let init3={status:res.status,code:parsed.error.code,message:parsed.error.message};throw parsed.error.request_id!==void 0&&(init3.requestId=parsed.error.request_id),parsed.error.details!==void 0&&(init3.details=parsed.error.details),retryAfterSeconds!==void 0&&(init3.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init3)}let init2={status:res.status,code:"http_error",message:`HTTP ${res.status}${res.statusText?` ${res.statusText}`:""}`};throw retryAfterSeconds!==void 0&&(init2.retryAfterSeconds=retryAfterSeconds),new SekyroApiError(init2)}if(!isSuccessEnvelope(parsed))throw new SekyroApiError({status:res.status,code:"malformed_response",message:"Response is not a `{ success: true, data }` envelope",cause:parseError});return parsed.data}},SessionsApi=class{constructor(call){this.call=call}call;async create(input={},opts={}){let wire=await this.call("POST","/sessions",input,opts.idempotencyKey);return toCreatedSession(wire)}async selectMethod(id,method){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.selectMethod: `id` must be a non-empty string");return this.call("POST",`/sessions/${encodeURIComponent(id)}/method`,{method})}async get(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.get: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}`)}async list(query={}){let qs=new URLSearchParams;if(query.externalRef!==void 0){if(typeof query.externalRef!="string"||query.externalRef.length===0)throw new TypeError("sessions.list: `externalRef` must be a non-empty string");qs.set("externalRef",query.externalRef)}query.status!==void 0&&qs.set("status",query.status);let suffix=qs.size>0?`?${qs.toString()}`:"";return(await this.call("GET",`/sessions${suffix}`)).filter(s=>(query.externalRef===void 0||s.externalRef===query.externalRef)&&(query.status===void 0||s.status===query.status))}async portrait(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.portrait: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/portrait?format=url`)}async resultToken(id){if(typeof id!="string"||id.length===0)throw new TypeError("sessions.resultToken: `id` must be a non-empty string");return this.call("GET",`/sessions/${encodeURIComponent(id)}/result-token`)}};function assertId(method,id){if(typeof id!="string"||id.length===0)throw new TypeError(`subjects.${method}: \`id\` must be a non-empty string`)}var SubjectsApi=class{constructor(call){this.call=call}call;async get(id){return assertId("get",id),this.call("GET",`/subjects/${encodeURIComponent(id)}`)}async list(query){if(typeof query?.externalRef!="string"||query.externalRef.length===0)throw new TypeError("subjects.list: `externalRef` must be a non-empty string");let qs=new URLSearchParams({externalRef:query.externalRef});return this.call("GET",`/subjects?${qs.toString()}`)}async revoke(id,input={},opts={}){return assertId("revoke",id),this.call("POST",`/subjects/${encodeURIComponent(id)}/revoke`,input,opts.idempotencyKey)}async delete(id){return assertId("delete",id),this.call("DELETE",`/subjects/${encodeURIComponent(id)}`)}async createSession(target,input,opts={}){let path;if(typeof target=="string")assertId("createSession",target),path=SUBJECT_ID_RE.test(target)?`/subjects/${encodeURIComponent(target)}/sessions`:`/subjects/by-external-ref/${encodeURIComponent(target)}/sessions`;else if(target!==null&&typeof target=="object"&&"subjectId"in target)assertId("createSession",target.subjectId),path=`/subjects/${encodeURIComponent(target.subjectId)}/sessions`;else{let ref=target?.externalRef;assertId("createSession",ref),path=`/subjects/by-external-ref/${encodeURIComponent(ref)}/sessions`}if(input?.mode!=="recheck"&&input?.mode!=="step_up")throw new TypeError("subjects.createSession: `mode` must be 'recheck' or 'step_up'");let wire=await this.call("POST",path,input,opts.idempotencyKey);return toCreatedSession(wire)}},Sekyro=class{sessions;subjects;#transport;constructor(opts){if(typeof opts?.apiKey!="string"||opts.apiKey.length===0)throw new SekyroConfigError("missing_api_key");let transport=new Transport(opts);this.#transport=transport,this.sessions=new SessionsApi(transport.call.bind(transport)),this.subjects=new SubjectsApi(transport.call.bind(transport)),Object.defineProperty(this,CONNECT_TELEMETRY,{value:{setConnector(identity){transport.connectorHeader=connectorHeaderOf(identity)},async postEvents(events,timeoutMs){await transport.call("POST","/connect/events",{events},void 0,timeoutMs)}},enumerable:!1})}async listFlows(){return this.#transport.call("GET","/flows")}};var REGISTRY_TEXT=[[/mauritan/i,"MR"],[/موريتاني/,"MR"]];function alpha2FromRegistry(values){let out=new Set;for(let v of values??[])if(typeof v=="string")for(let[re,code]of REGISTRY_TEXT)re.test(v)&&out.add(code);return[...out]}var ADAPTERS={MR:fromAnrpts};function subjectFromNationalRegistry(country,response,options){let adapter=Object.prototype.hasOwnProperty.call(ADAPTERS,country)?ADAPTERS[country]:void 0;if(adapter===void 0)throw new SekyroConfigError("registry_country_unsupported",`Sekyro AI: no national registry format for country \`${String(country)}\``);return adapter(response,options)}function invalid(what){throw new SekyroConfigError("invalid_registry_record",`Sekyro AI: the registry answer has no usable \`${what}\``)}function fromAnrpts(response,options){let raw=response?.personne,p=raw!==null&&typeof raw=="object"?raw:{},number=text(p.nni)??invalid("personne.nni"),names=[],latin=nameOf("Latn",p.prenomFr,p.patronymeFr,p.perePrenomFr);latin!==void 0&&names.push(latin);let arabic=nameOf("Arab",p.prenomAr,p.patronymeAr,p.perePrenomAr);arabic!==void 0&&names.push(arabic),names.length===0&&invalid("names (personne.prenomFr and personne.patronymeFr, or personne.prenomAr and personne.patronymeAr)");let birthDate=isoDay(p.dateNaissance)??invalid("personne.dateNaissance"),photo=(text(response?.photo)??invalid("photo")).replace(/\s+/g,""),fetchedAt=new Date(options?.fetchedAt??Number.NaN);if(Number.isNaN(fetchedAt.getTime()))throw new SekyroConfigError("invalid_registry_record","Sekyro AI: `fetchedAt` (when your system received the registry answer) is missing or not a valid date");let record={idNumber:{type:"national_id",issuingCountry:"MR",number},names,birthDate,photo,fetchedAt:fetchedAt.toISOString()},birthPlace=text(p.lieuNaissanceFr)??text(p.lieuNaissanceAr);birthPlace!==void 0&&(record.birthPlace=birthPlace);let sex=text(p.sexeCode)?.toUpperCase();(sex==="M"||sex==="F")&&(record.sex=sex);let adjectives=Array.isArray(p.nationalities)?p.nationalities.map(text).filter(n=>n!==void 0):[],nationality=text(options?.nationality)?.toUpperCase()??alpha2FromRegistry(adjectives)[0];if(nationality===void 0&&adjectives.length>0)throw new SekyroConfigError("registry_nationality_unmapped","Sekyro AI: the registry answer has a nationality the SDK cannot map; map it and pass options.nationality");nationality!==void 0&&(record.nationality=nationality);let photoDate=isoDay(response?.datePhoto);return photoDate!==void 0&&(record.photoDate=photoDate),record}function nameOf(script,given,family,patronymic){let g=text(given),f=text(family);if(g===void 0||f===void 0)return;let pat=text(patronymic);return pat===void 0?{script,given:g,family:f}:{script,given:g,family:f,patronymic:pat}}function text(value){if(typeof value!="string")return;let s=value.trim();return s.length>0?s:void 0}function isoDay(value){let s=text(value);if(s===void 0)return;let iso=/^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(s),fr=/^(\d{2})\/(\d{2})\/(\d{4})$/.exec(s),[y,m,d]=iso?[iso[1],iso[2],iso[3]]:fr?[fr[3],fr[2],fr[1]]:[];if(y===void 0||m===void 0||d===void 0)return;let t=new Date(Date.UTC(Number(y),Number(m)-1,Number(d)));return t.getUTCFullYear()===Number(y)&&t.getUTCMonth()===Number(m)-1&&t.getUTCDate()===Number(d)?`${y}-${m}-${d}`:void 0}import{createHmac,timingSafeEqual}from"crypto";var SEKYRO_SIGNATURE_HEADER="x-sekyro-signature",LEGACY_SIGNATURE_HEADER="x-ibtikar-signature";function signatureFromHeaders(headers){return readHeader(headers,SEKYRO_SIGNATURE_HEADER)??readHeader(headers,LEGACY_SIGNATURE_HEADER)}function readHeader(headers,name){if(typeof headers.get=="function"){let v2=headers.get(name);return v2===null||v2===""?void 0:v2}let record=headers,key=Object.keys(record).find(k=>k.toLowerCase()===name);if(key===void 0)return;let raw=record[key],v=Array.isArray(raw)?raw[0]:raw;return v===void 0||v===""?void 0:v}var HEX64=/^[0-9a-f]{64}$/i;function verifyWebhook(rawBody,header,secret,opts={}){if(!header||!secret)throw new SekyroWebhookError("invalid_signature");let parts=header.split(",").map(part=>{let trimmed=part.trim(),eq=trimmed.indexOf("=");return eq===-1?[trimmed,""]:[trimmed.slice(0,eq).trim(),trimmed.slice(eq+1).trim()]}),tRaw=parts.find(([k])=>k==="t")?.[1],t=tRaw!==void 0&&/^\d+$/.test(tRaw)?Number(tRaw):Number.NaN,sigs=parts.filter(([k])=>k==="v1").map(([,v])=>v);if(!Number.isSafeInteger(t)||sigs.length===0)throw new SekyroWebhookError("malformed");let nowSec=Math.floor((opts.now?.()??Date.now())/1e3),tolerance=opts.toleranceSec??300;if(Math.abs(nowSec-t)>tolerance)throw new SekyroWebhookError("stale");let expected=createHmac("sha256",secret).update(`${t}.${rawBody}`).digest();if(!sigs.some(hex=>{if(!HEX64.test(hex))return!1;let got=Buffer.from(hex,"hex");return got.length===expected.length&&timingSafeEqual(got,expected)}))throw new SekyroWebhookError("invalid_signature");let parsed;try{parsed=JSON.parse(rawBody)}catch{throw new SekyroWebhookError("malformed","Signed body is not valid JSON")}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))throw new SekyroWebhookError("malformed","Signed body is not a JSON object");return parsed}import{createLocalJWKSet,errors as joseErrors,jwtVerify}from"jose";var DEFAULT_RESULT_TOKEN_ISSUER="https://api.sekyro.ai",RESULT_TOKEN_JWKS_PATH="/.well-known/sekyro/jwks.json",SANDBOX_KID_PREFIX="sbx-",JWKS_MAX_AGE_MS=600*1e3,JWKS_COOLDOWN_MS=30*1e3,JWKS_TIMEOUT_MS=5e3,jwksCache=new Map,LOOPBACK_HOSTS2=new Set(["localhost","127.0.0.1","[::1]"]);function assertSafeUrl(raw){let url;try{url=new URL(raw)}catch{throw new SekyroResultTokenError("invalid_options","`jwksUrl` (or `issuer`) is not a URL")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS2.has(url.hostname)))throw new SekyroResultTokenError("invalid_options","`jwksUrl` must be an https: URL (http: is allowed only for localhost, 127.0.0.1 or [::1])")}async function fetchKeySet(url,fetchImpl){let res;try{res=await fetchImpl(url,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(JWKS_TIMEOUT_MS)})}catch(err){throw new SekyroResultTokenError("jwks_unavailable",void 0,err)}if(!res.ok)throw new SekyroResultTokenError("jwks_unavailable",`Key set answered HTTP ${res.status}`);let body;try{body=await res.json()}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not JSON",err)}try{return createLocalJWKSet(body)}catch(err){throw new SekyroResultTokenError("jwks_unavailable","Key set is not a JWKS document",err)}}async function keySet(url,fetchImpl,nowMs,force){let entry=jwksCache.get(url);if(entry?.pending)return entry.pending;if(entry?.keys&&!force&&nowMs-entry.fetchedAt<JWKS_MAX_AGE_MS)return entry.keys;let pending=fetchKeySet(url,fetchImpl),next={fetchedAt:entry?.fetchedAt??0,pending};entry?.keys&&(next.keys=entry.keys),jwksCache.set(url,next);try{let keys=await pending;return jwksCache.set(url,{keys,fetchedAt:nowMs}),keys}catch(err){throw next.keys?jwksCache.set(url,{keys:next.keys,fetchedAt:next.fetchedAt}):jwksCache.delete(url),err}}function mapJoseError(err){if(err instanceof SekyroResultTokenError)return err;if(err instanceof joseErrors.JWTExpired)return new SekyroResultTokenError("expired",void 0,err);if(err instanceof joseErrors.JWTClaimValidationFailed){if(err.claim==="aud")return new SekyroResultTokenError("wrong_audience",void 0,err);if(err.claim==="iss")return new SekyroResultTokenError("wrong_issuer",void 0,err)}return new SekyroResultTokenError("invalid_token",void 0,err)}function str(v){return typeof v=="string"&&v.length>0?v:void 0}function appIdsOf(appId){let ids=Array.isArray(appId)?appId:[appId];if(ids.length===0||ids.some(id=>typeof id!="string"||id.length===0))throw new SekyroResultTokenError("invalid_options","`appId` is required (a non-empty string or array of them)");return ids}function matchedAud(aud,accepted){return typeof aud=="string"?aud:(aud??[]).find(a=>accepted.includes(a))??accepted[0]}function toResult(payload,claim,env,appId){let out={sessionId:String(claim.session_id),orgId:String(claim.org_id??""),appId,env,level:typeof claim.level=="number"?claim.level:null,assurance:str(claim.assurance)??null,outcome:str(claim.outcome)??null,unit:str(claim.unit)??null,verifiedAt:String(claim.verified_at??"")},subjectId=str(payload.sub);subjectId!==void 0&&(out.subjectId=subjectId);let externalRef=str(claim.external_ref);externalRef!==void 0&&(out.externalRef=externalRef);let flow=claim.flow;flow&&typeof flow.slug=="string"&&typeof flow.version=="number"&&(out.flow={slug:flow.slug,version:flow.version}),(claim.reuse_mode==="recheck"||claim.reuse_mode==="step_up")&&(out.reuseMode=claim.reuse_mode);let r=claim.risk;r&&typeof r=="object"&&(out.risk={level:r.level==="high"||r.level==="medium"?r.level:"low",vpn:r.vpn===!0,ipDocumentMismatch:r.ip_document_mismatch===!0,deviceTampered:r.device_tampered===!0});let c=claim.checks;c&&typeof c=="object"&&(out.checks={attestation:c.attestation,captureProof:c.capture_proof,injectionSignals:c.injection_signals}),Array.isArray(claim.duplicates)&&(out.duplicates=claim.duplicates.map(d=>{let dup={subjectId:String(d.subject_id??d.subjectId??"")},ref=str(d.external_ref)??str(d.externalRef);return ref!==void 0&&(dup.externalRef=ref),dup}));let age=claim.age;return age&&typeof age=="object"&&typeof age.over=="number"&&Number.isFinite(age.over)&&typeof age.method=="string"&&age.method!==""&&(out.age={over:age.over,method:age.method}),out}async function verifyResultToken(token,opts){let appIds=appIdsOf(opts?.appId);if(typeof token!="string"||token.length===0)throw new SekyroResultTokenError("invalid_token","The token is empty");let issuer=(opts.issuer??DEFAULT_RESULT_TOKEN_ISSUER).replace(/\/+$/,""),jwksUrl=opts.jwksUrl??`${issuer}${RESULT_TOKEN_JWKS_PATH}`;assertSafeUrl(jwksUrl);let fetchImpl=opts.fetch??globalThis.fetch,now=opts.now??Date.now,verifyOpts={issuer,audience:appIds,algorithms:["ES256"],currentDate:new Date(now()),clockTolerance:opts.clockToleranceSec??30},verified;try{let keys=await keySet(jwksUrl,fetchImpl,now(),!1);try{verified=await jwtVerify(token,keys,verifyOpts)}catch(err){if(!(err instanceof joseErrors.JWKSNoMatchingKey))throw err;let entry=jwksCache.get(jwksUrl);if(entry&&now()-entry.fetchedAt<JWKS_COOLDOWN_MS)throw err;verified=await jwtVerify(token,await keySet(jwksUrl,fetchImpl,now(),!0),verifyOpts)}}catch(err){throw mapJoseError(err)}let{payload,protectedHeader}=verified,claim=payload.sekyro;if(typeof claim!="object"||claim===null||typeof claim.session_id!="string")throw new SekyroResultTokenError("invalid_token","The token has no `sekyro` claim");let c=claim,env=c.env;if(env!=="live"&&env!=="sandbox")throw new SekyroResultTokenError("invalid_token","The token has no valid `sekyro.env` claim");let sandboxKey=String(protectedHeader.kid??"").startsWith(SANDBOX_KID_PREFIX);if(env==="sandbox"!==sandboxKey)throw new SekyroResultTokenError("key_env_mismatch");if(opts.env!==void 0&&env!==opts.env)throw new SekyroResultTokenError("wrong_env",`The token is for ${env}, expected ${opts.env}`);return toResult(payload,c,env,matchedAud(payload.aud,appIds))}export{DEFAULT_BASE_URL,DEFAULT_RESULT_TOKEN_ISSUER,DEFAULT_TIMEOUT_MS,LEGACY_SIGNATURE_HEADER,RESULT_TOKEN_JWKS_PATH,SEKYRO_SIGNATURE_HEADER,Sekyro,SekyroApiError,SekyroConfigError,SekyroResultTokenError,SekyroWebhookError,isFlowError,signatureFromHeaders,subjectFromNationalRegistry,verifyResultToken,verifyWebhook};
|
package/package.json
CHANGED
|
@@ -1,6 +1,98 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sekyro/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-rc.10",
|
|
4
|
+
"description": "Sekyro AI server SDK for Node.js — create and read verification sessions, verify signed webhooks and result tokens.",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"require": {
|
|
18
|
+
"types": "./dist/index.d.cts",
|
|
19
|
+
"default": "./dist/index.cjs"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"./connect": {
|
|
23
|
+
"import": {
|
|
24
|
+
"types": "./dist/connect/index.d.ts",
|
|
25
|
+
"default": "./dist/connect/index.js"
|
|
26
|
+
},
|
|
27
|
+
"require": {
|
|
28
|
+
"types": "./dist/connect/index.d.cts",
|
|
29
|
+
"default": "./dist/connect/index.cjs"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"./connect/express": {
|
|
33
|
+
"import": {
|
|
34
|
+
"types": "./dist/connect/express/index.d.ts",
|
|
35
|
+
"default": "./dist/connect/express/index.js"
|
|
36
|
+
},
|
|
37
|
+
"require": {
|
|
38
|
+
"types": "./dist/connect/express/index.d.cts",
|
|
39
|
+
"default": "./dist/connect/express/index.cjs"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"./connect/next": {
|
|
43
|
+
"import": {
|
|
44
|
+
"types": "./dist/connect/next/index.d.ts",
|
|
45
|
+
"default": "./dist/connect/next/index.js"
|
|
46
|
+
},
|
|
47
|
+
"require": {
|
|
48
|
+
"types": "./dist/connect/next/index.d.cts",
|
|
49
|
+
"default": "./dist/connect/next/index.cjs"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"./package.json": "./package.json"
|
|
53
|
+
},
|
|
54
|
+
"files": [
|
|
55
|
+
"dist",
|
|
56
|
+
"README.md",
|
|
57
|
+
"CHANGELOG.md",
|
|
58
|
+
"LICENSE",
|
|
59
|
+
"sbom.cdx.json"
|
|
60
|
+
],
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=20"
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
},
|
|
67
|
+
"repository": {
|
|
68
|
+
"type": "git",
|
|
69
|
+
"url": "git+https://github.com/IBTIKAR-Technologies/ibtikar-identity.git",
|
|
70
|
+
"directory": "packages/sekyro-node"
|
|
71
|
+
},
|
|
72
|
+
"keywords": [
|
|
73
|
+
"sekyro",
|
|
74
|
+
"kyc",
|
|
75
|
+
"identity-verification",
|
|
76
|
+
"liveness",
|
|
77
|
+
"webhooks",
|
|
78
|
+
"mauritania",
|
|
79
|
+
"sdk"
|
|
80
|
+
],
|
|
81
|
+
"scripts": {
|
|
82
|
+
"build": "tsup",
|
|
83
|
+
"test": "vitest run",
|
|
84
|
+
"typecheck": "tsc --noEmit",
|
|
85
|
+
"api:report": "api-extractor run --local && api-extractor run --local -c api-extractor.connect.json && api-extractor run --local -c api-extractor.connect-express.json && api-extractor run --local -c api-extractor.connect-next.json",
|
|
86
|
+
"api:check": "api-extractor run && api-extractor run -c api-extractor.connect.json && api-extractor run -c api-extractor.connect-express.json && api-extractor run -c api-extractor.connect-next.json"
|
|
87
|
+
},
|
|
88
|
+
"devDependencies": {
|
|
89
|
+
"@microsoft/api-extractor": "^7",
|
|
90
|
+
"@types/node": "^20",
|
|
91
|
+
"tsup": "^8",
|
|
92
|
+
"typescript": "^5.7",
|
|
93
|
+
"vitest": "^3"
|
|
94
|
+
},
|
|
95
|
+
"dependencies": {
|
|
96
|
+
"jose": "^5.10.0"
|
|
97
|
+
}
|
|
98
|
+
}
|