@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/README.md
CHANGED
|
@@ -1,3 +1,533 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sekyro/node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server SDK for [Sekyro AI](https://sekyro.ai) identity verification. One runtime
|
|
4
|
+
dependency (`jose`, for result tokens), Node.js ≥ 20, ESM + CommonJS, typed.
|
|
5
|
+
|
|
6
|
+
Three jobs, nothing else:
|
|
7
|
+
|
|
8
|
+
1. **Sessions**: create a verification session from your backend and read its
|
|
9
|
+
result. The API key never leaves your server.
|
|
10
|
+
2. **Webhooks**: verify the `x-sekyro-signature` header on deliveries (the
|
|
11
|
+
legacy `x-ibtikar-signature` name is still sent) and get a typed envelope
|
|
12
|
+
back.
|
|
13
|
+
3. **Result tokens**: verify the signed result token of a finished session
|
|
14
|
+
(`verifyResultToken`) and read its level, assurance and outcome.
|
|
15
|
+
|
|
16
|
+
The SDK does **not** orchestrate checks or retry for you; the partner owns the
|
|
17
|
+
retry policy (`SekyroApiError.retryable` tells you when a retry is sensible).
|
|
18
|
+
|
|
19
|
+
**Integration guide:** [Web SDK guide](https://docs.sekyro.ai/en/web/embedded-sdk)
|
|
20
|
+
(server-bound NNI, display vs authoritative results, webhook receivers for
|
|
21
|
+
Next.js and Express, billing). The hosted-flow path is in the
|
|
22
|
+
[quickstart](https://docs.sekyro.ai/en/getting-started/quickstart).
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install @sekyro/node@next
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The SDK is licensed under the
|
|
31
|
+
[Sekyro AI SDK License](https://sekyro.ai/legal/sdk-license).
|
|
32
|
+
|
|
33
|
+
## Sessions
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { Sekyro } from "@sekyro/node";
|
|
37
|
+
|
|
38
|
+
const sekyro = new Sekyro({
|
|
39
|
+
apiKey: process.env.SEKYRO_API_KEY!,
|
|
40
|
+
// baseUrl: "https://api.sekyro.ai/api/v2", // default; use https://api-staging.sekyro.ai/api/v2 for sandbox work
|
|
41
|
+
// timeoutMs: 30_000, // default
|
|
42
|
+
});
|
|
43
|
+
// Throws `SekyroConfigError` (a TypeError; `code` = 'missing_api_key' | 'invalid_base_url')
|
|
44
|
+
// when apiKey is missing or baseUrl is not https: (plain http: is accepted only for
|
|
45
|
+
// localhost / 127.0.0.1 / [::1], since the API key rides on every request).
|
|
46
|
+
|
|
47
|
+
// Create: returns the one-time client token your front end hands to @sekyro/web.
|
|
48
|
+
// `flow` picks one of the app's flows (omit it for the default flow).
|
|
49
|
+
// `subject.idNumber` BINDS the session to that identity: the browser never sends
|
|
50
|
+
// the number (a different one is refused with 409 id_number_locked, formerly nni_locked).
|
|
51
|
+
const created = await sekyro.sessions.create(
|
|
52
|
+
{
|
|
53
|
+
flow: "default",
|
|
54
|
+
locale: "ar",
|
|
55
|
+
subject: { idNumber: { type: "national_id", issuingCountry: "<ISO alpha-2>", number: "<id number>" } },
|
|
56
|
+
},
|
|
57
|
+
{ idempotencyKey: `signup:${userId}` },
|
|
58
|
+
);
|
|
59
|
+
created.id; // persist against your user before returning to the page
|
|
60
|
+
created.clientToken; // give this to the browser; it is returned ONCE
|
|
61
|
+
created.hostedUrl; // the hosted-flow link, if you use that path instead
|
|
62
|
+
created.expiresAt; // ISO 8601
|
|
63
|
+
created.flow; // { id, slug, version }: the flow version the session runs
|
|
64
|
+
created.subjectUse; // 'reference' | 'prefill': whether the flow believes or checks your subject data
|
|
65
|
+
created.warnings; // one { code: 'deprecated_field', field, replacement } per deprecated key you sent
|
|
66
|
+
|
|
67
|
+
// Read: the whitelisted session view (never contains the client token).
|
|
68
|
+
const session = await sekyro.sessions.get(created.id);
|
|
69
|
+
session.status; // 'created' | 'in_progress' | 'review_pending' | 'completed' | 'expired' | 'failed'
|
|
70
|
+
session.outcome; // 'approved' | 'review' | 'rejected' | null
|
|
71
|
+
session.flow; // { id: 'flw_…', slug: 'default', version: 3 }: the flow version the session runs
|
|
72
|
+
session.steps; // [{ checkType, state, nodeId?, service?, handled?, reason?, calibratedScore? }]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Your API key belongs to an **app**. The app's **flows**, designed in the Sekyro AI
|
|
76
|
+
dashboard (app page → **Flows**), decide which steps run; a session runs the
|
|
77
|
+
flow you name in `flow`, or the app's default flow. To list the published flows
|
|
78
|
+
of the key's app, call `sekyro.listFlows()`: it resolves to
|
|
79
|
+
`FlowSummary[]` (`[{ id, slug, name, version, isDefault }]`), the default flow
|
|
80
|
+
first (`GET /api/v2/flows` under the hood, scope `sessions:create`;
|
|
81
|
+
see the [quickstart](https://docs.sekyro.ai/en/getting-started/quickstart#choose-a-flow)).
|
|
82
|
+
Every field is optional:
|
|
83
|
+
|
|
84
|
+
| field | meaning |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `flow` | the flow's identifier (slug, e.g. `foreigners`) or id (`flw_…`); omit for the app's default flow. `404 flow_not_found`, `409 flow_not_published`, `409 flow_archived` |
|
|
87
|
+
| `overrides` | `{ settings?, services? }`: changes the flow for this session only (see below; `403 override_widens_flow` for a looser change unless the flow allows it, `400 override_invalid` for an invalid one) |
|
|
88
|
+
| `locale` | `ar`, `fr` or `en`: pins the hosted-flow language |
|
|
89
|
+
| `ttlMinutes` | session lifetime, within the flow's link range (`400 ttl_out_of_policy` otherwise); omit for the flow default |
|
|
90
|
+
| `subject` | what you know about the person: `idNumber` (`{ type, issuingCountry, number }`, binds the session), `fullName`, `names` (per script), `birthDate`, `birthPlace`, `sex`, `nationality`, `phone`, `email`, and for a reference record `photo`, `photoDate`, `fetchedAt`; your own id for them (`externalRef`), or `reuse` for a [returning user](#subjects). The flow decides whether the data is checked or believed (`created.subjectUse`) |
|
|
91
|
+
| `input` | an open record of branch facts your flow's conditions read. Its person keys (`nni`, `phone`, `email`, `fullName`, `birthDate`, `suppliedIdentity`) are deprecated: send them in `subject` (`subject.nni` and `subject.documentNumber` are deprecated too, for `subject.idNumber`) |
|
|
92
|
+
| `identityMethod` | `national_number`, `document_photo`, `document_chip` or `national_eid`: pre-chooses the option of the flow's identity choice |
|
|
93
|
+
| `deliver` | `{ channel: "sms" \| "whatsapp", to: "+1555…" }`: also send the hosted link to the person |
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
// The app's flows (published only, default first): pick one at runtime.
|
|
97
|
+
const flows = await sekyro.listFlows(); // [{ id, slug, name, version, isDefault }]
|
|
98
|
+
|
|
99
|
+
await sekyro.sessions.create({
|
|
100
|
+
flow: "foreigners",
|
|
101
|
+
overrides: {
|
|
102
|
+
settings: { eligibility: { minAge: 21 } }, // general settings
|
|
103
|
+
services: { liveness: { attempts: 2 } }, // per-service settings
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`overrides.settings` changes the flow's general settings (eligibility,
|
|
109
|
+
decisions, data consistency, returning users, documents); `overrides.services`
|
|
110
|
+
changes a service's settings, keyed by service id (`liveness`, `phone_otp`,
|
|
111
|
+
`device_network`, …), or removes it with `'off'`. An override may only make
|
|
112
|
+
the flow stricter unless the flow allows widening; turning a service `'off'`
|
|
113
|
+
always widens. The changed paths come back on `session.overriddenFields`.
|
|
114
|
+
|
|
115
|
+
> **Sekyro flows breaking change.** The `profile` override is gone: use
|
|
116
|
+
> `overrides`. `flow` is accepted again, now as the app's flow slug or id.
|
|
117
|
+
|
|
118
|
+
The session view also carries `failureReason` (a policy stop such as
|
|
119
|
+
`location_not_allowed` or `underage`), `failureDetail` (why, when that reason
|
|
120
|
+
is `camera_unavailable`: `denied` or `no_camera`), `overriddenFields`, `riskSignals`,
|
|
121
|
+
`subjectId` / `externalRef`, `verifiedContacts`, `eid`, and the end user's
|
|
122
|
+
`network` and `device`. A step with `handled: true` failed, but the flow's
|
|
123
|
+
fallback took over.
|
|
124
|
+
|
|
125
|
+
Two more session calls:
|
|
126
|
+
|
|
127
|
+
- `sekyro.sessions.selectMethod(id, method)` chooses the identity method of a
|
|
128
|
+
session on the person's behalf (`POST /sessions/:id/method`): `409 choice_locked`
|
|
129
|
+
once the flow's identity choice can no longer change, `409 choice_option_unavailable`
|
|
130
|
+
for a method the flow does not offer this session, `409 choice_not_found` when the
|
|
131
|
+
flow has no identity choice.
|
|
132
|
+
- `sekyro.sessions.portrait(id)` returns a 5-minute link to the ICAO portrait of
|
|
133
|
+
a session whose `portrait_icao` check passed (`portraitAvailable`; scope
|
|
134
|
+
`portrait:read`).
|
|
135
|
+
|
|
136
|
+
`sekyro.sessions` is a `SessionsApi`, exported as a type only: you get the
|
|
137
|
+
instance from the client, never by constructing one.
|
|
138
|
+
|
|
139
|
+
### Person data
|
|
140
|
+
|
|
141
|
+
Send what you know about the person in `subject`: `idNumber`
|
|
142
|
+
(`{ type, issuingCountry, number }`), `fullName` or `names` (given, family and
|
|
143
|
+
patronymic per ISO 15924 script), `birthDate`, `nationality`, `phone`, `email`,
|
|
144
|
+
and for a flow that verifies identity from your data, `photo` and `fetchedAt`.
|
|
145
|
+
The session's flow decides how Sekyro AI uses it, never the request: when a step
|
|
146
|
+
reads partner-supplied data (an environment Sekyro AI set to the `supplied`
|
|
147
|
+
mode), the record is the **reference** to believe; otherwise it is a
|
|
148
|
+
**prefill** checked against what the person shows. `created.subjectUse` says
|
|
149
|
+
which (`"reference"` or `"prefill"`). The rules, the trust table and every
|
|
150
|
+
error are on the [Person data](https://docs.sekyro.ai/en/guides/person-data)
|
|
151
|
+
page.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
// A prefill: the flow checks it against the registry or the document.
|
|
155
|
+
await sekyro.sessions.create({
|
|
156
|
+
subject: {
|
|
157
|
+
externalRef: userId,
|
|
158
|
+
idNumber: { type: "passport", issuingCountry: "<ISO alpha-2>", number: "<id number>" },
|
|
159
|
+
birthDate: "<YYYY-MM-DD>",
|
|
160
|
+
},
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
If your data comes from your own call to a national registry,
|
|
165
|
+
`subjectFromNationalRegistry()` converts that answer locally into the
|
|
166
|
+
reference keys. Sekyro AI treats the result as identity data supplied by your
|
|
167
|
+
organization: it makes no registry call, and it never receives or stores any
|
|
168
|
+
registry key.
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { subjectFromNationalRegistry } from "@sekyro/node";
|
|
172
|
+
|
|
173
|
+
const answer = await myRegistryClient.lookup(idNumber); // your call, your key
|
|
174
|
+
const receivedAt = new Date();
|
|
175
|
+
const created = await sekyro.sessions.create({
|
|
176
|
+
subject: {
|
|
177
|
+
externalRef: userId,
|
|
178
|
+
// fetchedAt: when YOUR system received this answer (required; > 24 h old is refused)
|
|
179
|
+
...subjectFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }),
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
created.subjectUse; // "reference" in a supplied-mode environment whose flow reads it
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The first argument is the registry's country (ISO alpha-2) and types the
|
|
186
|
+
answer: `"MR"` takes the ANRPTS `getPersonne` answer
|
|
187
|
+
(`AnrptsPersonneResponse`). The result is a `SubjectRecord`: `idNumber`,
|
|
188
|
+
`names` (one entry per script found), `birthDate`, `birthPlace`, `sex`,
|
|
189
|
+
`nationality` (alpha-2), `photo`, `photoDate` and `fetchedAt`. A record without
|
|
190
|
+
a number, a birth date, a photo or any name, or with an invalid `fetchedAt`,
|
|
191
|
+
throws `SekyroConfigError` `invalid_registry_record` naming the field (never
|
|
192
|
+
its value); a country without an adapter throws `registry_country_unsupported`.
|
|
193
|
+
An answer that states a nationality none of whose values the SDK can map throws
|
|
194
|
+
`registry_nationality_unmapped` (the message never carries the value): map it
|
|
195
|
+
yourself and pass `options.nationality` (ISO alpha-2), so the stated nationality
|
|
196
|
+
is never dropped.
|
|
197
|
+
`subjectFromNationalRegistry()` replaces `registryFromAnrpts()`.
|
|
198
|
+
|
|
199
|
+
Refusals of a reference, in this order: `403 supplied_identity_not_entitled`
|
|
200
|
+
(the environment is not in `supplied` mode), `422 subject_record_incomplete`
|
|
201
|
+
(`error.details.fields` names the missing keys), `422 subject_record_stale`
|
|
202
|
+
(obtained more than 24 h ago, or more than 5 min ahead) and
|
|
203
|
+
`422 subject_photo_unusable` (not a JPEG or PNG of at most 1 MB within the size
|
|
204
|
+
bounds). A `photo` on a session that cannot use it (a prefill, a returning
|
|
205
|
+
user) answers `422 subject_photo_not_used`.
|
|
206
|
+
|
|
207
|
+
No face processing runs at create. The face on the supplied photo is checked after
|
|
208
|
+
the person consents, at the face match: a photo without one usable face fails that
|
|
209
|
+
step with `no_face_reference` (or `low_quality_reference`). That step runs after liveness, so check
|
|
210
|
+
that the photo shows exactly one clear face before you send it.
|
|
211
|
+
|
|
212
|
+
Partner-supplied identity data is not billed: the identity step in `supplied` mode
|
|
213
|
+
records no usage event (other steps, such as the face match, bill as usual).
|
|
214
|
+
|
|
215
|
+
**Deprecated keys.** `input.nni`, `input.fullName`, `input.birthDate`,
|
|
216
|
+
`input.phone`, `input.email`, `input.suppliedIdentity`, `subject.nni`,
|
|
217
|
+
`subject.documentNumber`, `subject.reuse.nni` and `subject.reuse.document`
|
|
218
|
+
still work. A create that uses one gets a `Deprecation` header and one
|
|
219
|
+
`created.warnings` entry per key (`{ code: "deprecated_field", field,
|
|
220
|
+
replacement }`). The step reasons and codes about the number get generic names
|
|
221
|
+
(`registry_record_not_found` for `nni_not_found`, `id_number_locked` for
|
|
222
|
+
`nni_locked`, `document_id_number_mismatch` for `document_nni_mismatch`, ...):
|
|
223
|
+
the API still sends the previous names, so accept both. The full migration
|
|
224
|
+
table is on the [Person data](https://docs.sekyro.ai/en/guides/person-data#deprecated-keys)
|
|
225
|
+
page.
|
|
226
|
+
|
|
227
|
+
### Errors
|
|
228
|
+
|
|
229
|
+
Every non-2xx response, network failure and timeout throws `SekyroApiError`:
|
|
230
|
+
|
|
231
|
+
| field | meaning |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `status` | HTTP status (`0` for network / timeout) |
|
|
234
|
+
| `code` | API error code, or `network` / `timeout` / `http_error` / `malformed_response` |
|
|
235
|
+
| `message` | human-readable, from the API when available |
|
|
236
|
+
| `requestId` | the API's `request_id`, quote it to support |
|
|
237
|
+
| `details` | the API's `error.details` when sent, else `undefined`; typed for the flow codes through `isFlowError()` |
|
|
238
|
+
| `retryable` | `true` for `network`, `timeout`, `429`, `5xx` and `idempotency_in_progress` |
|
|
239
|
+
| `retryAfterSeconds` | seconds to wait from the response's `Retry-After` header (seconds or an HTTP date), else `undefined` |
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import { SekyroApiError } from "@sekyro/node";
|
|
243
|
+
|
|
244
|
+
try {
|
|
245
|
+
await sekyro.sessions.create({ subject: { idNumber } });
|
|
246
|
+
} catch (err) {
|
|
247
|
+
if (err instanceof SekyroApiError && err.retryable) {
|
|
248
|
+
// wait err.retryAfterSeconds when set, else back off; retry with the SAME idempotencyKey
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Flow codes (`SekyroFlowErrorCode`) carry machine-readable `details`:
|
|
254
|
+
`details.issues[]` (`{ code, message, path?, nodeId?, service?, field? }`,
|
|
255
|
+
never a value you sent), plus `fields` on `override_widens_flow` and `flow`
|
|
256
|
+
(`{ id, slug }`) on `flow_not_published`, `flow_archived` and `reuse_disabled`.
|
|
257
|
+
`isFlowError(err, ...codes)` narrows `err.details` to the code's shape; it
|
|
258
|
+
returns `false` when the details are missing or not in that shape, so read
|
|
259
|
+
`err.code` as the fallback.
|
|
260
|
+
|
|
261
|
+
| code | from | `details` |
|
|
262
|
+
|---|---|---|
|
|
263
|
+
| `404 flow_not_found` | `sessions.create` | `issues` (`path: "flow"`) |
|
|
264
|
+
| `409 flow_not_published`, `409 flow_archived` | `sessions.create` | `issues`, `flow` |
|
|
265
|
+
| `400 override_invalid` | `sessions.create` | `issues`, one per problem (`path: "overrides.services.liveness.attempts"`, …) |
|
|
266
|
+
| `403 override_widens_flow` | `sessions.create` | `issues` (`field_widens_flow`), `fields` |
|
|
267
|
+
| `409 reuse_disabled` | `sessions.create` with `subject.reuse` | `issues`, `flow` |
|
|
268
|
+
| `409 choice_not_found`, `choice_locked`, `choice_option_unavailable` | `sessions.selectMethod` | `issues` |
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
import { isFlowError } from "@sekyro/node";
|
|
272
|
+
|
|
273
|
+
try {
|
|
274
|
+
await sekyro.sessions.create({ flow: "foreigners", overrides });
|
|
275
|
+
} catch (err) {
|
|
276
|
+
if (isFlowError(err, "override_widens_flow")) {
|
|
277
|
+
console.warn("widening refused", err.details.fields);
|
|
278
|
+
} else if (isFlowError(err, "override_invalid")) {
|
|
279
|
+
for (const issue of err.details.issues) console.warn(issue.path, issue.message);
|
|
280
|
+
} else throw err;
|
|
281
|
+
}
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
## Subjects
|
|
285
|
+
|
|
286
|
+
A **subject** is the same person across all of your apps. Reads need the
|
|
287
|
+
`subjects:read` scope; `revoke` and `delete` need `subjects:write` (keys minted
|
|
288
|
+
from the dashboard carry both; mint a new key if an older one answers
|
|
289
|
+
`403 insufficient_scope`).
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
const subject = await sekyro.subjects.get(subjectId);
|
|
293
|
+
subject.status; // 'active' | 'revoked'
|
|
294
|
+
subject.reference; // { source: 'registry' | 'doc_registry' | 'chip' | 'document', capturedAt } | null
|
|
295
|
+
subject.assurance; // 'registry_biometric' | 'chip_biometric' | 'document_biometric' | 'registry_only' | 'document_only' | null
|
|
296
|
+
subject.returningReady; // a returning-user session can be created now
|
|
297
|
+
subject.level; // the highest level proved: 0 | 1 | 2 | 3 (0 once revoked), null before any, absent on an older API
|
|
298
|
+
|
|
299
|
+
const recent = await sekyro.sessions.list({ externalRef: userId, status: "completed" }); // newest first, at most 100; filters re-applied client-side
|
|
300
|
+
|
|
301
|
+
const [byRef] = await sekyro.subjects.list({ externalRef: userId });
|
|
302
|
+
|
|
303
|
+
// Returning user: liveness + face match against the stored reference photo.
|
|
304
|
+
// Name exactly one of subjectId, externalRef or idNumber (nni and document are deprecated).
|
|
305
|
+
await sekyro.sessions.create({ subject: { reuse: { subjectId } } });
|
|
306
|
+
|
|
307
|
+
// The same in one call, with a mode: `recheck` (verify the same person again)
|
|
308
|
+
// or `step_up` (raise a level 1 subject to identity level). A 24-hex string is
|
|
309
|
+
// a subject id; anything else is your external reference.
|
|
310
|
+
await sekyro.subjects.createSession(userId, { mode: "step_up", flow: "identity" });
|
|
311
|
+
|
|
312
|
+
await sekyro.subjects.revoke(subjectId, { reason: "account closed" }); // idempotent
|
|
313
|
+
await sekyro.subjects.delete(subjectId); // photos, face templates and identifiers; cannot be undone
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
`subject.enrolled` (first reference photo stored), `subject.updated` (a linked
|
|
317
|
+
session finished, or `status: 'revoked'`) and `subject.deleted` webhooks are
|
|
318
|
+
typed on the envelope.
|
|
319
|
+
|
|
320
|
+
## Webhooks
|
|
321
|
+
|
|
322
|
+
Verify with the **raw** request body (bytes as received, before any JSON
|
|
323
|
+
parsing or re-serialisation) and the signature header: `x-sekyro-signature`
|
|
324
|
+
(primary), falling back to the legacy `x-ibtikar-signature` while both are
|
|
325
|
+
sent.
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
import { verifyWebhook, signatureFromHeaders, SekyroWebhookError } from "@sekyro/node";
|
|
329
|
+
|
|
330
|
+
app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), (req, res) => {
|
|
331
|
+
try {
|
|
332
|
+
const envelope = verifyWebhook(
|
|
333
|
+
req.body.toString("utf8"),
|
|
334
|
+
signatureFromHeaders(req.headers), // x-sekyro-signature, else the legacy x-ibtikar-signature
|
|
335
|
+
process.env.SEKYRO_WEBHOOK_SECRET!,
|
|
336
|
+
);
|
|
337
|
+
// The envelope is discriminated on `event`: narrowing it types `data`.
|
|
338
|
+
switch (envelope.event) {
|
|
339
|
+
case "session.completed":
|
|
340
|
+
case "session.failed":
|
|
341
|
+
envelope.data; // SessionLifecycleEventData: { sessionId, status, outcome, flow, steps, … }
|
|
342
|
+
break;
|
|
343
|
+
case "session.review_decided":
|
|
344
|
+
envelope.data; // SessionReviewDecidedEventData: { sessionId, outcome: 'pass' | 'fail', reason, flow }
|
|
345
|
+
break;
|
|
346
|
+
case "session.step.completed":
|
|
347
|
+
envelope.data; // SessionStepCompletedEventData: { sessionId, checkType, state, nodeId, service, flow }
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
res.sendStatus(200);
|
|
351
|
+
} catch (err) {
|
|
352
|
+
if (err instanceof SekyroWebhookError) return res.sendStatus(400); // invalid_signature | stale | malformed
|
|
353
|
+
throw err;
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
- The header is `t=<unix seconds>,v1=<hex>[,v1=<hex>]`. During a secret
|
|
359
|
+
rotation Sekyro AI signs with both the current and the previous secret, so the
|
|
360
|
+
delivery is accepted when **any** `v1` matches the secret you hold.
|
|
361
|
+
- **Header names.** Deliveries carry the signature in `x-sekyro-signature`
|
|
362
|
+
(`SEKYRO_SIGNATURE_HEADER`) and, for the transition, the identical legacy
|
|
363
|
+
`x-ibtikar-signature` (`LEGACY_SIGNATURE_HEADER`). `signatureFromHeaders()`
|
|
364
|
+
takes a Fetch `Headers` or a Node headers record and returns the branded
|
|
365
|
+
header, else the legacy one. The event id/type travel the same way:
|
|
366
|
+
`x-sekyro-event-id` / `x-sekyro-event-type` alongside their `x-ibtikar-*`
|
|
367
|
+
twins.
|
|
368
|
+
- Each `v1` is `HMAC-SHA256(secret, "<t>.<rawBody>")`, compared in constant time.
|
|
369
|
+
- Deliveries older or newer than `toleranceSec` (default 300 s) are rejected as
|
|
370
|
+
`stale`; pass `{ now }` to inject a clock in tests.
|
|
371
|
+
- Retried deliveries carry the same envelope `id`; de-duplicate on it.
|
|
372
|
+
|
|
373
|
+
## Result tokens
|
|
374
|
+
|
|
375
|
+
A finished session carries a short-lived ES256 JWT: `resultToken` on the
|
|
376
|
+
`session.completed` and `session.failed` webhooks, or on demand with
|
|
377
|
+
`sekyro.sessions.resultToken(id)`. Verify it against the public key set before
|
|
378
|
+
trusting it:
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
import { verifyResultToken, SekyroResultTokenError } from "@sekyro/node";
|
|
382
|
+
|
|
383
|
+
const result = await verifyResultToken(token, { appId: process.env.SEKYRO_APP_ID!, env: "live" });
|
|
384
|
+
result.level; // 0 | 1 | 2 | 3 | null (1 human, 2 identity, 3 corroborated)
|
|
385
|
+
result.assurance; // 'live_only' | 'document_biometric' | 'registry_biometric' | ...
|
|
386
|
+
result.outcome; // 'approved' | 'rejected' | ...
|
|
387
|
+
result.subjectId; // the person, when known
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
- Keys come from `https://api.sekyro.ai/.well-known/sekyro/jwks.json` and are
|
|
391
|
+
cached for 10 minutes; an unknown key id fetches the set again.
|
|
392
|
+
- `aud` must be your app id (pass an array to accept several; `result.appId`
|
|
393
|
+
says which), and the token expires 10 minutes after signing.
|
|
394
|
+
- Sandbox tokens are signed with sandbox keys (`sbx-` key ids); pass
|
|
395
|
+
`env: "live"` to refuse them in production.
|
|
396
|
+
- Failures throw `SekyroResultTokenError` with a `code`: `invalid_token`,
|
|
397
|
+
`expired`, `wrong_audience`, `wrong_issuer`, `wrong_env`,
|
|
398
|
+
`key_env_mismatch`, `jwks_unavailable` or `invalid_options`.
|
|
399
|
+
|
|
400
|
+
When the flow sets a minimum age, `result.age` is `{ over, method }` from the
|
|
401
|
+
`sekyro.age` claim: `over` is the flow's minimum age (never the person's age)
|
|
402
|
+
and `method` says how it was proved (`estimated` by the age check (selfie)
|
|
403
|
+
step, or `document`, `chip`, `registry`, `eid`). The token never carries the
|
|
404
|
+
estimated age; with the step's "Keep and show the estimated age" setting on,
|
|
405
|
+
`estimate` and `sigma` arrive on the session (`sekyro.sessions.get`) and the
|
|
406
|
+
`session.completed` / `session.failed` webhooks only. To carry the answer into
|
|
407
|
+
an identity provider, map it to the claims `sekyro_age_over` (`result.age.over`)
|
|
408
|
+
and `sekyro_age_method` (`result.age.method`).
|
|
409
|
+
|
|
410
|
+
## Connect
|
|
411
|
+
|
|
412
|
+
`@sekyro/node/connect` carries the Sekyro proof into your auth provider as one
|
|
413
|
+
small claim, `sekyro`, on the provider's user, and gates routes on it. A
|
|
414
|
+
provider package supplies the adapter that reads and writes the claim
|
|
415
|
+
(`@sekyro/connect-zitadel`, `@sekyro/connect-supabase`, `@sekyro/connect-clerk`,
|
|
416
|
+
`@sekyro/connect-auth0`, `@sekyro/connect-firebase`, `@sekyro/connect-keycloak`); any object with the
|
|
417
|
+
`ProviderAdapter` shape works too. Nothing else to install: the subpaths ship
|
|
418
|
+
inside `@sekyro/node`.
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
import { Sekyro } from "@sekyro/node";
|
|
422
|
+
import { createConnector } from "@sekyro/node/connect";
|
|
423
|
+
|
|
424
|
+
const connector = createConnector({
|
|
425
|
+
sekyro: new Sekyro({ apiKey: process.env.SEKYRO_API_KEY! }),
|
|
426
|
+
appId: process.env.SEKYRO_APP_ID!, // or an array of app ids
|
|
427
|
+
env: "live",
|
|
428
|
+
webhookSecret: process.env.SEKYRO_WEBHOOK_SECRET!,
|
|
429
|
+
provider, // from a provider package
|
|
430
|
+
onUserDeleted: "ignore", // 'ignore' | 'revoke' | 'delete'
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
// Start a verification for your user: their id becomes the session's externalRef.
|
|
434
|
+
const session = await connector.start(userId, { returnUrl, state });
|
|
435
|
+
// Store session.id with the state: the return must name this session.
|
|
436
|
+
// Later: connector.recheck(userId) or connector.stepUp(userId, { flow: "identity" }).
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
The webhook route writes the claim. Mount it on the raw body:
|
|
440
|
+
|
|
441
|
+
```ts
|
|
442
|
+
import express from "express";
|
|
443
|
+
import { SekyroResultTokenError, SekyroWebhookError } from "@sekyro/node";
|
|
444
|
+
import { SekyroConnectError } from "@sekyro/node/connect";
|
|
445
|
+
|
|
446
|
+
app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), async (req, res) => {
|
|
447
|
+
try {
|
|
448
|
+
await connector.webhook((req.body as Buffer).toString("utf8"), req.headers);
|
|
449
|
+
res.sendStatus(200);
|
|
450
|
+
} catch (err) {
|
|
451
|
+
if (err instanceof SekyroWebhookError || err instanceof SekyroResultTokenError || err instanceof SekyroConnectError) {
|
|
452
|
+
// `unavailable`: the key set is unreachable, a 503 makes Sekyro retry. Anything else is refused: 400.
|
|
453
|
+
res.status(err instanceof SekyroConnectError && err.code === "unavailable" ? 503 : 400).send(err.code);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
throw err;
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// The return URL: check `state` and the session id against the values you stored, then
|
|
461
|
+
// sync reads the session and its signed result token server-side (a session of another
|
|
462
|
+
// app, or created without one, is refused).
|
|
463
|
+
await connector.sync(userId, sessionIdFromQuery);
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
Gate a route on the claim in the session token (no network call):
|
|
467
|
+
|
|
468
|
+
```ts
|
|
469
|
+
import { requireLevel } from "@sekyro/node/connect/express";
|
|
470
|
+
|
|
471
|
+
app.get(
|
|
472
|
+
"/payouts",
|
|
473
|
+
requireLevel(connector, { level: 2, maxAgeDays: 365 }, { claims: (req) => (req as { auth?: Record<string, unknown> }).auth }),
|
|
474
|
+
handler,
|
|
475
|
+
);
|
|
476
|
+
// Fails with 403 { error: "sekyro_gate", reason, action }; action is verify | step_up | recheck | block.
|
|
477
|
+
// Next.js: sekyroGate() and gateRoute() from "@sekyro/node/connect/next".
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
The claim (unix seconds; never a name, a document number, a photo or a score):
|
|
481
|
+
|
|
482
|
+
```json
|
|
483
|
+
{ "v": 1, "level": 2, "assurance": "document_biometric", "verified_at": 1790000000, "rechecked_at": 1790003600,
|
|
484
|
+
"session_id": "<session id>", "subject_id": "<subject id>", "env": "live", "flags": ["face_mismatch"] }
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
Trust rules:
|
|
488
|
+
|
|
489
|
+
- A webhook writes only after its HMAC signature verified; retries are de-duplicated on the envelope id, which is never left recorded for a delivery whose handling failed (see the `store` contract in the guide).
|
|
490
|
+
- A key set outage while checking a result token throws `SekyroConnectError` with code `unavailable`: answer `503` so Sekyro retries, and `400` for every other refusal.
|
|
491
|
+
- When the webhook carries a result token it must verify too (audience, environment, same session, same user), and it is the source of the level, the assurance and the time.
|
|
492
|
+
- The return URL is a hint: store the session id with your `state` at start and compare both on return; `sync` then reads the session and its signed result token with your API key, verifies the token (your app ids, your environment) and refuses a session of another user, of another app or created without one.
|
|
493
|
+
- Every input goes through one merge: a failed attempt never erases a proof, a weaker proof never lowers the level, an older result never overwrites a newer one, and a result from the other environment is refused.
|
|
494
|
+
- Writes for one user are serialised: each one reads the stored claim, merges and writes it back through the adapter's optional `update` when it has one (the Firebase adapter does), otherwise under a lock per user inside the connector. That lock is per process: two server instances can still interleave for one user, and a re-check result read just before a revocation could write over it. When that matters, send the webhook route to one instance or queue its deliveries per user id.
|
|
495
|
+
- A revocation or deletion of the subject sets the level to 0 with the `revoked` flag (a claim stored without `subject_id` too, when the event's `externalRefs` include the user's id); the gate blocks `revoked` and `face_mismatch` by default. A revoked claim stays revoked: a later result of the same subject, or one without a subject id, is `revoked_ignored`; only an approved session of another subject writes a level again.
|
|
496
|
+
|
|
497
|
+
Telemetry: the six Sekyro provider packages tell Sekyro the connector is wired, so the dashboard's
|
|
498
|
+
Connectors page can show it as connected. Every API call carries an `x-sekyro-connector` header
|
|
499
|
+
(`<provider>/<version>`), and after each claim write, and each revocation the connector could not
|
|
500
|
+
resolve to a user (`revocation_unresolved`), it posts an event with ids only: the event type, the
|
|
501
|
+
provider, the session id, the subject id and the time. Never the claim, a token, a secret or user
|
|
502
|
+
data. Events go in the background with a 2-second timeout and no retry, and never slow or fail a
|
|
503
|
+
webhook. A custom adapter sends nothing. Turn both off with `telemetry: false`:
|
|
504
|
+
|
|
505
|
+
```ts
|
|
506
|
+
const connector = createConnector({ /* ... */ provider, telemetry: false });
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
Outside a connector, `new Sekyro({ apiKey, connector: { provider, version } })` sends the same header.
|
|
510
|
+
|
|
511
|
+
Revocations it cannot resolve: when Sekyro revokes or deletes a subject and the connector finds no
|
|
512
|
+
user for it (no `externalRefs`, no `store` entry), no claim is cleared and the connector logs
|
|
513
|
+
`revocation_unresolved`. Pass `onRevocationUnresolved` to act on it. The event carries ids only
|
|
514
|
+
(`subjectId`, `provider`, `reason`: `revoked` or `deleted`), never provider data. It runs after the
|
|
515
|
+
log line and telemetry event, in the background; a throw or rejection is caught and reported to
|
|
516
|
+
`logger` as `revocation_handler_failed`.
|
|
517
|
+
|
|
518
|
+
```ts
|
|
519
|
+
const connector = createConnector({
|
|
520
|
+
/* ... */
|
|
521
|
+
provider,
|
|
522
|
+
onRevocationUnresolved: async ({ subjectId, reason }) => {
|
|
523
|
+
// Find the user for subjectId and remove their access.
|
|
524
|
+
},
|
|
525
|
+
});
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
The full guide, with the Zitadel and Supabase setups, is in [Auth connectors](https://docs.sekyro.ai/en/connectors/overview).
|
|
529
|
+
|
|
530
|
+
## Compatibility
|
|
531
|
+
|
|
532
|
+
Only `node:crypto`, the global `fetch` and `jose` (result tokens) are used. You can inject a `fetch`
|
|
533
|
+
implementation via `new Sekyro({ fetch })` for tests or custom agents.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var CLAIM_VERSION=1,KNOWN_FLAGS=["face_mismatch","duplicate","revoked"];function isRecord(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function isFiniteNumber(v){return typeof v=="number"&&Number.isFinite(v)}function build(c){let out={v:1,level:c.level,assurance:c.assurance,verified_at:c.verified_at};c.rechecked_at!==void 0&&(out.rechecked_at=c.rechecked_at),out.session_id=c.session_id,c.subject_id!==void 0&&(out.subject_id=c.subject_id),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);return flags.size>0&&(out.flags=[...flags].sort()),out}function parseClaim(value){let v=value;if(typeof v=="string")try{v=JSON.parse(v)}catch{return null}if(!isRecord(v)||!isFiniteNumber(v.v))return null;if(v.v>1)return v;if(v.v!==1)return null;let level=v.level;return level!==0&&level!==1&&level!==2&&level!==3||typeof v.assurance!="string"||!isFiniteNumber(v.verified_at)||typeof v.session_id!="string"||v.env!=="live"&&v.env!=="sandbox"?null:build({level,assurance:v.assurance,verified_at:v.verified_at,rechecked_at:isFiniteNumber(v.rechecked_at)?v.rechecked_at:void 0,session_id:v.session_id,subject_id:typeof v.subject_id=="string"?v.subject_id:void 0,env:v.env,flags:Array.isArray(v.flags)?v.flags:void 0})}function toUnix(isoTime,now){let ms=Date.parse(isoTime);return Math.floor((Number.isFinite(ms)?ms:now())/1e3)}var same=(claim,rule)=>({claim,changed:!1,rule}),wrote=(claim,rule)=>({claim,changed:!0,rule});function mergeClaim(previous,event,opts){let now=opts.now??Date.now,prev=parseClaim(previous);if(prev&&prev.v>1)return same(prev,"unsupported_version");if(event.kind==="revoked"||event.kind==="deleted"){if(!prev)return same(null,"no_change");if(!(prev.subject_id===void 0?event.userInExternalRefs===!0:prev.subject_id===event.subjectId))return same(prev,"subject_mismatch");if(prev.level===0&&prev.flags?.includes("revoked"))return same(prev,"no_change");let{rechecked_at:_cleared,...kept}=prev;return wrote(build({...kept,level:0,subject_id:event.subjectId,flags:["revoked"]}),"revoked")}let r=event.result;if(r.env!==opts.env)return same(prev,"env_mismatch");let t=toUnix(r.verifiedAt,now);if(prev&&t<prev.verified_at)return same(prev,"stale_ignored");let revokedPrev=prev?.flags?.includes("revoked")===!0;if(prev&&revokedPrev&&(r.subjectId===void 0||r.subjectId===prev.subject_id))return same(prev,"revoked_ignored");if(r.outcome==="rejected"&&r.subjectConflict===!0)return!prev||prev.flags?.includes("face_mismatch")?same(prev,"no_change"):wrote(build({...prev,flags:[...prev.flags??[],"face_mismatch"]}),"face_mismatch");if(r.outcome!=="approved"||r.level===null||r.level===0)return same(prev,"not_approved");let level=r.level,assurance=r.assurance??"none",duplicate=r.duplicates===!0?["duplicate"]:[];if(!prev)return wrote(build({level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId,env:r.env,flags:duplicate}),"created");if(!revokedPrev&&(r.reuseMode==="recheck"||r.returning===!0&&level<=prev.level))return prev.rechecked_at!==void 0&&t<=prev.rechecked_at?same(prev,t<prev.rechecked_at?"stale_ignored":"no_change"):wrote(build({...prev,rechecked_at:t,subject_id:prev.subject_id??r.subjectId}),"rechecked");if(level>prev.level){let kept=(prev.flags??[]).filter(f=>f!=="face_mismatch"&&f!=="revoked");return wrote(build({...prev,level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId??prev.subject_id,flags:[...kept,...duplicate]}),"raised")}return level===prev.level&&t>prev.verified_at?wrote(build({...prev,assurance,verified_at:t,session_id:r.sessionId,subject_id:prev.subject_id??r.subjectId,flags:[...prev.flags??[],...duplicate]}),"renewed"):same(prev,"no_change")}var DEFAULT_DENY_FLAGS=["revoked","face_mismatch"],fail=(reason,action,claim)=>({ok:!1,reason,action,claim});function evaluateGate(claim,policy,nowSec=Math.floor(Date.now()/1e3)){let parsed=parseClaim(claim);if(!parsed)return fail("no_claim","verify",null);if(parsed.v>1)return fail("unsupported_version","verify",parsed);if(policy.env!==void 0&&parsed.env!==policy.env)return fail("wrong_env","verify",parsed);let deny=policy.denyFlags??DEFAULT_DENY_FLAGS;return parsed.flags?.some(f=>deny.includes(f))?fail("flagged","block",parsed):parsed.level<policy.level?fail("level_too_low",parsed.level>=1?"step_up":"verify",parsed):policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400?fail("stale","recheck",parsed):policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60?fail("recheck_stale","recheck",parsed):policy.assurance&&!policy.assurance.includes(parsed.assurance)?fail("assurance_not_allowed","step_up",parsed):{ok:!0,claim:parsed}}export{CLAIM_VERSION,parseClaim,mergeClaim,evaluateGate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{evaluateGate}from"./chunk-O5GJ3YJV.js";function sekyroGate(source,tokenClaims,policy){let claims=tokenClaims??{};if("gate"in source)return source.gate(claims,policy);let effective=source.env!==void 0&&policy.env===void 0?{...policy,env:source.env}:policy;return evaluateGate(source.provider.readClaimFromToken(claims),effective)}function gateRoute(result,routes){if(result.ok)return null;switch(result.action){case"verify":return routes.verify;case"step_up":return routes.stepUp;case"recheck":return routes.recheck;case"block":return routes.block}}export{sekyroGate,gateRoute};
|