@sekyro/node 0.1.0-rc.9 → 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/CHANGELOG.md +98 -0
- package/README.md +252 -106
- package/dist/{chunk-TAPXGI3Q.js → chunk-IM3UCVDB.js} +1 -1
- package/dist/chunk-J6U2QY7M.js +1 -0
- package/dist/client-sqMIpSkm.d.cts +2460 -0
- package/dist/client-sqMIpSkm.d.ts +2460 -0
- package/dist/connect/express/index.cjs +1 -1
- package/dist/connect/express/index.d.cts +2 -2
- package/dist/connect/express/index.d.ts +2 -2
- package/dist/connect/express/index.js +1 -1
- package/dist/connect/index.cjs +1 -1
- package/dist/connect/index.d.cts +2 -2
- package/dist/connect/index.d.ts +2 -2
- package/dist/connect/index.js +1 -1
- package/dist/connect/next/index.cjs +1 -1
- package/dist/connect/next/index.d.cts +2 -2
- package/dist/connect/next/index.d.ts +2 -2
- package/dist/connect/next/index.js +1 -1
- package/dist/{connector-Bo0P3ytq.d.cts → connector-CF78_88V.d.cts} +98 -15
- package/dist/{connector-B2vbywn2.d.ts → connector-DXF-FRVf.d.ts} +98 -15
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +92 -29
- package/dist/index.d.ts +92 -29
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
- package/dist/chunk-O5GJ3YJV.js +0 -1
- package/dist/client-BYoo67F-.d.cts +0 -1654
- package/dist/client-BYoo67F-.d.ts +0 -1654
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
|
|
11
|
-
|
|
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
|
|
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,36 +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
|
-
// `
|
|
50
|
-
// the number (a different one is refused with 409
|
|
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
51
|
{
|
|
53
52
|
flow: "default",
|
|
54
53
|
locale: "ar",
|
|
55
|
-
|
|
54
|
+
person: { idNumber: { type: "national_id", issuingCountry: "<ISO alpha-2>", number: "<id number>" } },
|
|
56
55
|
},
|
|
57
56
|
{ idempotencyKey: `signup:${userId}` },
|
|
58
57
|
);
|
|
59
|
-
created.id; // persist against your user before returning to the page
|
|
58
|
+
created.id; // `ses_…`: persist against your user before returning to the page
|
|
60
59
|
created.clientToken; // give this to the browser; it is returned ONCE
|
|
61
60
|
created.hostedUrl; // the hosted-flow link, if you use that path instead
|
|
62
61
|
created.expiresAt; // ISO 8601
|
|
63
62
|
created.flow; // { id, slug, version }: the flow version the session runs
|
|
64
|
-
created.subjectUse; // 'reference' | 'prefill': whether the flow believes or checks your
|
|
65
|
-
created.warnings; // one { code: 'deprecated_field', field, replacement } per deprecated key you sent
|
|
63
|
+
created.subjectUse; // 'reference' | 'prefill': whether the flow believes or checks your person data
|
|
66
64
|
|
|
67
65
|
// Read: the whitelisted session view (never contains the client token).
|
|
68
66
|
const session = await sekyro.sessions.get(created.id);
|
|
69
67
|
session.status; // 'created' | 'in_progress' | 'review_pending' | 'completed' | 'expired' | 'failed'
|
|
70
|
-
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
|
|
71
70
|
session.flow; // { id: 'flw_…', slug: 'default', version: 3 }: the flow version the session runs
|
|
72
|
-
session.steps; // [{
|
|
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', …]
|
|
73
75
|
```
|
|
74
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
|
+
|
|
75
81
|
Your API key belongs to an **app**. The app's **flows**, designed in the Sekyro AI
|
|
76
82
|
dashboard (app page → **Flows**), decide which steps run; a session runs the
|
|
77
83
|
flow you name in `flow`, or the app's default flow. To list the published flows
|
|
78
|
-
of the key's app, call `sekyro.
|
|
84
|
+
of the key's app, call `sekyro.flows.list()`: it resolves to
|
|
79
85
|
`FlowSummary[]` (`[{ id, slug, name, version, isDefault }]`), the default flow
|
|
80
86
|
first (`GET /api/v2/flows` under the hood, scope `sessions:create`;
|
|
81
87
|
see the [quickstart](https://docs.sekyro.ai/en/getting-started/quickstart#choose-a-flow)).
|
|
@@ -87,14 +93,14 @@ Every field is optional:
|
|
|
87
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) |
|
|
88
94
|
| `locale` | `ar`, `fr` or `en`: pins the hosted-flow language |
|
|
89
95
|
| `ttlMinutes` | session lifetime, within the flow's link range (`400 ttl_out_of_policy` otherwise); omit for the flow default |
|
|
90
|
-
| `
|
|
91
|
-
| `input` | an open record of branch facts your flow's conditions read
|
|
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` |
|
|
92
98
|
| `identityMethod` | `national_number`, `document_photo`, `document_chip` or `national_eid`: pre-chooses the option of the flow's identity choice |
|
|
93
99
|
| `deliver` | `{ channel: "sms" \| "whatsapp", to: "+1555…" }`: also send the hosted link to the person |
|
|
94
100
|
|
|
95
101
|
```ts
|
|
96
102
|
// The app's flows (published only, default first): pick one at runtime.
|
|
97
|
-
const flows = await sekyro.
|
|
103
|
+
const flows = await sekyro.flows.list(); // [{ id, slug, name, version, isDefault }]
|
|
98
104
|
|
|
99
105
|
await sekyro.sessions.create({
|
|
100
106
|
flow: "foreigners",
|
|
@@ -112,39 +118,100 @@ changes a service's settings, keyed by service id (`liveness`, `phone_otp`,
|
|
|
112
118
|
the flow stricter unless the flow allows widening; turning a service `'off'`
|
|
113
119
|
always widens. The changed paths come back on `session.overriddenFields`.
|
|
114
120
|
|
|
115
|
-
|
|
116
|
-
> `overrides`. `flow` is accepted again, now as the app's flow slug or id.
|
|
121
|
+
`flow` takes the app's flow slug or id.
|
|
117
122
|
|
|
118
123
|
The session view also carries `failureReason` (a policy stop such as
|
|
119
124
|
`location_not_allowed` or `underage`), `failureDetail` (why, when that reason
|
|
120
125
|
is `camera_unavailable`: `denied` or `no_camera`), `overriddenFields`, `riskSignals`,
|
|
121
|
-
`
|
|
126
|
+
`personId` / `externalRef`, `verifiedContacts`, `eid`, and the end user's
|
|
122
127
|
`network` and `device`. A step with `handled: true` failed, but the flow's
|
|
123
128
|
fallback took over.
|
|
124
129
|
|
|
125
|
-
|
|
130
|
+
More session calls:
|
|
126
131
|
|
|
127
132
|
- `sekyro.sessions.selectMethod(id, method)` chooses the identity method of a
|
|
128
133
|
session on the person's behalf (`POST /sessions/:id/method`): `409 choice_locked`
|
|
129
134
|
once the flow's identity choice can no longer change, `409 choice_option_unavailable`
|
|
130
135
|
for a method the flow does not offer this session, `409 choice_not_found` when the
|
|
131
136
|
flow has no identity choice.
|
|
132
|
-
- `sekyro.sessions.
|
|
133
|
-
|
|
134
|
-
`
|
|
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.
|
|
135
200
|
|
|
136
201
|
`sekyro.sessions` is a `SessionsApi`, exported as a type only: you get the
|
|
137
202
|
instance from the client, never by constructing one.
|
|
138
203
|
|
|
139
204
|
### Person data
|
|
140
205
|
|
|
141
|
-
Send what you know about the person in `
|
|
206
|
+
Send what you know about the person in `person`: `idNumber`
|
|
142
207
|
(`{ type, issuingCountry, number }`), `fullName` or `names` (given, family and
|
|
143
|
-
patronymic per ISO 15924 script), `birthDate`, `
|
|
144
|
-
|
|
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`.
|
|
145
212
|
The session's flow decides how Sekyro AI uses it, never the request: when a step
|
|
146
|
-
reads partner-supplied data (
|
|
147
|
-
|
|
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
|
|
148
215
|
**prefill** checked against what the person shows. `created.subjectUse` says
|
|
149
216
|
which (`"reference"` or `"prefill"`). The rules, the trust table and every
|
|
150
217
|
error are on the [Person data](https://docs.sekyro.ai/en/guides/person-data)
|
|
@@ -153,7 +220,7 @@ page.
|
|
|
153
220
|
```ts
|
|
154
221
|
// A prefill: the flow checks it against the registry or the document.
|
|
155
222
|
await sekyro.sessions.create({
|
|
156
|
-
|
|
223
|
+
person: {
|
|
157
224
|
externalRef: userId,
|
|
158
225
|
idNumber: { type: "passport", issuingCountry: "<ISO alpha-2>", number: "<id number>" },
|
|
159
226
|
birthDate: "<YYYY-MM-DD>",
|
|
@@ -162,42 +229,39 @@ await sekyro.sessions.create({
|
|
|
162
229
|
```
|
|
163
230
|
|
|
164
231
|
If your data comes from your own call to a national registry,
|
|
165
|
-
`
|
|
232
|
+
`personFromNationalRegistry()` converts that answer locally into the
|
|
166
233
|
reference keys. Sekyro AI treats the result as identity data supplied by your
|
|
167
|
-
organization: it makes no registry call
|
|
168
|
-
registry key.
|
|
234
|
+
organization: it makes no registry call and needs no registry key.
|
|
169
235
|
|
|
170
236
|
```ts
|
|
171
|
-
import {
|
|
237
|
+
import { personFromNationalRegistry } from "@sekyro/node";
|
|
172
238
|
|
|
173
239
|
const answer = await myRegistryClient.lookup(idNumber); // your call, your key
|
|
174
240
|
const receivedAt = new Date();
|
|
175
241
|
const created = await sekyro.sessions.create({
|
|
176
|
-
|
|
242
|
+
person: {
|
|
177
243
|
externalRef: userId,
|
|
178
244
|
// fetchedAt: when YOUR system received this answer (required; > 24 h old is refused)
|
|
179
|
-
...
|
|
245
|
+
...personFromNationalRegistry("MR", answer, { fetchedAt: receivedAt }),
|
|
180
246
|
},
|
|
181
247
|
});
|
|
182
|
-
created.subjectUse; // "reference"
|
|
248
|
+
created.subjectUse; // "reference" when the flow has a Partner-supplied identity step
|
|
183
249
|
```
|
|
184
250
|
|
|
185
251
|
The first argument is the registry's country (ISO alpha-2) and types the
|
|
186
252
|
answer: `"MR"` takes the ANRPTS `getPersonne` answer
|
|
187
|
-
(`AnrptsPersonneResponse`). The result is a `
|
|
253
|
+
(`AnrptsPersonneResponse`). The result is a `PersonRecord`: `idNumber`,
|
|
188
254
|
`names` (one entry per script found), `birthDate`, `birthPlace`, `sex`,
|
|
189
|
-
`
|
|
190
|
-
a number, a birth date, a photo or any name, or with an invalid `fetchedAt`,
|
|
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`,
|
|
191
257
|
throws `SekyroConfigError` `invalid_registry_record` naming the field (never
|
|
192
258
|
its value); a country without an adapter throws `registry_country_unsupported`.
|
|
193
259
|
An answer that states a nationality none of whose values the SDK can map throws
|
|
194
260
|
`registry_nationality_unmapped` (the message never carries the value): map it
|
|
195
261
|
yourself and pass `options.nationality` (ISO alpha-2), so the stated nationality
|
|
196
262
|
is never dropped.
|
|
197
|
-
`subjectFromNationalRegistry()` replaces `registryFromAnrpts()`.
|
|
198
263
|
|
|
199
|
-
Refusals of a reference, in this order: `
|
|
200
|
-
(the environment is not in `supplied` mode), `422 subject_record_incomplete`
|
|
264
|
+
Refusals of a reference, in this order: `422 subject_record_incomplete`
|
|
201
265
|
(`error.details.fields` names the missing keys), `422 subject_record_stale`
|
|
202
266
|
(obtained more than 24 h ago, or more than 5 min ahead) and
|
|
203
267
|
`422 subject_photo_unusable` (not a JPEG or PNG of at most 1 MB within the size
|
|
@@ -209,20 +273,13 @@ the person consents, at the face match: a photo without one usable face fails th
|
|
|
209
273
|
step with `no_face_reference` (or `low_quality_reference`). That step runs after liveness, so check
|
|
210
274
|
that the photo shows exactly one clear face before you send it.
|
|
211
275
|
|
|
212
|
-
Partner-supplied identity data is not billed: the identity step
|
|
276
|
+
Partner-supplied identity data is not billed: the Partner-supplied identity step
|
|
213
277
|
records no usage event (other steps, such as the face match, bill as usual).
|
|
214
278
|
|
|
215
|
-
|
|
216
|
-
`
|
|
217
|
-
`
|
|
218
|
-
|
|
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.
|
|
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).
|
|
226
283
|
|
|
227
284
|
### Errors
|
|
228
285
|
|
|
@@ -233,8 +290,9 @@ Every non-2xx response, network failure and timeout throws `SekyroApiError`:
|
|
|
233
290
|
| `status` | HTTP status (`0` for network / timeout) |
|
|
234
291
|
| `code` | API error code, or `network` / `timeout` / `http_error` / `malformed_response` |
|
|
235
292
|
| `message` | human-readable, from the API when available |
|
|
236
|
-
| `requestId` | the API's `
|
|
293
|
+
| `requestId` | the API's `requestId`, quote it to support |
|
|
237
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 |
|
|
238
296
|
| `retryable` | `true` for `network`, `timeout`, `429`, `5xx` and `idempotency_in_progress` |
|
|
239
297
|
| `retryAfterSeconds` | seconds to wait from the response's `Retry-After` header (seconds or an HTTP date), else `undefined` |
|
|
240
298
|
|
|
@@ -242,7 +300,7 @@ Every non-2xx response, network failure and timeout throws `SekyroApiError`:
|
|
|
242
300
|
import { SekyroApiError } from "@sekyro/node";
|
|
243
301
|
|
|
244
302
|
try {
|
|
245
|
-
await sekyro.sessions.create({
|
|
303
|
+
await sekyro.sessions.create({ person: { idNumber } });
|
|
246
304
|
} catch (err) {
|
|
247
305
|
if (err instanceof SekyroApiError && err.retryable) {
|
|
248
306
|
// wait err.retryAfterSeconds when set, else back off; retry with the SAME idempotencyKey
|
|
@@ -264,7 +322,7 @@ returns `false` when the details are missing or not in that shape, so read
|
|
|
264
322
|
| `409 flow_not_published`, `409 flow_archived` | `sessions.create` | `issues`, `flow` |
|
|
265
323
|
| `400 override_invalid` | `sessions.create` | `issues`, one per problem (`path: "overrides.services.liveness.attempts"`, …) |
|
|
266
324
|
| `403 override_widens_flow` | `sessions.create` | `issues` (`field_widens_flow`), `fields` |
|
|
267
|
-
| `409 reuse_disabled` | `sessions.create` with `
|
|
325
|
+
| `409 reuse_disabled` | `sessions.create` with `person.reuse` | `issues`, `flow` |
|
|
268
326
|
| `409 choice_not_found`, `choice_locked`, `choice_option_unavailable` | `sessions.selectMethod` | `issues` |
|
|
269
327
|
|
|
270
328
|
```ts
|
|
@@ -281,48 +339,52 @@ try {
|
|
|
281
339
|
}
|
|
282
340
|
```
|
|
283
341
|
|
|
284
|
-
##
|
|
342
|
+
## People
|
|
285
343
|
|
|
286
|
-
A **
|
|
287
|
-
`
|
|
288
|
-
from the dashboard carry both; mint a new key if
|
|
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
|
|
289
347
|
`403 insufficient_scope`).
|
|
290
348
|
|
|
291
349
|
```ts
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
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
|
|
300
357
|
|
|
301
|
-
const [byRef] = await sekyro.
|
|
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
|
|
302
360
|
|
|
303
361
|
// Returning user: liveness + face match against the stored reference photo.
|
|
304
|
-
// Name exactly one of
|
|
305
|
-
await sekyro.sessions.create({
|
|
362
|
+
// Name exactly one of personId (the person id), externalRef or idNumber.
|
|
363
|
+
await sekyro.sessions.create({ person: { reuse: { personId } } });
|
|
306
364
|
|
|
307
365
|
// The same in one call, with a mode: `recheck` (verify the same person again)
|
|
308
|
-
// or `step_up` (raise a level 1
|
|
309
|
-
//
|
|
310
|
-
await sekyro.
|
|
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" });
|
|
311
369
|
|
|
312
|
-
await sekyro.
|
|
313
|
-
await sekyro.
|
|
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
|
|
314
372
|
```
|
|
315
373
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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`.
|
|
319
383
|
|
|
320
384
|
## Webhooks
|
|
321
385
|
|
|
322
386
|
Verify with the **raw** request body (bytes as received, before any JSON
|
|
323
|
-
parsing or re-serialisation) and the signature header
|
|
324
|
-
(primary), falling back to the legacy `x-ibtikar-signature` while both are
|
|
325
|
-
sent.
|
|
387
|
+
parsing or re-serialisation) and the signature header, `x-sekyro-signature`.
|
|
326
388
|
|
|
327
389
|
```ts
|
|
328
390
|
import { verifyWebhook, signatureFromHeaders, SekyroWebhookError } from "@sekyro/node";
|
|
@@ -331,20 +393,21 @@ app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), (req, re
|
|
|
331
393
|
try {
|
|
332
394
|
const envelope = verifyWebhook(
|
|
333
395
|
req.body.toString("utf8"),
|
|
334
|
-
signatureFromHeaders(req.headers), // x-sekyro-signature
|
|
396
|
+
signatureFromHeaders(req.headers), // the x-sekyro-signature header
|
|
335
397
|
process.env.SEKYRO_WEBHOOK_SECRET!,
|
|
336
398
|
);
|
|
337
399
|
// The envelope is discriminated on `event`: narrowing it types `data`.
|
|
338
400
|
switch (envelope.event) {
|
|
339
401
|
case "session.completed":
|
|
340
402
|
case "session.failed":
|
|
341
|
-
|
|
403
|
+
// The one terminal event of a session: { sessionId, status, outcome, decidedBy, decision?, flow, steps, identity?, media?, … }
|
|
404
|
+
envelope.data; // SessionLifecycleEventData
|
|
342
405
|
break;
|
|
343
|
-
case "session.
|
|
344
|
-
envelope.data; //
|
|
406
|
+
case "session.superseded":
|
|
407
|
+
envelope.data; // SessionSupersededEventData: { sessionId, supersededBy, reason: 'superseded_by_retry' }
|
|
345
408
|
break;
|
|
346
|
-
case "
|
|
347
|
-
envelope.data; //
|
|
409
|
+
case "person.updated":
|
|
410
|
+
envelope.data; // PersonUpdatedEventData: { personId, status, externalRefs, … }
|
|
348
411
|
break;
|
|
349
412
|
}
|
|
350
413
|
res.sendStatus(200);
|
|
@@ -359,17 +422,41 @@ app.post("/webhooks/sekyro", express.raw({ type: "application/json" }), (req, re
|
|
|
359
422
|
rotation Sekyro AI signs with both the current and the previous secret, so the
|
|
360
423
|
delivery is accepted when **any** `v1` matches the secret you hold.
|
|
361
424
|
- **Header names.** Deliveries carry the signature in `x-sekyro-signature`
|
|
362
|
-
(`SEKYRO_SIGNATURE_HEADER`)
|
|
363
|
-
|
|
364
|
-
|
|
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.
|
|
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`.
|
|
368
428
|
- Each `v1` is `HMAC-SHA256(secret, "<t>.<rawBody>")`, compared in constant time.
|
|
369
429
|
- Deliveries older or newer than `toleranceSec` (default 300 s) are rejected as
|
|
370
430
|
`stale`; pass `{ now }` to inject a clock in tests.
|
|
371
431
|
- Retried deliveries carry the same envelope `id`; de-duplicate on it.
|
|
372
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
|
+
|
|
373
460
|
## Result tokens
|
|
374
461
|
|
|
375
462
|
A finished session carries a short-lived ES256 JWT: `resultToken` on the
|
|
@@ -380,21 +467,26 @@ trusting it:
|
|
|
380
467
|
```ts
|
|
381
468
|
import { verifyResultToken, SekyroResultTokenError } from "@sekyro/node";
|
|
382
469
|
|
|
383
|
-
const result = await verifyResultToken(token, {
|
|
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
|
+
});
|
|
384
475
|
result.level; // 0 | 1 | 2 | 3 | null (1 human, 2 identity, 3 corroborated)
|
|
385
476
|
result.assurance; // 'live_only' | 'document_biometric' | 'registry_biometric' | ...
|
|
386
477
|
result.outcome; // 'approved' | 'rejected' | ...
|
|
387
|
-
result.
|
|
478
|
+
result.personId; // the person id (per_…), when known
|
|
388
479
|
```
|
|
389
480
|
|
|
390
481
|
- Keys come from `https://api.sekyro.ai/.well-known/sekyro/jwks.json` and are
|
|
391
482
|
cached for 10 minutes; an unknown key id fetches the set again.
|
|
392
483
|
- `aud` must be your app id (pass an array to accept several; `result.appId`
|
|
393
484
|
says which), and the token expires 10 minutes after signing.
|
|
394
|
-
-
|
|
395
|
-
|
|
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`.
|
|
396
488
|
- Failures throw `SekyroResultTokenError` with a `code`: `invalid_token`,
|
|
397
|
-
`expired`, `wrong_audience`, `wrong_issuer`, `wrong_env`,
|
|
489
|
+
`expired`, `wrong_audience`, `wrong_issuer`, `wrong_env`, `env_required`,
|
|
398
490
|
`key_env_mismatch`, `jwks_unavailable` or `invalid_options`.
|
|
399
491
|
|
|
400
492
|
When the flow sets a minimum age, `result.age` is `{ over, method }` from the
|
|
@@ -403,9 +495,22 @@ and `method` says how it was proved (`estimated` by the age check (selfie)
|
|
|
403
495
|
step, or `document`, `chip`, `registry`, `eid`). The token never carries the
|
|
404
496
|
estimated age; with the step's "Keep and show the estimated age" setting on,
|
|
405
497
|
`estimate` and `sigma` arrive on the session (`sekyro.sessions.get`) and the
|
|
406
|
-
`session.completed` / `session.failed` webhooks only.
|
|
407
|
-
|
|
408
|
-
and `
|
|
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.
|
|
409
514
|
|
|
410
515
|
## Connect
|
|
411
516
|
|
|
@@ -477,13 +582,23 @@ app.get(
|
|
|
477
582
|
// Next.js: sekyroGate() and gateRoute() from "@sekyro/node/connect/next".
|
|
478
583
|
```
|
|
479
584
|
|
|
480
|
-
The claim (unix seconds; never a name, a document number, a photo
|
|
585
|
+
The claim (unix seconds; never a name, a document number, a photo, a score, a birth date or an estimated age):
|
|
481
586
|
|
|
482
587
|
```json
|
|
483
588
|
{ "v": 1, "level": 2, "assurance": "document_biometric", "verified_at": 1790000000, "rechecked_at": 1790003600,
|
|
484
|
-
"session_id": "<session id>", "subject_id": "<
|
|
589
|
+
"session_id": "<session id>", "subject_id": "<person id>", "env": "live", "flags": ["face_mismatch"],
|
|
590
|
+
"age_over": 18, "age_method": "document" }
|
|
485
591
|
```
|
|
486
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
|
+
|
|
487
602
|
Trust rules:
|
|
488
603
|
|
|
489
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).
|
|
@@ -492,7 +607,38 @@ Trust rules:
|
|
|
492
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.
|
|
493
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.
|
|
494
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.
|
|
495
|
-
- A revocation or deletion of the
|
|
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
|
+
```
|
|
496
642
|
|
|
497
643
|
The full guide, with the Zitadel and Supabase setups, is in [Auth connectors](https://docs.sekyro.ai/en/connectors/overview).
|
|
498
644
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{evaluateGate}from"./chunk-
|
|
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};
|