@sekyro/node 0.1.0-rc.1 → 0.1.0-rc.11

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.
@@ -0,0 +1,426 @@
1
+ import { W as WebhookEventType, L as Locale, C as CreatedSession, S as Sekyro, F as FetchLike } from './client-B7_KS_rG.js';
2
+
3
+ /**
4
+ * The Sekyro claim contract and its only state machine, `mergeClaim` (spec
5
+ * 2026-10-29 §4). Pure: no I/O, no `jose`, no `node:` built-ins, so it runs in
6
+ * an edge runtime as well as on Node.
7
+ */
8
+ /** The claim contract version this SDK writes and reads. @public */
9
+ declare const CLAIM_VERSION = 1;
10
+ /**
11
+ * Security facts a claim can carry: `face_mismatch` (a step-up failed because
12
+ * the face belongs to another subject), `duplicate` (the face matched another
13
+ * subject), `revoked` (the subject was revoked or deleted).
14
+ * @public
15
+ */
16
+ type ClaimFlag = "face_mismatch" | "duplicate" | "revoked";
17
+ /**
18
+ * The small object a connector stores on the auth provider's user and the
19
+ * session token carries (spec §4.1). Timestamps are unix seconds. It never
20
+ * carries a name, a document number, a photo, a score or the risk block.
21
+ * @public
22
+ */
23
+ interface SekyroClaim {
24
+ /** Contract version; a reader refuses a higher one. */
25
+ v: 1;
26
+ /** The highest level the person proved for this app; `0` after a revocation. */
27
+ level: 0 | 1 | 2 | 3;
28
+ /** The assurance of the session that proved `level` (`none` when it had none). */
29
+ assurance: string;
30
+ /** Unix seconds: when `level` was proved. */
31
+ verified_at: number;
32
+ /** Unix seconds: the latest approved re-check; absent until one ran. */
33
+ rechecked_at?: number;
34
+ /** The session that set `level`. */
35
+ session_id: string;
36
+ /** The Sekyro subject, when known (needed to apply a revocation). */
37
+ subject_id?: string;
38
+ /** The environment the proof comes from. */
39
+ env: "live" | "sandbox";
40
+ /** Sorted and deduplicated; absent when empty. */
41
+ flags?: ClaimFlag[];
42
+ }
43
+ /**
44
+ * A terminal session result in the shape {@link mergeClaim} reads, built from
45
+ * a verified result token, a webhook or a session view.
46
+ * @public
47
+ */
48
+ interface VerificationResultInput {
49
+ sessionId: string;
50
+ /** `superseded` (a newer attempt took the review over) is never approved: the claim stays as it was. */
51
+ outcome: "approved" | "rejected" | "review" | "superseded" | null;
52
+ level: 0 | 1 | 2 | 3 | null;
53
+ assurance: string | null;
54
+ /** ISO 8601. */
55
+ verifiedAt: string;
56
+ env: "live" | "sandbox";
57
+ subjectId?: string;
58
+ reuseMode?: "recheck" | "step_up";
59
+ returning?: boolean;
60
+ subjectConflict?: boolean;
61
+ /** `true` when the session reported at least one duplicate subject. */
62
+ duplicates?: boolean;
63
+ }
64
+ /**
65
+ * What happened, as {@link mergeClaim} sees it. On a revocation or deletion,
66
+ * `userInExternalRefs` is `true` when the event's external references (or the
67
+ * subject's, read with the API key) include this user's id: a stored claim
68
+ * without `subject_id` is revoked only then, otherwise it is `subject_mismatch`.
69
+ * @public
70
+ */
71
+ type MergeEvent = {
72
+ kind: "result";
73
+ result: VerificationResultInput;
74
+ } | {
75
+ kind: "revoked";
76
+ subjectId: string;
77
+ userInExternalRefs?: boolean;
78
+ } | {
79
+ kind: "deleted";
80
+ subjectId: string;
81
+ userInExternalRefs?: boolean;
82
+ };
83
+ /** The rule {@link mergeClaim} applied. @public */
84
+ type MergeRule = "created" | "raised" | "renewed" | "rechecked" | "face_mismatch" | "revoked" | "revoked_ignored" | "not_approved" | "stale_ignored" | "env_mismatch" | "unsupported_version" | "subject_mismatch" | "no_change";
85
+ /** Result of {@link mergeClaim}: write `claim` only when `changed`. @public */
86
+ interface MergeOutcome {
87
+ claim: SekyroClaim | null;
88
+ changed: boolean;
89
+ rule: MergeRule;
90
+ }
91
+ /**
92
+ * Read a stored or token-carried claim: an object or its JSON string.
93
+ * Returns `null` when the value is not a claim. A claim with a higher
94
+ * version than {@link CLAIM_VERSION} is returned as-is (the caller refuses
95
+ * it); unknown keys and unknown flags of a current claim are dropped.
96
+ * @public
97
+ */
98
+ declare function parseClaim(value: unknown): SekyroClaim | null;
99
+ /**
100
+ * Apply one event to the stored claim (spec §4.2) and say whether to write.
101
+ * Pure and idempotent: the webhook and the return-URL path converge on one
102
+ * write, a retry is a no-op, an older result never overwrites a newer one, a
103
+ * failed attempt never erases a proof, a weaker proof never lowers the level,
104
+ * a result from another environment is refused, and a revoked claim stays
105
+ * revoked (`revoked_ignored`) until a session of another, known subject
106
+ * proves a level again.
107
+ *
108
+ * @param previous - The stored value (object, JSON string or nothing).
109
+ * @param event - A session result, or a revocation or deletion of a subject.
110
+ * @param opts - `env`: the connector's environment; `now`: epoch milliseconds
111
+ * (used only when a result's `verifiedAt` is not a date).
112
+ * @public
113
+ */
114
+ declare function mergeClaim(previous: unknown, event: MergeEvent, opts: {
115
+ env: "live" | "sandbox";
116
+ now?: () => number;
117
+ }): MergeOutcome;
118
+
119
+ /**
120
+ * The gate: a claim and a policy in, `{ ok }` or a reason and an action out
121
+ * (spec 2026-10-29 §5.3). Pure and framework-free; edge-runtime safe.
122
+ */
123
+
124
+ /**
125
+ * What a route requires of the person's claim.
126
+ * @public
127
+ */
128
+ interface GatePolicy {
129
+ /** The lowest level that passes. */
130
+ level: 1 | 2 | 3;
131
+ /** Maximum age of `verified_at`, in days. */
132
+ maxAgeDays?: number;
133
+ /** Maximum age of `rechecked_at` (falling back to `verified_at` when absent), in minutes. */
134
+ maxRecheckAgeMinutes?: number;
135
+ /** The assurances that pass; any when omitted. */
136
+ assurance?: string[];
137
+ /** The environment that passes; any when omitted. */
138
+ env?: "live" | "sandbox";
139
+ /** Flags that block. Default `["revoked", "face_mismatch"]`. */
140
+ denyFlags?: ClaimFlag[];
141
+ }
142
+ /** Why a gate failed. @public */
143
+ type GateReason = "no_claim" | "unsupported_version" | "wrong_env" | "flagged" | "level_too_low" | "stale" | "recheck_stale" | "assurance_not_allowed";
144
+ /**
145
+ * What the app should do about a failed gate: start a verification
146
+ * (`verify`), a step-up (`step_up`), a re-check (`recheck`), or refuse
147
+ * (`block`).
148
+ * @public
149
+ */
150
+ type GateAction = "verify" | "step_up" | "recheck" | "block";
151
+ /** Result of {@link evaluateGate}. @public */
152
+ type GateResult = {
153
+ ok: true;
154
+ claim: SekyroClaim;
155
+ } | {
156
+ ok: false;
157
+ reason: GateReason;
158
+ action: GateAction;
159
+ claim: SekyroClaim | null;
160
+ };
161
+ /**
162
+ * Check a claim (as read from the session token, an object or its JSON
163
+ * string) against a policy. The checks run in this order: present, version,
164
+ * environment, flags, level, age, re-check age, assurance.
165
+ *
166
+ * @param claim - The claim value, or anything else (`no_claim`).
167
+ * @param policy - What the route requires.
168
+ * @param nowSec - Unix seconds. Default the current time.
169
+ * @public
170
+ */
171
+ declare function evaluateGate(claim: unknown, policy: GatePolicy, nowSec?: number): GateResult;
172
+
173
+ /**
174
+ * The connector's small state: delivery and token ids already handled (a
175
+ * retry is skipped) and, optionally, which user a subject belongs to (to
176
+ * resolve a `subject.deleted` that carries no external references).
177
+ * @public
178
+ */
179
+ interface ConnectorStore {
180
+ /** Record `id` for `ttlSec`; resolves `true` when it was already recorded (a retry). */
181
+ seen(id: string, ttlSec: number): Promise<boolean>;
182
+ /** Forget a recorded `id` so a retry is handled again; called when handling failed. Optional. */
183
+ forget?(id: string): Promise<void>;
184
+ setSubjectUser?(subjectId: string, userId: string): Promise<void>;
185
+ getSubjectUser?(subjectId: string): Promise<string | undefined>;
186
+ }
187
+ /**
188
+ * The in-process store of {@link memoryStore}. Its content is lost on restart
189
+ * and not shared between processes; use your own {@link ConnectorStore} (a
190
+ * cache or a table) when you run several instances.
191
+ * @public
192
+ */
193
+ interface MemoryStore extends ConnectorStore {
194
+ forget(id: string): Promise<void>;
195
+ setSubjectUser(subjectId: string, userId: string): Promise<void>;
196
+ getSubjectUser(subjectId: string): Promise<string | undefined>;
197
+ /** The number of recorded ids not yet expired. */
198
+ size(): number;
199
+ }
200
+ /**
201
+ * An in-memory {@link ConnectorStore}, the connector's default. Expired ids
202
+ * are evicted on every call, so it never grows past the ids of one TTL window.
203
+ * @param opts - `now`: a clock returning epoch milliseconds (default `Date.now`).
204
+ * @public
205
+ */
206
+ declare function memoryStore(opts?: {
207
+ now?: () => number;
208
+ }): MemoryStore;
209
+
210
+ /**
211
+ * Where a provider keeps the claim. A provider package (`@sekyro/connect-zitadel`,
212
+ * `@sekyro/connect-supabase`, ...) ships one; any object of this shape works.
213
+ * @public
214
+ */
215
+ interface ProviderAdapter {
216
+ /** The provider's name, for example `zitadel` or `supabase`. */
217
+ readonly name: string;
218
+ /**
219
+ * The adapter package version, sent with the provider name in the
220
+ * `x-sekyro-connector` header (see {@link ConnectorOptions.telemetry}).
221
+ */
222
+ readonly version?: string;
223
+ /** The value stored at the provider's claim key for this user, or `null`. */
224
+ readUser(userId: string): Promise<unknown>;
225
+ /** Store the claim at the provider's claim key for this user. */
226
+ writeUser(userId: string, claim: SekyroClaim): Promise<void>;
227
+ /** The value at the provider's claim path inside a decoded session token. */
228
+ readClaimFromToken(tokenClaims: Record<string, unknown>): unknown;
229
+ /**
230
+ * Optional read-merge-write for one user. Read the stored value, call `fn`
231
+ * with it, store `claim` when the outcome is `changed` and `claim` is not
232
+ * `null`, and resolve to the outcome. Make it atomic for the user against
233
+ * every other `update` the adapter can see (a per-user lock, a transaction
234
+ * or a compare-and-set retry; `fn` is pure and may be called again).
235
+ * Without it, the connector serialises `readUser` then `writeUser` per user
236
+ * in this process only.
237
+ */
238
+ update?(userId: string, fn: (previous: unknown) => MergeOutcome): Promise<MergeOutcome>;
239
+ }
240
+ /** Why a webhook was not written. @public */
241
+ type WebhookSkipReason = "duplicate_delivery" | "ignored_event" | "other_app" | "no_external_ref" | "result_token_required" | "revocation_unresolved" | "env_mismatch" | "unsupported_version" | "stale_ignored" | "not_approved" | "no_change";
242
+ /**
243
+ * Structured events of the connector, for your logger. Ids, enums and rules
244
+ * only: never a claim body, a token, a secret or a return URL.
245
+ * @public
246
+ */
247
+ type ConnectorLogEvent = {
248
+ type: "write";
249
+ userId: string;
250
+ sessionId?: string;
251
+ rule: MergeRule;
252
+ } | {
253
+ type: "skip";
254
+ reason: WebhookSkipReason;
255
+ sessionId?: string;
256
+ subjectId?: string;
257
+ } | {
258
+ type: "result_token_absent";
259
+ sessionId: string;
260
+ } | {
261
+ type: "revocation_unresolved";
262
+ subjectId: string;
263
+ } | {
264
+ type: "revocation_handler_failed";
265
+ subjectId: string;
266
+ } | {
267
+ type: "env_mismatch";
268
+ sessionId: string;
269
+ } | {
270
+ type: "flag_cleared";
271
+ userId: string;
272
+ flag: ClaimFlag;
273
+ };
274
+ /**
275
+ * Passed to {@link ConnectorOptions.onRevocationUnresolved}: Sekyro revoked or
276
+ * deleted a subject and the connector found no user to clear the claim on.
277
+ * Ids only: never provider data, a claim body or a token.
278
+ * @public
279
+ */
280
+ interface RevocationUnresolvedEvent {
281
+ /** The Sekyro subject that was revoked or deleted. */
282
+ subjectId: string;
283
+ /** The provider adapter's name, for example `zitadel` or `supabase`. */
284
+ provider: string;
285
+ /** `revoked` for `subject.updated` with status `revoked`, `deleted` for `subject.deleted`. */
286
+ reason: "revoked" | "deleted";
287
+ }
288
+ /** Options of {@link createConnector}. @public */
289
+ interface ConnectorOptions {
290
+ /** A client with this environment's API key. */
291
+ sekyro: Sekyro;
292
+ /** Your app id, or every app id this connector serves. */
293
+ appId: string | string[];
294
+ /** The environment of the API key and webhook secret; a claim from the other one is never written. */
295
+ env: "live" | "sandbox";
296
+ /** The webhook endpoint secret. */
297
+ webhookSecret: string;
298
+ /** Where the claim is stored. */
299
+ provider: ProviderAdapter;
300
+ /** What {@link Connector.userDeleted} does with the person's subjects. Default `ignore`. */
301
+ onUserDeleted?: "ignore" | "revoke" | "delete";
302
+ /** Delivery de-duplication and the subject-to-user map. Default {@link memoryStore}. */
303
+ store?: ConnectorStore;
304
+ /** Refuse to write a terminal webhook without a result token. Default `false`. */
305
+ requireResultToken?: boolean;
306
+ /** Passed to `verifyResultToken`. */
307
+ issuer?: string;
308
+ /** Passed to `verifyResultToken`. */
309
+ jwksUrl?: string;
310
+ /** `fetch` for the result-token key set. Default `globalThis.fetch`. */
311
+ fetch?: FetchLike;
312
+ /** Clock returning epoch milliseconds. Default `Date.now`. */
313
+ now?: () => number;
314
+ /** Receives every {@link ConnectorLogEvent}; the connector never writes to the console. */
315
+ logger?: (event: ConnectorLogEvent) => void;
316
+ /**
317
+ * Called when Sekyro revokes or deletes a subject and the connector cannot
318
+ * find the user (no `externalRefs`, no store entry), so no claim was
319
+ * cleared. Find the user for `event.subjectId` and remove their access.
320
+ * Runs after the `revocation_unresolved` log line and telemetry event, in the
321
+ * background: the webhook does not wait for it, and a throw or rejection is
322
+ * caught and reported to `logger` as `revocation_handler_failed`.
323
+ */
324
+ onRevocationUnresolved?: (event: RevocationUnresolvedEvent) => void | Promise<void>;
325
+ /**
326
+ * Tell Sekyro this connector is wired, for the dashboard's Connectors page.
327
+ * Default `true`: every API call carries the `x-sekyro-connector` header
328
+ * (`<provider>/<version>`), and after each claim write (and each
329
+ * `revocation_unresolved`) the connector posts an event with ids only (type,
330
+ * provider, session id, subject id, time; never the claim, a token or user
331
+ * data), in the background with a 2-second timeout and no retry. Only the
332
+ * six Sekyro provider packages send it. `false` sends neither.
333
+ */
334
+ telemetry?: boolean;
335
+ }
336
+ /** Result of {@link Connector.webhook}. @public */
337
+ type WebhookOutcome = {
338
+ handled: true;
339
+ event: WebhookEventType;
340
+ userId: string;
341
+ claim: SekyroClaim | null;
342
+ rule: MergeRule;
343
+ } | {
344
+ handled: false;
345
+ event: WebhookEventType | null;
346
+ reason: WebhookSkipReason;
347
+ };
348
+ /** Options of {@link Connector.start}, {@link Connector.recheck} and {@link Connector.stepUp}. @public */
349
+ interface StartOptions {
350
+ /** A flow slug or id; the app's default flow when omitted. */
351
+ flow?: string;
352
+ locale?: Locale;
353
+ /** Where the hosted flow sends the person at the end. */
354
+ returnUrl?: string;
355
+ /** A value you store against the user and check on the return. */
356
+ state?: string;
357
+ ttlMinutes?: number;
358
+ }
359
+ /** The object {@link createConnector} returns. @public */
360
+ interface Connector {
361
+ /** The environment the connector writes claims for. */
362
+ readonly env: "live" | "sandbox";
363
+ /** The app ids whose webhooks and result tokens the connector accepts. */
364
+ readonly appIds: readonly string[];
365
+ /**
366
+ * Verify and apply a Sekyro webhook. Pass the raw body exactly as received.
367
+ * Throws `SekyroWebhookError` (bad signature), `SekyroResultTokenError` (bad
368
+ * token) or {@link SekyroConnectError} (token for another session or user):
369
+ * answer those with a 4xx, except `SekyroConnectError` with code
370
+ * `unavailable` (the key set could not be fetched): answer it with a 503 so
371
+ * Sekyro retries. Answer 2xx once it resolves.
372
+ */
373
+ webhook(rawBody: string, headers: Headers | Record<string, string | string[] | undefined>): Promise<WebhookOutcome>;
374
+ /**
375
+ * The return-URL path: read the session and its signed result token with
376
+ * the API key, verify the token (audience = your app ids, environment) and
377
+ * apply it. A session created without an app or for another app is refused
378
+ * (`SekyroResultTokenError` `wrong_audience`), as is a session of another
379
+ * user ({@link SekyroConnectError} `external_ref_mismatch`). Check your
380
+ * `state` first: store the session id with the state when you create the
381
+ * session, and compare both on the return.
382
+ */
383
+ sync(userId: string, sessionId: string): Promise<{
384
+ claim: SekyroClaim | null;
385
+ rule: MergeRule;
386
+ }>;
387
+ /** Create a verification session for your user (`subject.externalRef` = `userId`). */
388
+ start(userId: string, opts?: StartOptions): Promise<CreatedSession>;
389
+ /** Create a re-check session for your user's subject. */
390
+ recheck(userId: string, opts?: Omit<StartOptions, "flow">): Promise<CreatedSession>;
391
+ /** Create a step-up session for your user's subject with an identity flow. */
392
+ stepUp(userId: string, opts: StartOptions & {
393
+ flow: string;
394
+ }): Promise<CreatedSession>;
395
+ /** Your app deleted the user: apply the `onUserDeleted` policy to the person's subjects. */
396
+ userDeleted(userId: string): Promise<{
397
+ policy: "ignore" | "revoke" | "delete";
398
+ subjects: number;
399
+ }>;
400
+ /** The stored claim, read from the provider (no token lag). */
401
+ claimOf(userId: string): Promise<SekyroClaim | null>;
402
+ /** Remove a flag from the stored claim (for example after a manual review of a `face_mismatch`). */
403
+ clearFlag(userId: string, flag: ClaimFlag): Promise<SekyroClaim | null>;
404
+ /** Check a decoded session token against a policy; `env` defaults to the connector's. */
405
+ gate(tokenClaims: Record<string, unknown>, policy: GatePolicy): GateResult;
406
+ }
407
+ /**
408
+ * Tie Sekyro to an auth provider: verified webhooks and return-URL reads
409
+ * become one idempotent claim write on the provider's user, and the gate
410
+ * reads that claim from the session token.
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * const connector = createConnector({
415
+ * sekyro: new Sekyro({ apiKey: process.env.SEKYRO_API_KEY! }),
416
+ * appId: process.env.SEKYRO_APP_ID!,
417
+ * env: "live",
418
+ * webhookSecret: process.env.SEKYRO_WEBHOOK_SECRET!,
419
+ * provider,
420
+ * });
421
+ * ```
422
+ * @public
423
+ */
424
+ declare function createConnector(opts: ConnectorOptions): Connector;
425
+
426
+ export { type Connector as C, type GatePolicy as G, type MemoryStore as M, type ProviderAdapter as P, type RevocationUnresolvedEvent as R, type SekyroClaim as S, type VerificationResultInput as V, type WebhookOutcome as W, type GateResult as a, CLAIM_VERSION as b, type ClaimFlag as c, type ConnectorLogEvent as d, type ConnectorOptions as e, type ConnectorStore as f, type GateAction as g, type GateReason as h, type MergeEvent as i, type MergeOutcome as j, type MergeRule as k, type StartOptions as l, type WebhookSkipReason as m, createConnector as n, evaluateGate as o, memoryStore as p, mergeClaim as q, parseClaim as r };