@sekyro/node 0.1.0-rc.8 → 1.0.0-rc.15

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/README.md CHANGED
@@ -7,9 +7,8 @@ Three jobs, nothing else:
7
7
 
8
8
  1. **Sessions**: create a verification session from your backend and read its
9
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.
10
+ 2. **Webhooks**: verify the `x-sekyro-signature` header on deliveries and get
11
+ a typed envelope back.
13
12
  3. **Result tokens**: verify the signed result token of a finished session
14
13
  (`verifyResultToken`) and read its level, assurance and outcome.
15
14
 
@@ -37,7 +36,7 @@ import { Sekyro } from "@sekyro/node";
37
36
 
38
37
  const sekyro = new Sekyro({
39
38
  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
39
+ // baseUrl: "https://api.sekyro.ai/api/v2", // default, for Sandbox and Live keys: the key chooses the environment
41
40
  // timeoutMs: 30_000, // default
42
41
  });
43
42
  // Throws `SekyroConfigError` (a TypeError; `code` = 'missing_api_key' | 'invalid_base_url')
@@ -46,30 +45,43 @@ const sekyro = new Sekyro({
46
45
 
47
46
  // Create: returns the one-time client token your front end hands to @sekyro/web.
48
47
  // `flow` picks one of the app's flows (omit it for the default flow).
49
- // `input.nni` BINDS the session to that identity: the browser never sends the
50
- // NNI (a different one is refused with 409 nni_locked).
48
+ // `person.idNumber` BINDS the session to that identity: the browser never sends
49
+ // the number (a different one is refused with a 409).
51
50
  const created = await sekyro.sessions.create(
52
- { flow: "default", locale: "ar", input: { nni: "0000000098" } },
51
+ {
52
+ flow: "default",
53
+ locale: "ar",
54
+ person: { idNumber: { type: "national_id", issuingCountry: "<ISO alpha-2>", number: "<id number>" } },
55
+ },
53
56
  { idempotencyKey: `signup:${userId}` },
54
57
  );
55
- created.id; // persist against your user before returning to the page
58
+ created.id; // `ses_…`: persist against your user before returning to the page
56
59
  created.clientToken; // give this to the browser; it is returned ONCE
57
60
  created.hostedUrl; // the hosted-flow link, if you use that path instead
58
61
  created.expiresAt; // ISO 8601
59
62
  created.flow; // { id, slug, version }: the flow version the session runs
63
+ created.subjectUse; // 'reference' | 'prefill': whether the flow believes or checks your person data
60
64
 
61
65
  // Read: the whitelisted session view (never contains the client token).
62
66
  const session = await sekyro.sessions.get(created.id);
63
67
  session.status; // 'created' | 'in_progress' | 'review_pending' | 'completed' | 'expired' | 'failed'
64
- session.outcome; // 'approved' | 'review' | 'rejected' | null
68
+ session.outcome; // 'approved' | 'review' | 'rejected' | null (null on a superseded session: see `supersededBy`)
69
+ session.decidedBy; // 'automatic' | 'review' on a completed or failed session
65
70
  session.flow; // { id: 'flw_…', slug: 'default', version: 3 }: the flow version the session runs
66
- session.steps; // [{ checkType, state, nodeId?, service?, handled?, reason?, calibratedScore? }]
71
+ session.steps; // [{ id, service, state, handled?, reason?, calibratedScore?, decision? }]
72
+ session.personId; // 'per_…' once the person passed a verification
73
+ session.identity; // what the session read: names, birth date, document, sources (see Identity data and media)
74
+ session.media; // the media kinds it has: ['document_front', 'selfie', …]
67
75
  ```
68
76
 
77
+ Ids are prefixed: `ses_` sessions, `per_` people, `flw_` flows. Every route also
78
+ accepts the bare 24 hexadecimal characters, so an id you stored before keeps
79
+ working.
80
+
69
81
  Your API key belongs to an **app**. The app's **flows**, designed in the Sekyro AI
70
82
  dashboard (app page → **Flows**), decide which steps run; a session runs the
71
83
  flow you name in `flow`, or the app's default flow. To list the published flows
72
- of the key's app, call `sekyro.listFlows()`: it resolves to
84
+ of the key's app, call `sekyro.flows.list()`: it resolves to
73
85
  `FlowSummary[]` (`[{ id, slug, name, version, isDefault }]`), the default flow
74
86
  first (`GET /api/v2/flows` under the hood, scope `sessions:create`;
75
87
  see the [quickstart](https://docs.sekyro.ai/en/getting-started/quickstart#choose-a-flow)).
@@ -81,14 +93,14 @@ Every field is optional:
81
93
  | `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) |
82
94
  | `locale` | `ar`, `fr` or `en`: pins the hosted-flow language |
83
95
  | `ttlMinutes` | session lifetime, within the flow's link range (`400 ttl_out_of_policy` otherwise); omit for the flow default |
84
- | `input` | the step anchors: `nni`, `phone`, `email`, `fullName`, `birthDate`, all **strings** (an NNI is a 10-digit string, never a number), plus any further keys (flow branches can read them); `input.nni` binds the session to that identity |
85
- | `subject` | what you know about the person (`nni`, `phone`, `fullName`, `birthDate`, `nationality`, `documentNumber`), your own id for them (`externalRef`), or `reuse` for a [returning user](#subjects) |
96
+ | `person` | what you know about the person: `idNumber` (`{ type, issuingCountry, number }`, binds the session), `fullName`, `names` (per script), `birthDate`, `birthPlace` (a string or `[{ script, value }]`), `sex`, `nationalities`, `document` (`{ type, issuingCountry, number }`, compared with the capture), `phone`, `email`, and for a reference record `photo`, `photoDate`, `fetchedAt`; your own id for them (`externalRef`), or `reuse` for a [returning user](#people). The flow decides whether the data is checked or believed (`created.subjectUse`) |
97
+ | `input` | an open record of branch facts your flow's conditions read; facts about the person go in `person` |
86
98
  | `identityMethod` | `national_number`, `document_photo`, `document_chip` or `national_eid`: pre-chooses the option of the flow's identity choice |
87
99
  | `deliver` | `{ channel: "sms" \| "whatsapp", to: "+1555…" }`: also send the hosted link to the person |
88
100
 
89
101
  ```ts
90
102
  // The app's flows (published only, default first): pick one at runtime.
91
- const flows = await sekyro.listFlows(); // [{ id, slug, name, version, isDefault }]
103
+ const flows = await sekyro.flows.list(); // [{ id, slug, name, version, isDefault }]
92
104
 
93
105
  await sekyro.sessions.create({
94
106
  flow: "foreigners",
@@ -106,67 +118,169 @@ changes a service's settings, keyed by service id (`liveness`, `phone_otp`,
106
118
  the flow stricter unless the flow allows widening; turning a service `'off'`
107
119
  always widens. The changed paths come back on `session.overriddenFields`.
108
120
 
109
- > **Sekyro flows breaking change.** The `profile` override is gone: use
110
- > `overrides`. `flow` is accepted again, now as the app's flow slug or id.
121
+ `flow` takes the app's flow slug or id.
111
122
 
112
123
  The session view also carries `failureReason` (a policy stop such as
113
124
  `location_not_allowed` or `underage`), `failureDetail` (why, when that reason
114
125
  is `camera_unavailable`: `denied` or `no_camera`), `overriddenFields`, `riskSignals`,
115
- `subjectId` / `externalRef`, `verifiedContacts`, `eid`, and the end user's
126
+ `personId` / `externalRef`, `verifiedContacts`, `eid`, and the end user's
116
127
  `network` and `device`. A step with `handled: true` failed, but the flow's
117
128
  fallback took over.
118
129
 
119
- Two more session calls:
130
+ More session calls:
120
131
 
121
132
  - `sekyro.sessions.selectMethod(id, method)` chooses the identity method of a
122
133
  session on the person's behalf (`POST /sessions/:id/method`): `409 choice_locked`
123
134
  once the flow's identity choice can no longer change, `409 choice_option_unavailable`
124
135
  for a method the flow does not offer this session, `409 choice_not_found` when the
125
136
  flow has no identity choice.
126
- - `sekyro.sessions.portrait(id)` returns a 5-minute link to the ICAO portrait of
127
- a session whose `portrait_icao` check passed (`portraitAvailable`; scope
128
- `portrait:read`).
137
+ - `sekyro.sessions.cancel(id)` stops a session that has not ended: the hosted link
138
+ stops working and one `session.failed` with `failureReason: 'cancelled_by_organization'`
139
+ is sent (`409 session_not_cancellable` once it ended).
140
+ - `sekyro.sessions.resendLink(id)` sends the hosted link again through the session's own
141
+ `deliver` channel, to the same destination; `sekyro.sessions.extendLink(id, { ttlMinutes })`
142
+ (or `{ expiresAt }`) gives the link a later expiry within the flow's bounds. Both need a
143
+ session created with `deliver` (`409 link_not_deliverable` otherwise).
144
+ - `sekyro.sessions.list(query)` returns the first page of your sessions, newest first
145
+ (50 by default, up to 100 with `limit`), filtered by `externalRef`, `status`, `flow`,
146
+ `createdAfter` and `createdBefore`. `sessions.iterate(query)` reads every page;
147
+ `sessions.listPage(query)` returns one page and its `nextCursor`.
148
+
149
+ ```ts
150
+ for await (const s of sekyro.sessions.iterate({ externalRef: userId, status: "completed" })) {
151
+ s.id; // newest first, page after page
152
+ }
153
+ ```
154
+
155
+ ### Test in the Sandbox
156
+
157
+ A `sk_test_…` key runs on the same API as a `sk_live_…` key; the key chooses the
158
+ environment. `sekyro.me()` tells you which key you hold, and
159
+ `sekyro.sessions.simulate()` finishes a simulated session in one call, for tests
160
+ and CI. It runs the real engine, so the webhooks, the result token and the
161
+ dashboard behave as for a session driven by a person. It is never billed.
162
+
163
+ ```ts
164
+ const me = await sekyro.me();
165
+ // { env: "sandbox", keyPrefix, scopes, app: { id, slug, name }, org: { name } }
166
+
167
+ const { id } = await sekyro.sessions.create({ person: { externalRef: "<your user id>" } });
168
+ const session = await sekyro.sessions.simulate(
169
+ id,
170
+ { outcome: "rejected", reason: "spoof_detected" }, // or "approved", "review"
171
+ { idempotencyKey: "<your CI run id>" },
172
+ );
173
+ ```
174
+
175
+ `reason` is optional and goes only with `rejected`. Errors: `400 sandbox_only`
176
+ (a Live key), `409 session_not_simulated` (bound to a tester),
177
+ `409 session_already_final`, `422 simulate_outcome_unreachable` (the flow cannot
178
+ reach this outcome; `details.issues` says why) and `422 simulate_reason_invalid`.
179
+ See the [Sandbox guide](https://docs.sekyro.ai/en/getting-started/sandbox).
180
+
181
+ ### Identity data and media
182
+
183
+ `session.identity` holds what the session read, with the source of every value:
184
+ one `names[]` entry per source and script (`form`: `mrz`, `printed`, `chip`,
185
+ `registry`, `eid` or `supplied`), `birthDate`, `birthPlace[]`, `sex`,
186
+ `nationalities`, `idNumber`, `document` and `sources` (which sources agree on
187
+ each value). It is present once an identity step settled, whatever the outcome,
188
+ and it rides on `session.completed` and `session.failed` when that is enabled
189
+ for your organization.
190
+
191
+ ```ts
192
+ const { items } = await sekyro.sessions.media(id); // [{ kind, check, attempt?, decisive, contentType, url, expiresAt }]
193
+ const { contentType, bytes } = await sekyro.sessions.mediaBytes(id, "reference_portrait");
194
+ await sekyro.sessions.mediaBytes(id, "liveness_clip", { attempt: 2 });
195
+ ```
196
+
197
+ `url` is a download link valid 15 minutes, or the bytes route on this API (read
198
+ it with `mediaBytes`, which sends your key). Both need `sessions:read`. The
199
+ ICAO portrait is the `icao_portrait` media item.
129
200
 
130
201
  `sekyro.sessions` is a `SessionsApi`, exported as a type only: you get the
131
202
  instance from the client, never by constructing one.
132
203
 
133
- ### Partner-supplied identity data (`supplied` mode)
204
+ ### Person data
205
+
206
+ Send what you know about the person in `person`: `idNumber`
207
+ (`{ type, issuingCountry, number }`), `fullName` or `names` (given, family and
208
+ patronymic per ISO 15924 script), `birthDate`, `birthPlace` (a string or
209
+ `[{ script, value }]`), `sex`, `nationalities`, `document`
210
+ (`{ type, issuingCountry, number }`), `phone`, `email`, and for a flow that
211
+ verifies identity from your data, `photo` and `fetchedAt`.
212
+ The session's flow decides how Sekyro AI uses it, never the request: when a step
213
+ reads partner-supplied data (a Partner-supplied identity step on the session's
214
+ path, available in every environment), the record is the **reference** to believe; otherwise it is a
215
+ **prefill** checked against what the person shows. `created.subjectUse` says
216
+ which (`"reference"` or `"prefill"`). The rules, the trust table and every
217
+ error are on the [Person data](https://docs.sekyro.ai/en/guides/person-data)
218
+ page.
134
219
 
135
- If Sekyro AI set your environment to the `supplied` mode, you send the
136
- person's identity data (biographic record and photo) with the session in
137
- `input.suppliedIdentity`. Sekyro AI treats it as identity data supplied by
138
- your organization: it makes no registry call, and it never receives or stores
139
- any registry key. If your data comes from your own call to the national
140
- population registry, `registryFromAnrpts()` converts that answer locally into
141
- the record shape:
220
+ ```ts
221
+ // A prefill: the flow checks it against the registry or the document.
222
+ await sekyro.sessions.create({
223
+ person: {
224
+ externalRef: userId,
225
+ idNumber: { type: "passport", issuingCountry: "<ISO alpha-2>", number: "<id number>" },
226
+ birthDate: "<YYYY-MM-DD>",
227
+ },
228
+ });
229
+ ```
230
+
231
+ If your data comes from your own call to a national registry,
232
+ `personFromNationalRegistry()` converts that answer locally into the
233
+ reference keys. Sekyro AI treats the result as identity data supplied by your
234
+ organization: it makes no registry call and needs no registry key.
142
235
 
143
236
  ```ts
144
- import { registryFromAnrpts } from "@sekyro/node";
237
+ import { personFromNationalRegistry } from "@sekyro/node";
145
238
 
146
- const answer = await myRegistryClient.lookup(nni); // your call, your key
239
+ const answer = await myRegistryClient.lookup(idNumber); // your call, your key
147
240
  const receivedAt = new Date();
148
- await sekyro.sessions.create({
149
- // fetchedAt: when YOUR system received this answer (required; > 24 h old is refused)
150
- input: { nni, suppliedIdentity: registryFromAnrpts(answer, { fetchedAt: receivedAt }) },
241
+ const created = await sekyro.sessions.create({
242
+ person: {
243
+ externalRef: userId,
244
+ // fetchedAt: when YOUR system received this answer (required; > 24 h old is refused)
245
+ ...personFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }),
246
+ },
151
247
  });
248
+ created.subjectUse; // "reference" when the flow has a Partner-supplied identity step
152
249
  ```
153
250
 
154
- `suppliedIdentity.nni` must equal `input.nni`. Refusals:
155
- `403 supplied_identity_not_entitled` (the environment is not in `supplied` mode),
156
- `422 supplied_identity_required` (the environment is in `supplied` mode and the app
157
- verifies identity, but `input.suppliedIdentity` was not sent),
158
- `400 supplied_identity_nni_mismatch`, `422 supplied_identity_stale` (obtained more
159
- than 24 h ago) and `422 supplied_identity_photo_unusable` (not a JPEG or PNG of at
160
- most 1 MB within the size bounds).
251
+ The first argument is the registry's country (ISO alpha-2) and types the
252
+ answer: `"MR"` takes the ANRPTS `getPersonne` answer
253
+ (`AnrptsPersonneResponse`). The result is a `PersonRecord`: `idNumber`,
254
+ `names` (one entry per script found), `birthDate`, `birthPlace`, `sex`,
255
+ `nationalities` (`[code]`, alpha-2), `photo`, `photoDate` and `fetchedAt`. A
256
+ record without a number, a birth date, a photo or any name, or with an invalid `fetchedAt`,
257
+ throws `SekyroConfigError` `invalid_registry_record` naming the field (never
258
+ its value); a country without an adapter throws `registry_country_unsupported`.
259
+ An answer that states a nationality none of whose values the SDK can map throws
260
+ `registry_nationality_unmapped` (the message never carries the value): map it
261
+ yourself and pass `options.nationality` (ISO alpha-2), so the stated nationality
262
+ is never dropped.
263
+
264
+ Refusals of a reference, in this order: `422 subject_record_incomplete`
265
+ (`error.details.fields` names the missing keys), `422 subject_record_stale`
266
+ (obtained more than 24 h ago, or more than 5 min ahead) and
267
+ `422 subject_photo_unusable` (not a JPEG or PNG of at most 1 MB within the size
268
+ bounds). A `photo` on a session that cannot use it (a prefill, a returning
269
+ user) answers `422 subject_photo_not_used`.
161
270
 
162
271
  No face processing runs at create. The face on the supplied photo is checked after
163
272
  the person consents, at the face match: a photo without one usable face fails that
164
273
  step with `no_face_reference` (or `low_quality_reference`). That step runs after liveness, so check
165
274
  that the photo shows exactly one clear face before you send it.
166
275
 
167
- Partner-supplied identity data is not billed: the identity step in `supplied` mode
276
+ Partner-supplied identity data is not billed: the Partner-supplied identity step
168
277
  records no usage event (other steps, such as the face match, bill as usual).
169
278
 
279
+ The step reasons and codes about the number are `registry_record_not_found`,
280
+ `id_number_invalid`, `id_number_locked`, `document_id_number_mismatch` and
281
+ `sandbox_id_number_not_seeded`. See
282
+ [Person data](https://docs.sekyro.ai/en/guides/person-data).
283
+
170
284
  ### Errors
171
285
 
172
286
  Every non-2xx response, network failure and timeout throws `SekyroApiError`:
@@ -176,18 +290,20 @@ Every non-2xx response, network failure and timeout throws `SekyroApiError`:
176
290
  | `status` | HTTP status (`0` for network / timeout) |
177
291
  | `code` | API error code, or `network` / `timeout` / `http_error` / `malformed_response` |
178
292
  | `message` | human-readable, from the API when available |
179
- | `requestId` | the API's `request_id`, quote it to support |
293
+ | `requestId` | the API's `requestId`, quote it to support |
180
294
  | `details` | the API's `error.details` when sent, else `undefined`; typed for the flow codes through `isFlowError()` |
295
+ | `fieldErrors` | on a `validation_error`, the refused fields as `[{ field, code, expected? }]` (`field` is a dotted path such as `person.phone`, `expected` says what a picklist or literal accepts, such as `"ar" | "fr" | "en"`; `code` `unknown_field` marks a key the API does not accept, on the object that holds it), else `undefined`. Never a value you sent, never an unknown key |
181
296
  | `retryable` | `true` for `network`, `timeout`, `429`, `5xx` and `idempotency_in_progress` |
297
+ | `retryAfterSeconds` | seconds to wait from the response's `Retry-After` header (seconds or an HTTP date), else `undefined` |
182
298
 
183
299
  ```ts
184
300
  import { SekyroApiError } from "@sekyro/node";
185
301
 
186
302
  try {
187
- await sekyro.sessions.create({ input: { nni } });
303
+ await sekyro.sessions.create({ person: { idNumber } });
188
304
  } catch (err) {
189
305
  if (err instanceof SekyroApiError && err.retryable) {
190
- // back off and retry with the SAME idempotencyKey
306
+ // wait err.retryAfterSeconds when set, else back off; retry with the SAME idempotencyKey
191
307
  }
192
308
  }
193
309
  ```
@@ -206,7 +322,7 @@ returns `false` when the details are missing or not in that shape, so read
206
322
  | `409 flow_not_published`, `409 flow_archived` | `sessions.create` | `issues`, `flow` |
207
323
  | `400 override_invalid` | `sessions.create` | `issues`, one per problem (`path: "overrides.services.liveness.attempts"`, …) |
208
324
  | `403 override_widens_flow` | `sessions.create` | `issues` (`field_widens_flow`), `fields` |
209
- | `409 reuse_disabled` | `sessions.create` with `subject.reuse` | `issues`, `flow` |
325
+ | `409 reuse_disabled` | `sessions.create` with `person.reuse` | `issues`, `flow` |
210
326
  | `409 choice_not_found`, `choice_locked`, `choice_option_unavailable` | `sessions.selectMethod` | `issues` |
211
327
 
212
328
  ```ts
@@ -223,48 +339,52 @@ try {
223
339
  }
224
340
  ```
225
341
 
226
- ## Subjects
342
+ ## People
227
343
 
228
- A **subject** is the same person across all of your apps. Reads need the
229
- `subjects:read` scope; `revoke` and `delete` need `subjects:write` (keys minted
230
- from the dashboard carry both; mint a new key if an older one answers
344
+ A **person** is the same person across all of your apps (`per_…` ids). Reads
345
+ need the `people:read` scope; `revoke` and `delete` need `people:write` (keys
346
+ minted from the dashboard carry both; mint a new key if one answers
231
347
  `403 insufficient_scope`).
232
348
 
233
349
  ```ts
234
- const subject = await sekyro.subjects.get(subjectId);
235
- subject.status; // 'active' | 'revoked'
236
- subject.reference; // { source: 'registry' | 'doc_registry' | 'chip' | 'document', capturedAt } | null
237
- subject.assurance; // 'registry_biometric' | 'chip_biometric' | 'document_biometric' | 'registry_only' | 'document_only' | null
238
- subject.returningReady; // a returning-user session can be created now
239
- subject.level; // the highest level proved: 0 | 1 | 2 | 3 (0 once revoked), null before any, absent on an older API
240
-
241
- const recent = await sekyro.sessions.list({ externalRef: userId, status: "completed" }); // newest first, at most 100; filters re-applied client-side
350
+ const person = await sekyro.people.get(personId);
351
+ person.status; // 'active' | 'revoked'
352
+ person.reference; // { source: 'registry' | 'doc_registry' | 'chip' | 'document', capturedAt } | null
353
+ person.assurance; // 'registry_biometric' | 'chip_biometric' | 'document_biometric' | 'registry_only' | 'document_only' | null
354
+ person.returningReady; // a returning-user session can be created now
355
+ person.level; // the highest level proved: 0 | 1 | 2 | 3 (0 once revoked), null before any
356
+ person.identity; // the identity of the latest approved session that read one
242
357
 
243
- const [byRef] = await sekyro.subjects.list({ externalRef: userId });
358
+ const [byRef] = await sekyro.people.list({ externalRef: userId }); // first page, newest first
359
+ for await (const p of sekyro.people.iterate()) p.id; // every page
244
360
 
245
361
  // Returning user: liveness + face match against the stored reference photo.
246
- // Name exactly one of subjectId, externalRef or nni.
247
- await sekyro.sessions.create({ subject: { reuse: { subjectId } } });
362
+ // Name exactly one of personId (the person id), externalRef or idNumber.
363
+ await sekyro.sessions.create({ person: { reuse: { personId } } });
248
364
 
249
365
  // The same in one call, with a mode: `recheck` (verify the same person again)
250
- // or `step_up` (raise a level 1 subject to identity level). A 24-hex string is
251
- // a subject id; anything else is your external reference.
252
- await sekyro.subjects.createSession(userId, { mode: "step_up", flow: "identity" });
366
+ // or `step_up` (raise a level 1 person to identity level). A person id (`per_…`
367
+ // or 24 hexadecimal characters) names the person; anything else is your external reference.
368
+ await sekyro.people.createSession(userId, { mode: "step_up", flow: "identity" });
253
369
 
254
- await sekyro.subjects.revoke(subjectId, { reason: "account closed" }); // idempotent
255
- await sekyro.subjects.delete(subjectId); // photos, face templates and identifiers; cannot be undone
370
+ await sekyro.people.revoke(personId, { reason: "account closed" }); // idempotent
371
+ await sekyro.people.delete(personId); // photos, face templates, identifiers and their sessions' data; cannot be undone
256
372
  ```
257
373
 
258
- `subject.enrolled` (first reference photo stored), `subject.updated` (a linked
259
- session finished, or `status: 'revoked'`) and `subject.deleted` webhooks are
260
- typed on the envelope.
374
+ A person is visible once they have passed a verification. A person who never
375
+ passed, an unknown id and a person of another organization or environment all
376
+ answer the same `404 subject_not_found` on `get`, `revoke` and `delete`, and
377
+ `list` leaves them out (the list can be empty while sessions with that
378
+ `externalRef` exist).
379
+
380
+ `person.enrolled` (first reference photo stored), `person.updated` (a linked
381
+ session finished, or `status: 'revoked'`) and `person.deleted` webhooks are
382
+ typed on the envelope, with `personId`.
261
383
 
262
384
  ## Webhooks
263
385
 
264
386
  Verify with the **raw** request body (bytes as received, before any JSON
265
- parsing or re-serialisation) and the signature header: `x-sekyro-signature`
266
- (primary), falling back to the legacy `x-ibtikar-signature` while both are
267
- sent.
387
+ parsing or re-serialisation) and the signature header, `x-sekyro-signature`.
268
388
 
269
389
  ```ts
270
390
  import { verifyWebhook, signatureFromHeaders, SekyroWebhookError } from "@sekyro/node";
@@ -273,20 +393,21 @@ app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), (req, re
273
393
  try {
274
394
  const envelope = verifyWebhook(
275
395
  req.body.toString("utf8"),
276
- signatureFromHeaders(req.headers), // x-sekyro-signature, else the legacy x-ibtikar-signature
396
+ signatureFromHeaders(req.headers), // the x-sekyro-signature header
277
397
  process.env.SEKYRO_WEBHOOK_SECRET!,
278
398
  );
279
399
  // The envelope is discriminated on `event`: narrowing it types `data`.
280
400
  switch (envelope.event) {
281
401
  case "session.completed":
282
402
  case "session.failed":
283
- envelope.data; // SessionLifecycleEventData: { sessionId, status, outcome, flow, steps, … }
403
+ // The one terminal event of a session: { sessionId, status, outcome, decidedBy, decision?, flow, steps, identity?, media?, … }
404
+ envelope.data; // SessionLifecycleEventData
284
405
  break;
285
- case "session.review_decided":
286
- envelope.data; // SessionReviewDecidedEventData: { sessionId, outcome: 'pass' | 'fail', reason, flow }
406
+ case "session.superseded":
407
+ envelope.data; // SessionSupersededEventData: { sessionId, supersededBy, reason: 'superseded_by_retry' }
287
408
  break;
288
- case "session.step.completed":
289
- envelope.data; // SessionStepCompletedEventData: { sessionId, checkType, state, nodeId, service, flow }
409
+ case "person.updated":
410
+ envelope.data; // PersonUpdatedEventData: { personId, status, externalRefs, … }
290
411
  break;
291
412
  }
292
413
  res.sendStatus(200);
@@ -301,17 +422,41 @@ app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), (req, re
301
422
  rotation Sekyro AI signs with both the current and the previous secret, so the
302
423
  delivery is accepted when **any** `v1` matches the secret you hold.
303
424
  - **Header names.** Deliveries carry the signature in `x-sekyro-signature`
304
- (`SEKYRO_SIGNATURE_HEADER`) and, for the transition, the identical legacy
305
- `x-ibtikar-signature` (`LEGACY_SIGNATURE_HEADER`). `signatureFromHeaders()`
306
- takes a Fetch `Headers` or a Node headers record and returns the branded
307
- header, else the legacy one. The event id/type travel the same way:
308
- `x-sekyro-event-id` / `x-sekyro-event-type` alongside their `x-ibtikar-*`
309
- twins.
425
+ (`SEKYRO_SIGNATURE_HEADER`). `signatureFromHeaders()` takes a Fetch `Headers`
426
+ or a Node headers record and returns it. The event id and type travel in
427
+ `x-sekyro-event-id` and `x-sekyro-event-type`.
310
428
  - Each `v1` is `HMAC-SHA256(secret, "<t>.<rawBody>")`, compared in constant time.
311
429
  - Deliveries older or newer than `toleranceSec` (default 300 s) are rejected as
312
430
  `stale`; pass `{ now }` to inject a clock in tests.
313
431
  - Retried deliveries carry the same envelope `id`; de-duplicate on it.
314
432
 
433
+ ### Review decisions
434
+
435
+ When a person decides a step, the step carries `decision`
436
+ (`SessionStepDecision`) on `sekyro.sessions.get` and on the `steps` of the
437
+ `session.*` webhooks, and `session.completed` / `session.failed` carry it at the
438
+ top level with `decidedBy: 'review'`:
439
+ `{ source, mode, votes, agreement?, reasons, decidedAt, sessionId? }`.
440
+ `source` is `review` (a reviewer) or `prior_review` (an earlier review of the
441
+ same person, reference photo and face was reused; `sessionId` names your
442
+ earlier session). `mode` is `single` or `dual`, `votes` counts the votes that
443
+ formed it and `agreement` says whether two dual reviewers agreed. `reasons`
444
+ (`ReviewReason[]`: `document_authenticity`, `liveness`, `face_match`,
445
+ `data_mismatch`, `screening`, `org_rule`, `other`) says what failed on a rejection, or what was
446
+ overridden on an approval. The object never names a reviewer or a vote.
447
+
448
+ A review that reaches its deadline ends with `session.failed`, `decidedBy:
449
+ 'automatic'` and `failureReason: 'review_timeout'`, or `review_split` when two
450
+ reviewers disagreed and nobody settled it; those carry no `decision`.
451
+
452
+ Reason codes of these paths: `prior_review_approved` and
453
+ `prior_review_rejected` on a face match settled by an earlier review
454
+ (`PriorReviewReason`), and `superseded_by_retry` and `review_split` on any
455
+ reviewed step (`ReviewOutcomeReason`). A session that waited for a review ends
456
+ with `outcome: null` and `supersededBy` when a newer attempt of the same person
457
+ takes the review over: `session.superseded`, its one terminal event, names the
458
+ newer session in `supersededBy`.
459
+
315
460
  ## Result tokens
316
461
 
317
462
  A finished session carries a short-lived ES256 JWT: `resultToken` on the
@@ -322,21 +467,26 @@ trusting it:
322
467
  ```ts
323
468
  import { verifyResultToken, SekyroResultTokenError } from "@sekyro/node";
324
469
 
325
- const result = await verifyResultToken(token, { appId: process.env.SEKYRO_APP_ID!, env: "live" });
470
+ const result = await verifyResultToken(token, {
471
+ appId: process.env.SEKYRO_APP_ID!,
472
+ // Required. Set SEKYRO_ENV to "sandbox" while you integrate and to "live" at go-live.
473
+ env: process.env.SEKYRO_ENV as "live" | "sandbox",
474
+ });
326
475
  result.level; // 0 | 1 | 2 | 3 | null (1 human, 2 identity, 3 corroborated)
327
476
  result.assurance; // 'live_only' | 'document_biometric' | 'registry_biometric' | ...
328
477
  result.outcome; // 'approved' | 'rejected' | ...
329
- result.subjectId; // the person, when known
478
+ result.personId; // the person id (per_…), when known
330
479
  ```
331
480
 
332
481
  - Keys come from `https://api.sekyro.ai/.well-known/sekyro/jwks.json` and are
333
482
  cached for 10 minutes; an unknown key id fetches the set again.
334
483
  - `aud` must be your app id (pass an array to accept several; `result.appId`
335
484
  says which), and the token expires 10 minutes after signing.
336
- - Sandbox tokens are signed with sandbox keys (`sbx-` key ids); pass
337
- `env: "live"` to refuse them in production.
485
+ - `env` is required: `"live"` or `"sandbox"`. A token from the other
486
+ environment throws `wrong_env`, so a Sandbox token (signed with an `sbx-` key)
487
+ never passes in production. A missing or other value throws `env_required`.
338
488
  - Failures throw `SekyroResultTokenError` with a `code`: `invalid_token`,
339
- `expired`, `wrong_audience`, `wrong_issuer`, `wrong_env`,
489
+ `expired`, `wrong_audience`, `wrong_issuer`, `wrong_env`, `env_required`,
340
490
  `key_env_mismatch`, `jwks_unavailable` or `invalid_options`.
341
491
 
342
492
  When the flow sets a minimum age, `result.age` is `{ over, method }` from the
@@ -345,9 +495,22 @@ and `method` says how it was proved (`estimated` by the age check (selfie)
345
495
  step, or `document`, `chip`, `registry`, `eid`). The token never carries the
346
496
  estimated age; with the step's "Keep and show the estimated age" setting on,
347
497
  `estimate` and `sigma` arrive on the session (`sekyro.sessions.get`) and the
348
- `session.completed` / `session.failed` webhooks only. To carry the answer into
349
- an identity provider, map it to the claims `sekyro_age_over` (`result.age.over`)
350
- and `sekyro_age_method` (`result.age.method`).
498
+ `session.completed` / `session.failed` webhooks only. The connectors
499
+ (`@sekyro/node/connect`, see [Connect](#connect)) carry the answer into your
500
+ auth provider as `age_over` and `age_method` in the `sekyro` claim.
501
+
502
+ `result.decision` is the `sekyro.decision` claim (`ResultDecision`, the same
503
+ fields as a step's `decision`), when a person decided a step of the session.
504
+ `result.failureIdentification` is the `sekyro.failure_identification` claim
505
+ (`FailureIdentification`), when the flow's identify-failures setting is on and
506
+ the search found a match: `{ kind, scope, match: { personId?, reference?,
507
+ photoId?, tier, score, band }, referenceSource? }`. The same object is the
508
+ `failureIdentification` field of the session and of the terminal webhooks. It
509
+ is a signal, never a decision. `kind: 'other_identity'` is informational only:
510
+ the registry also knows this face under another record, and the person may
511
+ legitimately hold more than one identity document, for example a foreign
512
+ passport, an older document, a second nationality or a residence permit. Do
513
+ not treat this signal alone as fraud: use it as a lead for your own process.
351
514
 
352
515
  ## Connect
353
516
 
@@ -419,13 +582,23 @@ app.get(
419
582
  // Next.js: sekyroGate() and gateRoute() from "@sekyro/node/connect/next".
420
583
  ```
421
584
 
422
- The claim (unix seconds; never a name, a document number, a photo or a score):
585
+ The claim (unix seconds; never a name, a document number, a photo, a score, a birth date or an estimated age):
423
586
 
424
587
  ```json
425
588
  { "v": 1, "level": 2, "assurance": "document_biometric", "verified_at": 1790000000, "rechecked_at": 1790003600,
426
- "session_id": "<session id>", "subject_id": "<subject id>", "env": "live", "flags": ["face_mismatch"] }
589
+ "session_id": "<session id>", "subject_id": "<person id>", "env": "live", "flags": ["face_mismatch"],
590
+ "age_over": 18, "age_method": "document" }
427
591
  ```
428
592
 
593
+ `age_over` and `age_method` appear once a session of a flow with a minimum age
594
+ proved it: the flow's minimum age and how (`estimated`, or `document`, `chip`,
595
+ `registry`, `eid`). The claim keeps the stronger proof of the same person (a
596
+ birth date from identity data beats an estimate, then the higher minimum age).
597
+ Gate on it with `minAge`, and `ageMethods` when the route needs a proven birth
598
+ date: `{ level: 1, minAge: 18, ageMethods: ["document", "chip", "registry", "eid"] }`
599
+ fails with `age_not_proven` (action `verify`) or `age_method_not_allowed`
600
+ (action `step_up`).
601
+
429
602
  Trust rules:
430
603
 
431
604
  - 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).
@@ -434,7 +607,38 @@ Trust rules:
434
607
  - 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.
435
608
  - 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.
436
609
  - 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.
437
- - 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.
610
+ - A revocation or deletion of the person (`person.updated` with `status: 'revoked'`, `person.deleted`) 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 person, or one without a person id, is `revoked_ignored`; only an approved session of another person writes a level again.
611
+
612
+ Telemetry: the six Sekyro provider packages tell Sekyro the connector is wired, so the dashboard's
613
+ Connectors page can show it as connected. Every API call carries an `x-sekyro-connector` header
614
+ (`<provider>/<version>`), and after each claim write, and each revocation the connector could not
615
+ resolve to a user (`revocation_unresolved`), it posts an event with ids only: the event type, the
616
+ provider, the session id, the person id and the time. Never the claim, a token, a secret or user
617
+ data. Events go in the background with a 2-second timeout and no retry, and never slow or fail a
618
+ webhook. A custom adapter sends nothing. Turn both off with `telemetry: false`:
619
+
620
+ ```ts
621
+ const connector = createConnector({ /* ... */ provider, telemetry: false });
622
+ ```
623
+
624
+ Outside a connector, `new Sekyro({ apiKey, connector: { provider, version } })` sends the same header.
625
+
626
+ Revocations it cannot resolve: when Sekyro revokes or deletes a person and the connector finds no
627
+ user for it (no `externalRefs`, no `store` entry), no claim is cleared and the connector logs
628
+ `revocation_unresolved`. Pass `onRevocationUnresolved` to act on it. The event carries ids only
629
+ (`personId`, `provider`, `reason`: `revoked` or `deleted`), never provider data. It runs after the
630
+ log line and telemetry event, in the background; a throw or rejection is caught and reported to
631
+ `logger` as `revocation_handler_failed`.
632
+
633
+ ```ts
634
+ const connector = createConnector({
635
+ /* ... */
636
+ provider,
637
+ onRevocationUnresolved: async ({ personId, reason }) => {
638
+ // Find the user for personId and remove their access.
639
+ },
640
+ });
641
+ ```
438
642
 
439
643
  The full guide, with the Zitadel and Supabase setups, is in [Auth connectors](https://docs.sekyro.ai/en/connectors/overview).
440
644
 
@@ -1 +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};
1
+ import{evaluateGate}from"./chunk-J6U2QY7M.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};
@@ -0,0 +1 @@
1
+ var CLAIM_VERSION=1,KNOWN_FLAGS=["face_mismatch","duplicate","revoked"],AGE_METHODS=["estimated","document","chip","registry","eid"];function ageProofOf(over,method){if(!(typeof over!="number"||!Number.isInteger(over)||over<=0)&&!(typeof method!="string"||!AGE_METHODS.includes(method)))return{over,method}}var ageRank=a=>a.method==="estimated"?0:1;function strongerAge(stored,next){if(!stored)return next;if(!next)return stored;let r=ageRank(next)-ageRank(stored);return r!==0?r>0?next:stored:next.over>stored.over?next:stored}var sameAge=(a,b)=>a?.over===b?.over&&a?.method===b?.method;function canonicalId(id){return id.replace(/^(ses|per)_/,"")}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=canonicalId(c.subject_id)),out.env=c.env;let flags=new Set;for(let f of c.flags??[])KNOWN_FLAGS.includes(f)&&flags.add(f);flags.size>0&&(out.flags=[...flags].sort());let age=ageProofOf(c.age_over,c.age_method);return age&&(out.age_over=age.over,out.age_method=age.method),out}function ageFields(age){return{age_over:age?.over,age_method:age?.method}}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,age_over:v.age_over,age_method:v.age_method})}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===canonicalId(event.subjectId)))return same(prev,"subject_mismatch");if(prev.level===0&&prev.flags?.includes("revoked"))return same(prev,"no_change");let{rechecked_at:_cleared,age_over:_over,age_method:_method,...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||canonicalId(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"]:[],nextAge=r.age?ageProofOf(r.age.over,r.age.method):void 0;if(!prev)return wrote(build({level,assurance,verified_at:t,session_id:r.sessionId,subject_id:r.subjectId,env:r.env,flags:duplicate,...ageFields(nextAge)}),"created");let prevAge=ageProofOf(prev.age_over,prev.age_method),otherPerson=prev.subject_id!==void 0&&r.subjectId!==void 0&&canonicalId(r.subjectId)!==prev.subject_id,mergedAge=otherPerson?prevAge:strongerAge(prevAge,nextAge);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,...ageFields(mergedAge)}),"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],...ageFields(otherPerson?nextAge:mergedAge)}),"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],...ageFields(mergedAge)}),"renewed"):sameAge(mergedAge,prevAge)?same(prev,"no_change"):wrote(build({...prev,subject_id:prev.subject_id??r.subjectId,...ageFields(mergedAge)}),"age_proved")}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;if(parsed.flags?.some(f=>deny.includes(f)))return fail("flagged","block",parsed);if(parsed.level<policy.level)return fail("level_too_low",parsed.level>=1?"step_up":"verify",parsed);if(policy.maxAgeDays!==void 0&&nowSec-parsed.verified_at>policy.maxAgeDays*86400)return fail("stale","recheck",parsed);if(policy.maxRecheckAgeMinutes!==void 0&&nowSec-(parsed.rechecked_at??parsed.verified_at)>policy.maxRecheckAgeMinutes*60)return fail("recheck_stale","recheck",parsed);if(policy.assurance&&!policy.assurance.includes(parsed.assurance))return fail("assurance_not_allowed","step_up",parsed);if(policy.minAge!==void 0){if(parsed.age_over===void 0||parsed.age_over<policy.minAge)return fail("age_not_proven","verify",parsed);if(policy.ageMethods&&(parsed.age_method===void 0||!policy.ageMethods.includes(parsed.age_method)))return fail("age_method_not_allowed","step_up",parsed)}return{ok:!0,claim:parsed}}export{CLAIM_VERSION,canonicalId,parseClaim,mergeClaim,evaluateGate};