axiam-sdk 1.0.0-alpha8 → 1.0.0-beta02

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.
Files changed (78) hide show
  1. package/README.md +1479 -14
  2. package/dist/amqp/index.d.cts +769 -2
  3. package/dist/amqp/index.d.ts +769 -2
  4. package/dist/amqp/index.js +616 -1
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +582 -3
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-B7GSd3-t.d.cts → authzCore-CiMC6Eru.d.ts} +105 -7
  9. package/dist/{authzCore-CcTdIf78.d.ts → authzCore-Ct8ZzJL4.d.cts} +105 -7
  10. package/dist/browser/index.d.cts +90 -0
  11. package/dist/browser/index.d.ts +90 -0
  12. package/dist/browser/index.js +213 -0
  13. package/dist/browser/index.js.map +1 -0
  14. package/dist/browser/index.mjs +203 -0
  15. package/dist/browser/index.mjs.map +1 -0
  16. package/dist/client-DjCaHR3c.d.cts +5831 -0
  17. package/dist/client-y9dwy3p3.d.ts +5831 -0
  18. package/dist/cookieJar-BCILMWdK.d.cts +145 -0
  19. package/dist/cookieJar-DVW2SSf5.d.ts +145 -0
  20. package/dist/grpc/index.d.cts +141 -14
  21. package/dist/grpc/index.d.ts +141 -14
  22. package/dist/grpc/index.js +4963 -52
  23. package/dist/grpc/index.js.map +1 -1
  24. package/dist/grpc/index.mjs +4962 -53
  25. package/dist/grpc/index.mjs.map +1 -1
  26. package/dist/index.d.cts +7 -3
  27. package/dist/index.d.ts +7 -3
  28. package/dist/index.js +4930 -72
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +4846 -73
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/jwks-CSXHo3DS.d.cts +377 -0
  33. package/dist/jwks-CSXHo3DS.d.ts +377 -0
  34. package/dist/middleware/index.d.cts +196 -5
  35. package/dist/middleware/index.d.ts +196 -5
  36. package/dist/middleware/index.js +1880 -13
  37. package/dist/middleware/index.js.map +1 -1
  38. package/dist/middleware/index.mjs +1868 -15
  39. package/dist/middleware/index.mjs.map +1 -1
  40. package/dist/nestjs/index.d.cts +4 -3
  41. package/dist/nestjs/index.d.ts +4 -3
  42. package/dist/nestjs/index.js +9 -3
  43. package/dist/nestjs/index.js.map +1 -1
  44. package/dist/nestjs/index.mjs +9 -3
  45. package/dist/nestjs/index.mjs.map +1 -1
  46. package/dist/node/index.d.cts +228 -94
  47. package/dist/node/index.d.ts +228 -94
  48. package/dist/node/index.js +6693 -188
  49. package/dist/node/index.js.map +1 -1
  50. package/dist/node/index.mjs +6648 -189
  51. package/dist/node/index.mjs.map +1 -1
  52. package/dist/oidcState-BMcyBUz-.d.ts +1287 -0
  53. package/dist/oidcState-C4YtEKPT.d.cts +1287 -0
  54. package/dist/rest/index.d.cts +368 -18
  55. package/dist/rest/index.d.ts +368 -18
  56. package/dist/rest/index.js +4930 -72
  57. package/dist/rest/index.js.map +1 -1
  58. package/dist/rest/index.mjs +4846 -73
  59. package/dist/rest/index.mjs.map +1 -1
  60. package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
  61. package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
  62. package/dist/session-BJHqprWm.d.ts +229 -0
  63. package/dist/session-CMgYRxLP.d.cts +229 -0
  64. package/dist/telemetry-DrGqL4kb.d.cts +124 -0
  65. package/dist/telemetry-DrGqL4kb.d.ts +124 -0
  66. package/dist/types-CpbckLcy.d.cts +116 -0
  67. package/dist/types-DHnCMjtY.d.ts +116 -0
  68. package/dist/webauthnErrors-fLgfOflO.d.cts +26 -0
  69. package/dist/webauthnErrors-fLgfOflO.d.ts +26 -0
  70. package/package.json +25 -7
  71. package/dist/client-BPg9kfKV.d.ts +0 -150
  72. package/dist/client-CAeQw1a-.d.cts +0 -150
  73. package/dist/jwks-B8dPy2c6.d.cts +0 -36
  74. package/dist/jwks-B8dPy2c6.d.ts +0 -36
  75. package/dist/sensitive-CWBH_tHr.d.cts +0 -12
  76. package/dist/sensitive-CWBH_tHr.d.ts +0 -12
  77. package/dist/types-BVkMoqLU.d.cts +0 -59
  78. package/dist/types-BVkMoqLU.d.ts +0 -59
package/README.md CHANGED
@@ -8,16 +8,59 @@
8
8
 
9
9
  Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanich/axiam) — Access eXtended Identity and Authorization Management.
10
10
 
11
+ **Platform documentation:** <https://ilpanich.github.io/axiam/> — getting started, the authorization model, the OAuth2/OIDC surface, and the operations guides. This README covers the SDK; the site covers the server it talks to.
12
+
11
13
  ## Package identity
12
14
 
13
15
  - **npm package:** `axiam-sdk`
14
16
  - **Registry:** [npmjs.com/package/axiam-sdk](https://www.npmjs.com/package/axiam-sdk) _(reserved, not yet published)_
15
17
  - **Source:** [github.com/ilpanich/axiam-typescript-sdk](https://github.com/ilpanich/axiam-typescript-sdk)
16
18
  - **License:** Apache-2.0
19
+ - **Node:** `>=22` — see [Supported Node versions](#supported-node-versions)
17
20
 
18
21
  ## Contract conformance
19
22
 
20
- This SDK conforms to CONTRACT.md §1–§11.
23
+ This SDK conforms to CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19, §20, §21, §22, §23,
24
+ §24, §25, §26, §27 (including §6.1 mTLS client certificates, the §10.1 minimum
25
+ local-verification set, the §12 OIDC/SSO relying-party helpers, and the §13
26
+ `verifyWebhook` signature verifier).
27
+
28
+ §27 is implemented **in full**, both halves: the 146-operation imperative surface *and*
29
+ the §27.6 declarative manifest with its §27.7 `defineManifest` and decorator forms. The
30
+ contract asks an SDK that ships only one half to say which; this one ships both.
31
+
32
+ §12.7, §14, §15, §22, §24, §25, §26 and §27 are named rather than folded into the range
33
+ because they landed after this SDK already claimed §1–§13: widening the range silently
34
+ would turn a statement that was true when written into a different claim without anyone
35
+ editing it.
36
+
37
+ ### §10.1 minimum local-verification set
38
+
39
+ `axiamMiddleware` / `axiamPlugin` (and the `requireAuth` / `requireAccess` / `requireRole`
40
+ helpers built on them) funnel through `authenticateRequest`, which applies **every** §10.1
41
+ rule on every inbound token: EdDSA `alg` pinned before the JWKS is consulted, a REQUIRED
42
+ `exp` (`jose` only checks `exp` *if present*, so `requiredClaims: ['exp']` is passed
43
+ explicitly), `nbf` honoured when present, `tenant_id` asserted against the session's
44
+ configured tenant, `iss`/`aud` checked when configured, all under a named 60-second
45
+ `CLOCK_SKEW_LEEWAY_SEC`.
46
+
47
+ Because the `/oauth2/jwks` trust anchor is **organization-wide**, the session guarding a
48
+ resource server must be configured with the tenant **UUID** (`tenantId`), since that is
49
+ what the `tenant_id` claim carries. `expectedIssuer` / `expectedAudience` are optional and
50
+ unset by default:
51
+
52
+ ```ts
53
+ const client = createNodeClient({
54
+ baseUrl: 'https://iam.example.com',
55
+ tenantId: '…-uuid-…', // §10.1 rule 4 — compared against the tenant_id claim
56
+ expectedAudience: 'axiam:user', // §10.1 rule 6 — optional, recommended
57
+ });
58
+ app.use(axiamMiddleware(client.session));
59
+ ```
60
+
61
+ `verifier.verifySignatureOnlyUnchecked(token)` is the §10.1 raw signature-only primitive,
62
+ for integrators implementing their own policy. It checks the signature and nothing else —
63
+ never use it to guard a route.
21
64
 
22
65
  See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contract.
23
66
 
@@ -27,6 +70,39 @@ See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contra
27
70
  npm install axiam-sdk
28
71
  ```
29
72
 
73
+ ## Supported Node versions
74
+
75
+ | | Version | Why this one |
76
+ |---|---|---|
77
+ | **Floor** | 22 | The oldest release line still receiving security fixes. Node 18 went EOL 2025-04-30 and Node 20 on 2026-04-30. `engines.node` is `>=22`. |
78
+ | **Newest** | 26 | The current release line (out 2026-05, promoted to LTS 2026-10), and the line `@types/node` is pinned to. |
79
+
80
+ Node 24 (Active LTS) sits between the two and is supported.
81
+
82
+ **The SDK is built against the floor, and runs on everything up to the newest.**
83
+ Those are two different claims, and CI proves each separately: the gating
84
+ matrix in `sdk-ci-typescript.yml` runs `build`, `typecheck`, the full test
85
+ suite and the CommonJS-require smoke tests on **22 and on 26**. The floor leg
86
+ is what stops a Node 24-only built-in from slipping in; the newest leg is what
87
+ catches a removal, and is the runtime `tsc` is typechecking against. A line
88
+ between two green legs is interpolation, which is why the matrix is two legs
89
+ rather than four — the runtime-independent gates (bundle-grep, the token-leak
90
+ and TLS-lint greps, `npm audit`, the docs gate and the publish dry-run) run
91
+ once, on the floor.
92
+
93
+ If you are on a newer runtime than the floor you need do nothing: the
94
+ published bundle targets ES2022 and is forward-compatible, and the newest leg
95
+ is the evidence.
96
+
97
+ The browser persona (`axiam-sdk/browser`) has no Node floor at all — it needs
98
+ a runtime with `fetch`, `crypto.subtle` and `TextEncoder`, which every
99
+ currently supported browser has.
100
+
101
+ `test/core/versionPolicy.test.ts` fails the build if `engines.node`, the
102
+ `@types/node` pin and the CI matrix ever stop agreeing. They are three
103
+ independent declarations of the same fact and nothing else compares them —
104
+ before that test existed, all three disagreed at once.
105
+
30
106
  ## Two personas, tree-shaken subpath entries
31
107
 
32
108
  `axiam-sdk` ships as **one package with two personas**, each reachable through its own
@@ -37,9 +113,11 @@ never contains `@grpc/grpc-js` or `amqplib`):
37
113
  | Entry point | Persona | Contents |
38
114
  |-------------------------|-----------------------------|---------------------------------------------------------------------------|
39
115
  | `axiam-sdk` / `axiam-sdk/rest` | Browser + Node, REST-only | `AxiamClient`: `login`/`verifyMfa`/`refresh`/`logout`, `can`/`batchCheck` over the FND-04 REST authz endpoint |
40
- | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
116
+ | `axiam-sdk/browser` | Browser only | The WebAuthn **platform ceremony** — `webauthnRegister`/`webauthnLogin`/`webauthnDiscoverableLogin` over `navigator.credentials` (CONTRACT.md §24.6b). The relying-party operations themselves are on `AxiamClient` in `/rest` and work in Node too. |
117
+ | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` and `UserInfoGrpcClient.getUserInfo` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
41
118
  | `axiam-sdk/amqp` | Node only | `consume()` — HMAC-verified AMQP audit/authz event consumer (CONTRACT.md §8) |
42
- | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) — plus `requireAuth`/`requireAccess`/`requireRole` declarative route guards (CONTRACT.md §11) |
119
+ | `axiam-sdk/node` | Node only | The Node persona (`createNodeSession`/`createNodeClient`, cookie jar + local-JWKS verifier) plus the **OIDC/SSO relying-party helpers** — `OidcClient`, `MemoryOidcStateStore`, PKCE primitives (CONTRACT.md §12) |
120
+ | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) — plus `requireAuth`/`requireAccess`/`requireRole` declarative route guards (CONTRACT.md §11) and the `oidcLoginHandlers`/`oidcLoginPlugin` "Login with AXIAM" routes (CONTRACT.md §12) |
43
121
  | `axiam-sdk/nestjs` | Node only, optional | `@RequireAccess`/`@RequireAuth`/`@RequireRole` metadata decorators + `AxiamGuard` (CONTRACT.md §11, Tier 2) |
44
122
 
45
123
  **Browser code should only ever import from `axiam-sdk` or `axiam-sdk/rest`.** Importing
@@ -58,11 +136,43 @@ import { AxiamClient } from 'axiam-sdk';
58
136
  const client = new AxiamClient({
59
137
  baseUrl: 'https://iam.example.com',
60
138
  tenantSlug: 'acme',
139
+ // Organization context is required for login/refresh — a tenant slug is only
140
+ // unique within an organization (CONTRACT.md §5.1). Pass orgSlug (or orgId).
141
+ orgSlug: 'acme',
61
142
  // customCa is optional — PEM-encoded CA cert for self-signed dev environments (§6)
62
143
  // customCa: pemString,
63
144
  });
64
145
  ```
65
146
 
147
+ ### mTLS / client certificates (Node only)
148
+
149
+ For IoT devices and service accounts authenticated by **mutual TLS** (CONTRACT.md §6.1),
150
+ pass a PEM client-certificate chain and its PEM private key. The identity is presented on
151
+ **both** the REST and gRPC transports of the same client. Presenting a client certificate
152
+ **never** relaxes server verification — strict TLS stays on.
153
+
154
+ ```typescript
155
+ import { readFileSync } from 'node:fs';
156
+ import { AxiamClient } from 'axiam-sdk';
157
+
158
+ const client = new AxiamClient({
159
+ baseUrl: 'https://iam.example.com',
160
+ tenantSlug: 'acme',
161
+ orgSlug: 'acme', // organization context required for login/refresh (CONTRACT.md §5.1)
162
+ clientCert: readFileSync('device.crt', 'utf8'), // PEM certificate chain
163
+ clientKey: readFileSync('device.key', 'utf8'), // PEM private key (PKCS#8 or PKCS#1)
164
+ // customCa: readFileSync('ca.crt', 'utf8'), // optional server-trust CA (§6)
165
+ });
166
+ ```
167
+
168
+ - `clientCert` and `clientKey` are **all-or-nothing** — providing exactly one throws at
169
+ construction, and each is validated to be PEM-shaped (as `customCa` is).
170
+ - The private key is secret material: it is passed straight to the Node TLS stack and is
171
+ never retained on a public property, logged, or serialized (CONTRACT.md §7).
172
+ - **Node only.** Browsers cannot present a client certificate from JavaScript, so the
173
+ browser build validates the PEM shape then ignores `clientCert`/`clientKey` — exactly as
174
+ it already ignores `customCa`.
175
+
66
176
  ## Usage per persona
67
177
 
68
178
  ### Browser — login + authz (`axiam-sdk` / `axiam-sdk/rest`)
@@ -70,7 +180,7 @@ const client = new AxiamClient({
70
180
  ```typescript
71
181
  import { AxiamClient } from 'axiam-sdk';
72
182
 
73
- const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
183
+ const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme', orgSlug: 'acme' });
74
184
 
75
185
  const result = await client.login(email, password);
76
186
  switch (result.status) {
@@ -121,6 +231,32 @@ grpcClient.close();
121
231
  The gRPC channel is constructed once and reused; `UNAUTHENTICATED` responses transparently
122
232
  share the same single-flight refresh guard as the REST persona (CONTRACT.md §9).
123
233
 
234
+ #### gRPC userinfo (`UserInfoGrpcClient.getUserInfo`, CONTRACT.md §1.1)
235
+
236
+ `getUserInfo` is a **gRPC-only** operation (contract 1.3) — the low-latency counterpart of
237
+ the server's REST `/oauth2/userinfo` endpoint. It takes no arguments; the caller's identity
238
+ is derived server-side from the bearer token. It reuses the same channel, auth + `x-tenant-id`
239
+ metadata interceptor, and single-flight refresh guard as `AuthzGrpcClient` (a co-located
240
+ client built from the same session shares the pooled connection).
241
+
242
+ ```typescript
243
+ import { UserInfoGrpcClient, createNodeSession } from 'axiam-sdk/grpc';
244
+
245
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
246
+ // ... after a successful login() on an AxiamClient sharing this session ...
247
+ const userInfoClient = new UserInfoGrpcClient(session, { baseUrl: 'https://iam.example.com' });
248
+
249
+ const info = await userInfoClient.getUserInfo();
250
+ // info: { sub, tenantId, orgId, email?, preferredUsername? }
251
+ // email is present only with the "email" scope, preferredUsername only with "profile".
252
+
253
+ userInfoClient.close();
254
+ ```
255
+
256
+ Calling `getUserInfo()` with no token present raises `AuthError` client-side, without a wire
257
+ call (CONTRACT.md §1.1). A `UNAUTHENTICATED` response drives exactly one refresh + one retry,
258
+ identical to `checkAccess`.
259
+
124
260
  ### Node — AMQP consumer (`axiam-sdk/amqp`)
125
261
 
126
262
  ```typescript
@@ -128,14 +264,210 @@ import { consume, Sensitive } from 'axiam-sdk/amqp';
128
264
 
129
265
  const signingKey = new Sensitive(Buffer.from(process.env.AXIAM_AMQP_SIGNING_KEY ?? '', 'hex'));
130
266
 
131
- await consume('amqp://localhost:5672', 'axiam.audit.events', signingKey, async (event) => {
132
- // Only a verified event ever reaches this closure — HMAC-SHA256
133
- // signature checked and stripped by the SDK before your handler runs
134
- // (CONTRACT.md §8). Verification failures are nacked-without-requeue.
135
- console.log('verified audit event:', event);
136
- });
267
+ await consume(
268
+ // §8b: amqps:// only, enforced — a plaintext URL is refused before a socket
269
+ // opens, and there is no fallback for it to take.
270
+ 'amqps://localhost:5671',
271
+ 'axiam.audit.events',
272
+ signingKey,
273
+ async (event) => {
274
+ // Only a verified event ever reaches this closure — HMAC-SHA256
275
+ // signature checked and stripped by the SDK before your handler runs
276
+ // (CONTRACT.md §8). Verification failures are nacked-without-requeue.
277
+ console.log('verified audit event:', event);
278
+ },
279
+ // Optional. The PEM bundle for a privately issued broker certificate — the
280
+ // common in-cluster case (§8b rule 2), and the only TLS knob this SDK has.
281
+ { tls: { caCert: readFileSync('/etc/axiam/broker-ca.pem', 'utf8') } },
282
+ );
283
+ ```
284
+
285
+ #### Transport security (§8b)
286
+
287
+ `consume()` and `reactorServe()` both require `amqps://` and enforce it before
288
+ any socket is opened. HMAC signing (§8) gives authenticity and replay
289
+ protection across broker hops; TLS gives confidentiality. Both are required and
290
+ neither substitutes for the other — a signed `AuthzRequest` still names its
291
+ subject, resource and action in cleartext on an unencrypted wire.
292
+
293
+ | Option | Meaning |
294
+ |---|---|
295
+ | `tls.caCert` | PEM bundle for a privately issued broker certificate. Omit for a publicly issued one (Node's bundled roots verify it). |
296
+ | `tls.clientCert` + `tls.clientKey` | Mutual TLS toward the broker. All-or-nothing: half an identity is rejected before dialling. |
297
+
298
+ There is deliberately no verification-skip option, under any name (§8b rule 4).
299
+ A switch like that appears in a dev compose file, works, and travels unchanged
300
+ into production, where it turns TLS into an expensive no-op against precisely
301
+ the attacker TLS exists to stop. `caCert` covers the legitimate reason people
302
+ reach for one.
303
+
304
+ ### Node — reactors, AMQP extension actors (`axiam-sdk/amqp`, CONTRACT.md §22)
305
+
306
+ A **reactor** is an external process that subscribes to named hook events on the AMQP bus and
307
+ answers back — allow, deny, or a field-allow-listed mutation — inside a timeout the server
308
+ declared. It is AXIAM's answer to Zitadel Actions and Keycloak SPIs, and the difference is the
309
+ whole design: those load third-party code *into* the authorization server, and this keeps it
310
+ outside, reachable only through a signed reply schema the server validates before it believes
311
+ a word of it.
312
+
313
+ ```typescript
314
+ import { Sensitive } from 'axiam-sdk/amqp';
315
+ import { REACTOR_EVENTS, allow, deny, mutate, reactorServe } from 'axiam-sdk/amqp';
316
+
317
+ const signingKey = new Sensitive(Buffer.from(process.env.AXIAM_AMQP_SIGNING_KEY_HEX ?? '', 'hex'));
318
+
319
+ await reactorServe(
320
+ {
321
+ amqpUrl: 'amqps://reactor:secret@broker.example.com:5671',
322
+ tenantId: '11111111-1111-1111-1111-111111111111',
323
+ reactorId: '99999999-9999-9999-9999-999999999999',
324
+ signingKey, // the tenant's HKDF-derived AMQP subkey, never the master key
325
+ },
326
+ (event) => {
327
+ switch (event.event) {
328
+ // token.pre_issue is mutable — the `ext.` namespace, and nothing else.
329
+ case REACTOR_EVENTS.TOKEN_PRE_ISSUE:
330
+ return mutate({ 'ext.cost_center': '42' });
331
+ // login.post_auth is veto-only, plus step-up.
332
+ case REACTOR_EVENTS.LOGIN_POST_AUTH:
333
+ return deny('embargoed region');
334
+ default:
335
+ return allow();
336
+ }
337
+ },
338
+ );
339
+ ```
340
+
341
+ #### Binding handlers per event (§22.14)
342
+
343
+ The `switch` above is the shape every multi-event reactor grows, and its `default:` arm —
344
+ `return allow()` — answers on behalf of code that never ran. That is the defect §22.10
345
+ rule 2 forbids the *runtime* from committing, relocated into your file where the rule does
346
+ not reach it: an operator who set `fail_closed` on the registration has it defeated there.
347
+
348
+ `reactorHandlers` is §22.14's declarative form, in the spirit of the §11 declarative
349
+ authorization helpers:
350
+
351
+ ```typescript
352
+ import { REACTOR_EVENTS, reactorHandlers, reactorServe } from 'axiam-sdk/amqp';
353
+
354
+ await reactorServe(
355
+ options,
356
+ reactorHandlers({
357
+ [REACTOR_EVENTS.TOKEN_PRE_ISSUE]: (event) => mutate({ 'ext.cost_center': '42' }),
358
+ [REACTOR_EVENTS.LOGIN_POST_AUTH]: async (event) => deny('embargoed region'),
359
+ }),
360
+ );
361
+ ```
362
+
363
+ - **A misspelled event is a compile error**, because the map's key type is
364
+ `ReactorEventName` — and it is re-checked at runtime for JavaScript callers, who get no
365
+ such help. That runtime check is also how the three hot-path operations §22.7 excludes are
366
+ refused: they are in no registry row.
367
+ - **An unbound event abstains** — no reply, and the registration's `failure_policy` decides
368
+ (§22.8), exactly as it decides a timeout. Never a synthesized `allow`.
369
+ - Several maps may be passed (`reactorHandlers(tokenHandlers, loginHandlers)`) so handlers
370
+ can be split across modules; binding the same event twice throws rather than silently
371
+ overwriting.
372
+
373
+ It is pure sugar: the value it produces is exactly the `ReactorHandler` `reactorServe`
374
+ already takes. It opens nothing, verifies nothing, signs nothing, does not filter a patch,
375
+ and a handler's own rejection reaches the runtime unchanged so nothing is published.
376
+
377
+ See [`examples/reactor/index.ts`](examples/reactor/index.ts) for a complete three-hook reactor
378
+ with graceful shutdown and a telemetry hook.
379
+
380
+ #### The five hookable events, and their allow-lists
381
+
382
+ | Event | Mutable | Complete allow-list | Default failure policy |
383
+ |---|---|---|---|
384
+ | `token.pre_issue` | yes | the **`ext.`** namespace only | `fail_open` |
385
+ | `login.post_auth` | no | — (veto, or `require_mfa`) | `fail_closed` |
386
+ | `user.pre_create` | yes | `username`, `email`, `metadata.` | `fail_closed` |
387
+ | `user.pre_update` | yes | `username`, `email`, `metadata.` | `fail_closed` |
388
+ | `grant.pre_assign` | no | — (veto only) | `fail_closed` |
389
+
390
+ An entry ending in `.` is a **namespace prefix** and needs at least one character after the
391
+ dot: `ext.` admits `ext.department` and `ext.a.b.c`, and refuses `ext.` itself, `ext`, `extra`,
392
+ `external_id` and `evil.ext.department`. So a reactor can never reach `sub`, `aud`, `exp`,
393
+ `scope` or any other standard claim — a **correctly signed** reply setting `sub` is refused
394
+ exactly as a forged one is.
395
+
396
+ Registrations that name no `failure_policy` get **the strictest default among their events**,
397
+ in either array order — `defaultFailurePolicyFor([...])` computes it, and "take the first
398
+ event's default" is specifically what §22.8 forbids, because it lets the order of a JSON array
399
+ decide whether an unreachable fraud check passes.
400
+
401
+ #### `authz.check` is not hookable, and this SDK does not pretend otherwise
402
+
403
+ `authz.check`, `authz.check_batch` and `token.introspect` are absent from `EVENT_REGISTRY`,
404
+ from `REACTOR_EVENTS` and from every example here (§22.7, a normative MUST NOT). A reactor
405
+ round-trip is milliseconds; the check path's budget is microseconds. An application that needs
406
+ external input on an authorization decision writes a **deny grant**, which the engine
407
+ evaluates in the hot path at hot-path cost — and there is deliberately no client-side
408
+ interceptor in this SDK offering itself as the reactor equivalent.
409
+
410
+ #### What the runtime guarantees
411
+
412
+ - **Both directions are signed.** The server signs the event with the tenant's HKDF-derived
413
+ AMQP subkey; the reactor signs its reply with the same key. An unsigned or stale reply is
414
+ not a weak reply — the server discards it as though the reactor had never answered. Every
415
+ event is verified (`key_version >= 2`, MAC, ±300 s freshness, nonce seen-set) *before* your
416
+ handler is called.
417
+ - **Two canonicalization quirks, both of which are silent failures if missed.** First, a
418
+ reactor body signs `hmac_signature` as **`null`**, where §8's own two message types omit it.
419
+ Second — and this one is TypeScript's alone — `Date.prototype.toISOString()` always emits
420
+ three fractional digits, while the server's `chrono` emits none on a whole second; a reply
421
+ timestamped `…T12:00:00.000Z` is re-serialized server-side as `…T12:00:00Z` and its MAC
422
+ fails with no other symptom. `toChronoRfc3339()` is the fix and the runtime always uses it.
423
+ Both are pinned by server-generated vectors rather than by memory — see
424
+ [`testdata/reactor_v2_reference_vectors.json`](testdata/reactor_v2_reference_vectors.json)
425
+ and [`test/amqp/reactor/vectors.test.ts`](test/amqp/reactor/vectors.test.ts).
426
+ - **It declares no topology.** No `assertQueue`, no `assertExchange`, no `bindQueue` — the
427
+ server owns all three, and the `ReactorChannel` seam this runtime is written against does
428
+ not even offer them. A reactor that can bind is a reactor that can bind itself to
429
+ `*.token.pre_issue` and read another tenant's issuance events.
430
+ - **It fails closed on its own errors.** A handler that throws, a body that will not parse, a
431
+ window that has already closed: each publishes **nothing**, so the registration's
432
+ `failure_policy` decides. Synthesizing an `allow` would override the operator's
433
+ `fail_closed` setting from inside the library. `abstain()` is the explicit form of the same
434
+ thing.
435
+ - **It does not filter your patch.** One forbidden key rejects the whole patch server-side;
436
+ pruning it here would leave you believing a field was set when it was dropped. Check
437
+ yourself with `patchFieldAllowed(spec, field)` if you want to know before you send.
438
+ - **It honours `timeout_ms`.** The handler runs inside the window the server declared, and a
439
+ reply whose window has closed is abandoned rather than published late.
440
+ - **Shutdown drains (§18).** Pass an `AbortSignal`; aborting it cancels the consumer, lets
441
+ every dispatch already running finish — handler, signature, publish — and only then closes
442
+ the channel and connection.
443
+
444
+ #### Registering a reactor (§22.9)
445
+
446
+ Registration is a REST admin call, not part of this runtime:
447
+
448
+ ```bash
449
+ curl -X POST https://axiam.example.com/api/v1/reactors \
450
+ -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
451
+ -d '{"name":"fraud-check","events":["login.post_auth"],"mode":"intercept","timeout_ms":500}'
137
452
  ```
138
453
 
454
+ The response's `id` is what `reactorId` takes, and the server declares the queue.
455
+ `timeout_ms` defaults to **500** and is refused outside `1…5000`; the chain's wall-clock
456
+ ceiling is **5000 ms** and the per-tenant in-flight cap is **64**. This SDK exposes those as
457
+ constants (`DEFAULT_REACTOR_TIMEOUT_MS`, `MAX_REACTOR_TIMEOUT_MS`,
458
+ `DEFAULT_REACTOR_MAX_IN_FLIGHT`) but ships **no typed client for the CRUD endpoints** — call
459
+ them through the REST client, and let the server validate; §22.9 explicitly warns against
460
+ re-deriving `PUT` merge semantics or the `failure_policy` re-derivation client-side.
461
+
462
+ #### Logging
463
+
464
+ The `payload`, `patch`, `reason` and `decision` are tenant business data — readable by design,
465
+ since a handler that cannot inspect the event cannot decide anything, but this runtime never
466
+ logs them at info level and yours should not either (§22.12). The signing key is
467
+ `Sensitive<Buffer>`, is never logged at any level, and never appears in an error payload.
468
+ `nonce`, `correlation_id` and `hmac_signature` are not secrets and may be logged for
469
+ correlation.
470
+
139
471
  ### Express middleware (`axiam-sdk/middleware`)
140
472
 
141
473
  ```typescript
@@ -285,10 +617,1127 @@ See `examples/nestjs-app.ts` for a complete, compiling example (including the
285
617
  More runnable examples (all compiling under `tsc --noEmit -p examples/tsconfig.json`) live
286
618
  in `examples/` at the package root.
287
619
 
620
+ ## OIDC / SSO relying-party helpers (`axiam-sdk/node`, CONTRACT.md §12)
621
+
622
+ Everything a backend needs to offer **"Login with AXIAM"** — authorization code + PKCE
623
+ against AXIAM's own OIDC provider — plus service-account M2M login, token
624
+ introspection/revocation, and the upstream-IdP federation endpoints. Node-only: PKCE uses
625
+ `node:crypto` and ID-token validation uses `jose`, so these deliberately do not hang off the
626
+ browser-safe `AxiamClient` (a `/rest` browser bundle stays free of Node code, proven by CI).
627
+
628
+ ```typescript
629
+ import { createNodeSession, createOidcClient, MemoryOidcStateStore } from 'axiam-sdk/node';
630
+
631
+ // One session carries the cookie jar (§4), TLS config (§6) and refresh guard (§9)
632
+ // that the OIDC client reuses rather than duplicating.
633
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantId, orgId });
634
+
635
+ const oidc = createOidcClient(session, {
636
+ clientId: 'my-web-app',
637
+ clientSecret: process.env.AXIAM_CLIENT_SECRET, // omit for a public client
638
+ });
639
+ ```
640
+
641
+ ### The nine operations
642
+
643
+ | Operation | Wire call | Notes |
644
+ |-----------|-----------|-------|
645
+ | `oidcDiscover()` | `GET /.well-known/openid-configuration` | Cached per origin, TTL ≥ 5 min, concurrent calls share one fetch |
646
+ | `oidcBegin({ configuration, redirectUri, scope?, extraParams? })` | *none — pure local computation* | CSPRNG `state`/`nonce` (256-bit) + PKCE **S256** challenge; returns `{ url, state, nonce, codeVerifier }` |
647
+ | `oidcExchange({ code, codeVerifier, nonce, redirectUri, tenantId?, configuration? })` | `POST /oauth2/token?tenant_id=…` | `grant_type=authorization_code`; validates the ID token in full before returning |
648
+ | `oidcRefresh({ refreshToken, scope?, tenantId?, configuration? })` | `POST /oauth2/token?tenant_id=…` | `grant_type=refresh_token`, under the §9 single-flight guard. **Distinct from `AxiamClient.refresh()`**, which drives the cookie-session path |
649
+ | `loginClientCredentials({ scope?, tenantId?, adoptAsCredential?, configuration? })` | `POST /oauth2/token?tenant_id=…` | Service-account M2M login; no `openid` scope, no ID token. `adoptAsCredential: true` uses the token as the session's bearer credential |
650
+ | `introspect({ token, tokenTypeHint?, tenantId?, configuration? })` | `POST /oauth2/introspect?tenant_id=…` | RFC 7662; requires a `clientSecret` |
651
+ | `revoke({ token, tokenTypeHint?, tenantId?, configuration? })` | `POST /oauth2/revoke?tenant_id=…` | RFC 7009; returns `void` and is **idempotent** — a `200` for an unknown token is success |
652
+ | `ssoStart({ federationConfigId, redirectUri, tenantId?/tenantSlug?, orgId?/orgSlug? })` | `POST /api/v1/auth/federation/oidc/start` | Upstream-IdP SSO step 1; returns `{ authorizeUrl, state, expiresInSecs }` |
653
+ | `ssoComplete({ state, code })` | `POST /api/v1/auth/federation/oidc/callback` | Step 2; the session arrives as `Set-Cookie`, so it needs the cookie-jar-backed Node session |
654
+
655
+ Wire details worth knowing: the token/introspection/revocation endpoints are
656
+ **form-encoded** (not JSON) and take `tenant_id` as a **required query parameter** in **UUID**
657
+ form — a slug-only client raises `AuthError` client-side rather than sending a slug. Client
658
+ authentication is `client_secret_post` (never HTTP Basic). Endpoint URLs always come from the
659
+ discovery document, never hardcoded.
660
+
661
+ ### The caller owns the login state
662
+
663
+ `oidcBegin` and `oidcExchange` store **nothing** — no `state`, `nonce` or `code_verifier` in
664
+ the SDK, in process-global state, or in any implicit cache. You keep them (typically in your
665
+ own HTTP session) and pass `nonce` + `codeVerifier` back into `oidcExchange`:
666
+
667
+ ```typescript
668
+ // 1. login route
669
+ const configuration = await oidc.oidcDiscover();
670
+ const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile email' });
671
+ req.session.oidc = { state: request.state, nonce: request.nonce, verifier: request.codeVerifier };
672
+ res.redirect(request.url);
673
+
674
+ // 2. callback route — check the returned `state` matches, then exchange
675
+ const tokens = await oidc.oidcExchange({
676
+ code: String(req.query.code),
677
+ codeVerifier: req.session.oidc.verifier,
678
+ nonce: req.session.oidc.nonce,
679
+ redirectUri,
680
+ });
681
+ console.log(tokens.idClaims?.sub); // validated ID-token subject
682
+ ```
683
+
684
+ `MemoryOidcStateStore` is an optional, opt-in reference store for that bookkeeping (10-minute
685
+ TTL, single-use `consume(state)` — mirroring the server's own `federation_login_state`
686
+ semantics). It is single-process; use a shared store (Redis, a database) behind a load
687
+ balancer by implementing `OidcStateStore` yourself. The core operations never require one.
688
+
689
+ ### Framework glue
690
+
691
+ ```typescript
692
+ import { oidcLoginHandlers } from 'axiam-sdk/middleware';
693
+
694
+ const { login, callback } = oidcLoginHandlers({
695
+ client: oidc,
696
+ store: new MemoryOidcStateStore(),
697
+ redirectUri: 'https://app.example.com/auth/callback',
698
+ scope: 'openid profile email',
699
+ // Establishing YOUR app session is your decision — the SDK validates the login
700
+ // and hands you the token set.
701
+ onSuccess: (tokens) => establishMySession(String(tokens.idClaims?.sub)),
702
+ });
703
+
704
+ app.get('/auth/login', login); // 302 -> AXIAM /oauth2/authorize
705
+ app.get('/auth/callback', callback); // consume state -> exchange -> validate ID token
706
+ ```
707
+
708
+ Fastify gets the same flow as a plugin: `fastify.register(oidcLoginPlugin({ …, loginPath,
709
+ callbackPath }))`. Both are thin adapters over the shared `beginOidcLogin`/`completeOidcLogin`
710
+ core, so they cannot drift. Failure mapping is identical: `400` malformed callback, `401`
711
+ authentication failure (unknown/expired/replayed state, IdP error, ID-token failure, OAuth2
712
+ protocol error), `503` when AXIAM is unreachable — never a silent success.
713
+
714
+ The login handler reads an optional `?returnTo=` and stores it with the login state.
715
+ **Validate or allowlist that value in your application** if you accept it from user input —
716
+ an unchecked redirect target is an open-redirect vector, and the SDK cannot know which
717
+ destinations your app considers safe.
718
+
719
+ ### ID-token validation (always on)
720
+
721
+ Every ID token is validated before `oidcExchange` returns, per CONTRACT.md §12.4:
722
+ `alg` must be exactly `EdDSA` (`none` and everything else rejected, checked from the header
723
+ *before* any signature work); the Ed25519 signature must verify against the key selected by
724
+ `kid` from the document's `jwks_uri` (one JWKS re-fetch on an unknown `kid`, then fail);
725
+ `iss` must equal the discovery document's `issuer` by exact string comparison; `aud` must
726
+ contain the `client_id` (with `azp` required when there are multiple audiences); `exp`/`iat`/
727
+ `nbf` must hold within at most 60 s of clock skew; and the `nonce` claim must match the
728
+ `oidcBegin` nonce (constant-time). Any failure raises `AuthError` with a stable
729
+ `reason` code — `invalid_alg`, `unknown_kid`, `invalid_signature`, `invalid_issuer`,
730
+ `invalid_audience`, `token_expired`, `nonce_mismatch` — and **discards the entire token set**;
731
+ the access and refresh tokens from that response never reach the caller. There is no option
732
+ to disable or skip this.
733
+
734
+ ```typescript
735
+ try {
736
+ const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });
737
+ } catch (err) {
738
+ if (err instanceof OAuthProtocolError) {
739
+ console.error(err.error, err.errorDescription); // e.g. "invalid_grant", "code expired"
740
+ } else if (err instanceof AuthError) {
741
+ console.error(err.reason); // e.g. "nonce_mismatch"
742
+ }
743
+ }
744
+ ```
745
+
746
+ `access_token`, `refresh_token`, `id_token`, `client_secret` and `code_verifier` are all
747
+ `Sensitive<T>` (CONTRACT.md §12.5) — they redact to `[SENSITIVE]` in `toString()`,
748
+ `JSON.stringify()` and `console.log`. `state` and `nonce` are not secrets and stay plain
749
+ strings.
750
+
751
+ See `examples/express-oidc-login.ts` for a complete, runnable example.
752
+
753
+ ## OPAQUE (CONTRACT.md §23)
754
+
755
+ `loginOpaque` proves the password without sending it. What crosses the wire is
756
+ a blinded group element and a MAC, neither useful without the account's
757
+ registration record **and** the tenant's OPRF seed.
758
+
759
+ ```ts
760
+ const result = await client.loginOpaque('alice', 'correct horse battery staple');
761
+ ```
762
+
763
+ It takes the same arguments as `login` and returns the same `LoginResult`, MFA
764
+ branch included, so switching a tenant to OPAQUE needs no change to how the
765
+ result is handled.
766
+
767
+ ### Falling back — and when not to
768
+
769
+ Fall back to `login()` when the tenant does not offer OPAQUE, or when this
770
+ installation cannot perform it. Both are a `NetworkError`, deliberately **not**
771
+ an `AuthError`, so neither can be mistaken for a bad password:
772
+
773
+ ```ts
774
+ let result;
775
+ try {
776
+ result = await client.loginOpaque(user, password);
777
+ } catch (err) {
778
+ if (!(err instanceof NetworkError)) throw err; // <- not a fallback case
779
+ result = await client.login(user, password);
780
+ }
781
+ ```
782
+
783
+ The `if` is the important line. **Any other error is a failed login**, and
784
+ retrying it over `login()` yourself would hand the plaintext to a server that
785
+ just failed to prove it holds the record.
786
+
787
+ One case is handled for you. `login/start` returns the tenant's `mode`, and when
788
+ it is `"optional"` — the mid-migration state, where accounts acquire a
789
+ registration record only as their passwords are next set — a failed exchange is
790
+ not yet a verdict on the credentials, so `loginOpaque` retries over
791
+ `POST /api/v1/auth/login` itself and returns that call's outcome (CONTRACT.md
792
+ §23.4 rule 7). Under `"required"`, and against a server too old to send `mode`
793
+ at all, it fails closed exactly as before. `mode` is **not** downgrade
794
+ protection: a hostile server that wanted the plaintext could answer `404` and
795
+ get the fallback above regardless. `required` is what closes that, server-side,
796
+ by refusing `/auth/login` for every principal in the tenant.
797
+
798
+ ### What this buys, and what it does not
799
+
800
+ OPAQUE closes holes TLS 1.3 does not:
801
+
802
+ - a TLS-terminating reverse proxy, ingress controller, CDN or service mesh sees
803
+ every plaintext password today; under OPAQUE it sees a blinded group element;
804
+ - an accidental request-body log, a heap dump or a crash reporter can no longer
805
+ capture a plaintext password, because the server never has one;
806
+ - **a stolen record database is not offline-crackable on its own.** Recovering a
807
+ password additionally requires the tenant's OPRF seed, encrypted at rest
808
+ separately. This is the property SRP could not offer, and the main reason
809
+ AXIAM replaced it.
810
+
811
+ It does **not** protect against a compromised AXIAM server, and in a browser it
812
+ does not protect against AXIAM serving malicious JavaScript.
813
+
814
+ ### Enrolment
815
+
816
+ The server cannot build a record — it never sees the plaintext — so one has to
817
+ be sent with any request that sets a password:
818
+
819
+ ```ts
820
+ const opaque = await client.opaqueEnrollment(newPassword);
821
+ // send `opaque` as the request body's `opaque` field
822
+ ```
823
+
824
+ One argument, where the SRP verifier this replaces took four. There is no
825
+ `identity` — a record binds to a credential identifier the server chooses, so
826
+ enrolling against an email can no longer produce something no login can satisfy,
827
+ and a later rename cannot invalidate it — and no group or KDF, because the
828
+ server names them in its `register/start` response and this call honours what
829
+ it names.
830
+
831
+ It is `async` because that response has to be fetched: OPAQUE's envelope is
832
+ sealed under the server's oblivious PRF, so there is no offline computation that
833
+ produces a valid record. The SRP verifier needed no network at all.
834
+
835
+ ### This SDK does not implement OPAQUE
836
+
837
+ CONTRACT.md §23.1 forbids it. SRP was hand-written eleven times because it is
838
+ modular arithmetic every language has; OPAQUE needs an oblivious PRF,
839
+ `hash_to_curve`, `expand_message_xmd`, an envelope construction and a
840
+ three-message AKE. `core/srp.ts` — 419 lines of it — is replaced by a loader
841
+ around `@axiam/opaque-wasm`, the WebAssembly build of the same implementation
842
+ the AXIAM server links and every other SDK binds.
843
+
844
+ ### Runtime requirements
845
+
846
+ `@axiam/opaque-wasm` is an **optional peer dependency**:
847
+
848
+ ```bash
849
+ npm install @axiam/opaque-wasm
850
+ ```
851
+
852
+ Optional, because an installation that never touches the OPAQUE path should not
853
+ be made to carry a WebAssembly module. When it is absent, `opaqueAvailable()`
854
+ resolves to `false` and `loginOpaque` rejects with a `NetworkError` — reporting
855
+ rather than throwing at login time is what §23.1 asks of an SDK whose native
856
+ artifact did not load, and it is why the fallback above works unchanged.
857
+
858
+ ```ts
859
+ if (!(await client.opaqueAvailable())) {
860
+ // use login() — this installation cannot do OPAQUE
861
+ }
862
+ ```
863
+
864
+ It is imported lazily and memoized, so a consumer who never calls OPAQUE does
865
+ not pay the wasm payload at module-load time, and two concurrent logins do not
866
+ instantiate it twice.
867
+
868
+ ### Cost
869
+
870
+ `loginOpaque` runs the tenant's key-stretching function: Argon2id at 19 MiB and
871
+ t=2 by default, tens to hundreds of milliseconds of synchronous work. That cost
872
+ is the point — it is what makes a stolen record expensive to attack even by
873
+ someone holding the OPRF seed. In a browser, consider a Web Worker.
874
+
875
+ ## WebAuthn and passkeys (CONTRACT.md §24)
876
+
877
+ A passkey ceremony is **two exchanges stacked**: one with an *authenticator*,
878
+ which needs a platform API, and one with *AXIAM*, which is four ordinary JSON
879
+ round trips. This SDK splits along that seam, and where you import from tells
880
+ you which half you get.
881
+
882
+ | | Where | Runs in |
883
+ |---|---|---|
884
+ | The six relying-party operations | `AxiamClient`, from `axiam-sdk` / `axiam-sdk/rest` | **Browser and Node** |
885
+ | The ceremony (`navigator.credentials`) | `axiam-sdk/browser` | Browser only |
886
+
887
+ The Node half is not a consolation prize. A service completing a ceremony that
888
+ ran on a handset — an Android app, an iOS app, a hardware client — is the
889
+ relying party, exactly as a browser is, and it never touches
890
+ `navigator.credentials`.
891
+
892
+ ### The browser: three calls
893
+
894
+ ```ts
895
+ import { AxiamClient } from 'axiam-sdk/rest';
896
+ import {
897
+ isWebauthnSupported,
898
+ webauthnRegister,
899
+ webauthnLogin,
900
+ webauthnDiscoverableLogin,
901
+ classifyWebauthnError,
902
+ webauthnErrorMessage,
903
+ } from 'axiam-sdk/browser';
904
+
905
+ const client = new AxiamClient({ baseUrl, orgSlug: 'globex', tenantSlug: 'acme' });
906
+
907
+ // Enrol, for a user who is already signed in.
908
+ if (isWebauthnSupported()) {
909
+ await webauthnRegister(client, 'Alice’s laptop', 'platform');
910
+ }
911
+
912
+ // Passkey as a SECOND factor, continuing a password login.
913
+ const result = await client.login(email, password);
914
+ if (result.status === 'mfa_required' && result.availableMethods.includes('webauthn')) {
915
+ await webauthnLogin(client, result.mfaToken); // client is authenticated after this
916
+ }
917
+
918
+ // Passkey with NO username at all.
919
+ await webauthnDiscoverableLogin(client);
920
+ ```
921
+
922
+ `isWebauthnSupported()` is a query, not a try/catch: hide the button rather than
923
+ offer one that throws. Ceremony failures classify into five outcomes, and
924
+ `already_registered` is the one worth separating — it means the authenticator
925
+ already holds a credential for this account and refused to mint a second, so the
926
+ remedy is a different device rather than another attempt:
927
+
928
+ ```ts
929
+ try {
930
+ await webauthnRegister(client, name, kind);
931
+ } catch (err) {
932
+ const failure = classifyWebauthnError(err); // 'cancelled' | 'already_registered' | …
933
+ showBanner(webauthnErrorMessage(failure));
934
+ }
935
+ ```
936
+
937
+ `cancelled` covers **both** an explicit refusal and a silent timeout. The
938
+ WebAuthn spec deliberately refuses to distinguish them, because telling a website
939
+ which one happened leaks whether an authenticator was present — so the copy for
940
+ it does not accuse anyone of cancelling, and you should not try to recover the
941
+ distinction by timing the call.
942
+
943
+ Passkey autofill (conditional mediation) is a flag, and everything about it
944
+ degrades quietly:
945
+
946
+ ```ts
947
+ if (await isConditionalMediationAvailable()) {
948
+ const abort = new AbortController();
949
+ void webauthnDiscoverableLogin(client, undefined, { conditional: true, signal: abort.signal })
950
+ .catch(() => {/* abandoned, not failed */});
951
+ }
952
+ ```
953
+
954
+ That promise may never settle — the user simply may not pick a passkey — so
955
+ abandon it on navigation and never show an error for a prompt nobody engaged
956
+ with.
957
+
958
+ ### Anywhere else: the JSON bridge
959
+
960
+ Every platform authenticator API speaks the same WebAuthn **JSON form** — Android's
961
+ Credential Manager takes `requestJson` and returns `registrationResponseJson`;
962
+ browsers use `parseCreationOptionsFromJSON()` and `credential.toJSON()`. So the
963
+ SDK hands you the challenge as that JSON and takes the platform's answer back as
964
+ that JSON, from any runtime:
965
+
966
+ ```ts
967
+ import { webauthnRequestJson } from 'axiam-sdk/rest';
968
+
969
+ const { challenge, stateToken } = await client.webauthnDiscoverableStart();
970
+ const requestJson = webauthnRequestJson(challenge); // → give this to the platform
971
+
972
+ // …the platform runs the ceremony and hands back a JSON string…
973
+ await client.webauthnDiscoverableFinish(stateToken, responseJson);
974
+ ```
975
+
976
+ Nothing is destructured on the way through, which matters: the response is the
977
+ input to a signature check over bytes this SDK did not produce, and re-encoding
978
+ base64url "to be safe" is the most common way to break a ceremony that was
979
+ otherwise correct.
980
+
981
+ ### What the SDK does not do, on purpose
982
+
983
+ **It never adjusts an option.** The server generates the challenge and chooses
984
+ `residentKey`, `userVerification`, the attestation conveyance, the exclusion list
985
+ and the timeout; this SDK passes all of it to the authenticator unchanged and
986
+ posts the answer back unchanged. Not because those fields are hard — because they
987
+ are not, and that is the hazard: relaxing `userVerification` to `"preferred"`
988
+ because a CI authenticator kept prompting weakens a ceremony the server believes
989
+ it configured, and the server cannot detect it, since an assertion produced under
990
+ weaker options is a valid assertion.
991
+
992
+ The single exception is the `authenticatorAttachment` hint, and only when you
993
+ pass one. It selects which authenticator the user is prompted for; without it, a
994
+ user reaching for a security key gets asked for Touch ID.
995
+
996
+ **It never emulates an authenticator.** A "credential" held in process memory is
997
+ not a second factor. Where no platform API is reachable, the JSON bridge is the
998
+ answer and it is a complete one.
999
+
1000
+ **There is no user private key anywhere in this API.** The private half never
1001
+ leaves the authenticator — that is the property the whole mechanism rests on.
1002
+
1003
+ ### Two error rows that are not the generic mapping
1004
+
1005
+ - A **`403` on `webauthnRegisterFinish`** is the tenant's attestation policy
1006
+ refusing *this authenticator* — an AAGUID that is not allow-listed, a missing
1007
+ FIDO certification, a revoked status — not a permission problem with the user.
1008
+ The server's message is surfaced verbatim, because it is the only way the person
1009
+ holding the key learns that a different one would work.
1010
+ - A **`503` on `webauthnRegisterStart`** means the attestation policy requires
1011
+ attestation and the FIDO metadata service has no usable snapshot. It is a server
1012
+ configuration state, not a transient failure, and it is deliberately **not**
1013
+ retried: retrying changes nothing and delays a message an operator needs.
1014
+
1015
+ ## Account lifecycle and MFA enrolment (CONTRACT.md §25)
1016
+
1017
+ §1 locks the *middle* of an account's life — `login`, `verifyMfa`, `refresh`,
1018
+ `logout` all assume an account that already exists, is verified, and already has
1019
+ its second factor. These nine operations are how it gets there.
1020
+
1021
+ ```ts
1022
+ // Voluntary TOTP enrolment, by a signed-in user. Two calls, deliberately: the
1023
+ // human step in the middle is not something a helper can wait for, and one that
1024
+ // returned after mfaEnroll would report MFA as enabled when it is not.
1025
+ const enrolment = await client.mfaEnroll();
1026
+ renderQr(enrolment.totpUri.expose());
1027
+ await client.mfaConfirm(codeTypedByUser); // → true once the factor is live
1028
+ ```
1029
+
1030
+ `secretBase32` and `totpUri` are both `Sensitive`, and the URI is the one that
1031
+ matters: it *is* `otpauth://…?secret=…`, so it contains the secret it sits next
1032
+ to. Wrapping only the secret would have wrapped nothing — the URI is the field
1033
+ that actually reaches a log, because it is the field you hand to a QR renderer.
1034
+
1035
+ ### `login()` has a third outcome
1036
+
1037
+ **This is a breaking change** (contract 1.28). The server has always been able to
1038
+ answer `POST /api/v1/auth/login` with `403 mfa_setup_required` and a setup token,
1039
+ meaning "this tenant requires MFA, this account has none, here is how to finish".
1040
+ It used to reach you as an `AuthzError` — which told you that you lacked
1041
+ permission to log in, when what the server said was recoverable and came with the
1042
+ means to recover.
1043
+
1044
+ ```ts
1045
+ switch (result.status) {
1046
+ case 'authenticated':
1047
+ break;
1048
+ case 'mfa_required':
1049
+ await client.verifyMfa(result.mfaToken, code);
1050
+ break;
1051
+ case 'mfa_setup_required': { // ← new
1052
+ const enrolment = await client.mfaSetupEnroll(result.setupToken);
1053
+ renderQr(enrolment.totpUri.expose());
1054
+ await client.mfaSetupConfirm(result.setupToken, codeTypedByUser);
1055
+ break; // this completes the login
1056
+ }
1057
+ }
1058
+ ```
1059
+
1060
+ If you match `LoginResult` exhaustively, this is the edit you need. A genuine
1061
+ authorization refusal is still an `AuthzError`: the SDK matches on the body's own
1062
+ discriminant, not on the `403` alone.
1063
+
1064
+ ### Email verification and password reset
1065
+
1066
+ ```ts
1067
+ await client.verifyEmail(tokenFromLink, tenantId);
1068
+ await client.resendVerification(email, tenantId); // anonymous caller
1069
+ await client.resendOwnVerification(); // signed-in caller
1070
+
1071
+ await client.requestPasswordReset({ email });
1072
+ ```
1073
+
1074
+ **There are two resends, and picking the wrong one is silent.** Use the second
1075
+ whenever you have a session.
1076
+
1077
+ `resendVerification` takes an address from an *unauthenticated* caller, so it
1078
+ resolves whatever happens — unknown address, already verified, over the daily
1079
+ limit. That constancy is the point: anything else is an oracle for which
1080
+ addresses have accounts.
1081
+
1082
+ `resendOwnVerification` is for a caller signed in to the account it is asking
1083
+ about. It takes **no address at all** (the server reads it off your own record,
1084
+ and a parameter would let a session mail an arbitrary one) and it says what
1085
+ happened:
1086
+
1087
+ ```ts
1088
+ try {
1089
+ await client.resendOwnVerification(); // minted and enqueued
1090
+ } catch (e) {
1091
+ if (e instanceof ConflictError) { /* already verified, or not eligible */ }
1092
+ else if (e instanceof NetworkError) { /* 429 — daily limit */ }
1093
+ else throw e;
1094
+ }
1095
+ ```
1096
+
1097
+ A profile page that called the *first* one reports success while doing nothing,
1098
+ which is the bug this pair exists to separate. This SDK does not fall back from
1099
+ the second to the first on either failure — that would turn both back into a
1100
+ resolved promise with an extra round-trip. And resolving means *enqueued*:
1101
+ delivery is asynchronous and can still fail at the provider.
1102
+
1103
+ ### Organization-level principals (§5.2)
1104
+
1105
+ An authenticated `LoginResult` also says whether the account is an
1106
+ **organization-level** principal — one whose record lives in its organization's
1107
+ reserved tenant, so its global grants apply in every tenant of that organization:
1108
+
1109
+ ```ts
1110
+ if (result.status === 'authenticated' && result.user.organizationLevel) {
1111
+ // Acts on any tenant of its organization by sending a different
1112
+ // `X-Tenant-ID` on the next request. No re-login: it already is a
1113
+ // principal of every tenant there.
1114
+ }
1115
+ ```
1116
+
1117
+ Check it *before* offering a tenant switch. An ordinary tenant principal is a
1118
+ principal of exactly one tenant, and changing the header for one of those
1119
+ produces a `403` — so a UI that offers the switch to everyone has turned a
1120
+ distinction the server made into a failure the user discovers. `false` against a
1121
+ server older than contract 1.31, which is the safe reading of absent.
1122
+
1123
+ `requestPasswordReset` resolves **whether or not the address exists**, and this
1124
+ SDK exposes no way to tell the difference. That is not an omission to improve on:
1125
+ any signal distinguishing them — including one inferred from timing — turns the
1126
+ endpoint into the account enumeration oracle its uniform response exists to
1127
+ prevent.
1128
+
1129
+ Setting the new password takes one extra call on any tenant that might have
1130
+ OPAQUE enabled (§23), because the client has to build a registration record and
1131
+ cannot know the parameters before it has a token to ask with:
1132
+
1133
+ ```ts
1134
+ const context = await client.passwordResetContext(token);
1135
+ await client.confirmPasswordReset({
1136
+ token,
1137
+ newPassword,
1138
+ tenantId,
1139
+ ...(context.opaque ? { opaque: await client.opaqueEnrollment(newPassword) } : {}),
1140
+ });
1141
+ ```
1142
+
1143
+ The context discloses no identity — an unauthenticated endpoint that confirmed
1144
+ which account a token belongs to would be an oracle worth not having — and a
1145
+ `404` covers unknown, expired and already-consumed without distinguishing them.
1146
+
1147
+ ## Device authorization grant (`axiam-sdk/node`, CONTRACT.md §14)
1148
+
1149
+ RFC 8628 — signing in a device that cannot show a browser: a TV, a CLI, a headless
1150
+ commissioning tool.
1151
+
1152
+ ```ts
1153
+ const tokens = await oidc.deviceLogin({
1154
+ onUserCode: (auth) => {
1155
+ // Called BEFORE the first poll. Display it however the device can —
1156
+ // screen, QR code, e-ink panel. The SDK never prints it for you.
1157
+ console.log(`visit ${auth.verificationUri} and enter ${auth.userCode}`);
1158
+ },
1159
+ });
1160
+ ```
1161
+
1162
+ `deviceAuthorize` and `devicePoll` are also public, for an application driving its own
1163
+ loop. The polling rules are where implementations go wrong, so they are worth stating:
1164
+
1165
+ - **`slow_down` raises the interval permanently.** An SDK that backs off for one round and
1166
+ returns to the original interval will be told to slow down again, forever.
1167
+ - **`access_denied` and `expired_token` stay distinct.** A human said no, versus nobody
1168
+ answered — the only information the device can act on.
1169
+ - **Polling stops at `expires_in`**, even if the server has not yet said `expired_token`.
1170
+ - **A `5xx` mid-poll is not terminal.** A server restart must not lose a grant the user has
1171
+ already approved.
1172
+
1173
+ `deviceCode` is `Sensitive`; `userCode` deliberately is not — it exists to be read aloud,
1174
+ and wrapping it would defeat the one thing it is for.
1175
+
1176
+ Per §14.3 rule 4, `deviceLogin` **returns** the token set rather than adopting it. See
1177
+ [`examples/device-login.ts`](examples/device-login.ts).
1178
+
1179
+ ## Token exchange (`axiam-sdk/node`, CONTRACT.md §15)
1180
+
1181
+ RFC 8693 — a service holding a user's token exchanging it for a *narrower* one before
1182
+ calling the next service.
1183
+
1184
+ ```ts
1185
+ const exchanged = await oidc.tokenExchange({
1186
+ subjectToken: new Sensitive(userToken),
1187
+ subjectTokenType: ACCESS_TOKEN_TYPE, // required (§15.1), no default
1188
+ scopes: ['orders:read'],
1189
+ audience: 'orders-service',
1190
+ });
1191
+ ```
1192
+
1193
+ Most of what this method does is refuse to be helpful, and each refusal is deliberate:
1194
+
1195
+ - **No default `actorToken`.** Omitting it asks for *impersonation*; the SDK will not
1196
+ quietly substitute the client's own session token and turn that into a delegation.
1197
+ - **No auto-narrowing after `invalid_scope`.** The server refuses rather than silently
1198
+ narrowing precisely so the caller finds out here.
1199
+ - **No refresh token, ever** — `ExchangedToken` has no such field, so there is nothing to
1200
+ synthesise. Re-run the exchange.
1201
+ - **No adoption.** The issued token is handed onward in one call; adopting it would
1202
+ silently re-privilege every later call this client makes. A MUST NOT, where
1203
+ `loginClientCredentials` adoption is a MAY.
1204
+
1205
+ See [`examples/token-exchange.ts`](examples/token-exchange.ts).
1206
+
1207
+ ### External-IdP subject tokens (CONTRACT.md §15.7)
1208
+
1209
+ The same method exchanges a token minted by a **trusted external IdP** — a partner's
1210
+ Entra, Okta or Keycloak — for an AXIAM token scoped to what the resolved AXIAM user may
1211
+ actually do. There is no separate operation:
1212
+
1213
+ ```ts
1214
+ const exchanged = await oidc.tokenExchange({
1215
+ subjectToken: new Sensitive(partnerToken),
1216
+ subjectTokenType: JWT_TOKEN_TYPE, // named, never guessed
1217
+ scopes: ['read:orders'],
1218
+ audience: 'https://orders.internal',
1219
+ });
1220
+ ```
1221
+
1222
+ - **`subjectTokenType` is yours to state, and is required** (§15.1). The SDK never decodes
1223
+ the subject token to pick it, and never overrides what you named. There is no default —
1224
+ omitting it does not compile, because a default would be the SDK choosing for you.
1225
+ - **No actor token.** Delegation across a trust boundary is unsupported in v1; sending one
1226
+ is `invalid_request`, which the SDK will not work around by dropping it and re-sending.
1227
+ - **One refusal is distinguishable.** `invalid_grant` whose description is `the subject
1228
+ token's issuer is not configured for token exchange` means *fix the AXIAM trust
1229
+ configuration*. Every other `invalid_grant` means *fix your token*, and is deliberately
1230
+ generic.
1231
+ - **Forward the result as-is.** It carries an `ext_exchange` claim naming the partner
1232
+ issuer; never strip it, and never read it as an authorization input. It also cannot be
1233
+ exchanged again — exchanges do not compose.
1234
+
1235
+ See [`examples/external-token-exchange.ts`](examples/external-token-exchange.ts) and the
1236
+ operator guide, `docs/api/federated-token-exchange.md`.
1237
+
1238
+ ## Pushed authorization requests (`axiam-sdk/node`, CONTRACT.md §26)
1239
+
1240
+ PAR (RFC 9126) moves the authorization request off the browser. Instead of
1241
+ putting `scope`, `redirect_uri`, `state` and the PKCE challenge into a URL the
1242
+ user agent carries, the client POSTs them straight to AXIAM over an
1243
+ authenticated back channel and puts an opaque `request_uri` in the redirect.
1244
+ What travels through the browser is then a random string that cannot be edited
1245
+ into meaning something else.
1246
+
1247
+ Required for a FAPI 2.0 client: `profile: "fapi2"` refuses a registration that
1248
+ does not set `require_par`, so such a client cannot authorize any other way.
1249
+
1250
+ ```ts
1251
+ const configuration = await oidc.oidcDiscover();
1252
+ const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });
1253
+
1254
+ const pushed = await oidc.oidcPar({ request, redirectUri, scope: 'openid profile', configuration });
1255
+
1256
+ redirect(pushed.authorizationUrl);
1257
+ // …on the callback, unchanged by PAR:
1258
+ const tokens = await oidc.oidcExchange({
1259
+ code, redirectUri, nonce: pushed.nonce, codeVerifier: pushed.codeVerifier,
1260
+ });
1261
+ ```
1262
+
1263
+ `oidcBegin` still does the computing — there is no second generator for `state`,
1264
+ `nonce` and PKCE — and `pushed.codeVerifier` is the one it produced, so there is
1265
+ exactly one value to keep.
1266
+
1267
+ Three things about this that are easy to get wrong:
1268
+
1269
+ 1. **The endpoint answers `201`, not `200`.** RFC 9126 §2.2 specifies Created,
1270
+ and a success predicate written `status === 200` treats every successful push
1271
+ as a failure.
1272
+ 2. **The authorization URL carries exactly `client_id` and `request_uri`.** The
1273
+ server *refuses* a request that mixes a `request_uri` with inline
1274
+ authorization parameters rather than merging them, and re-adding them "for
1275
+ compatibility" restores the parameter-confusion attack the refusal prevents:
1276
+ an attacker supplies the inline value they want and lets the pushed copy
1277
+ satisfy whichever check reads the other one.
1278
+ 3. **`request_uri` is single-use and short-lived.** There is nothing to retry
1279
+ with it — the safe recovery is a fresh push, which costs one round trip and
1280
+ cannot double-consume anything. `oidcPar` is correspondingly never retried on
1281
+ a `5xx` or a transport failure: it is a POST that creates server state.
1282
+
1283
+ `invalid_client` on a push has three usual causes: a wrong secret, a secret sent
1284
+ by a client registered for `tls_client_auth` / `private_key_jwt` /
1285
+ `self_signed_tls_client_auth` (which is refused, not ignored), or a client
1286
+ certificate the transport did not present.
1287
+
1288
+ ## Logout — RP-initiated and back-channel (`axiam-sdk/node`, CONTRACT.md §12.7)
1289
+
1290
+ `logoutUrl` builds the redirect; `verifyLogoutToken` validates a token the OP **pushed** to
1291
+ your back-channel endpoint.
1292
+
1293
+ ```ts
1294
+ const url = await oidc.logoutUrl({ idToken });
1295
+
1296
+ // …and at your registered backchannel_logout_uri:
1297
+ const verified = await oidc.verifyLogoutToken(logoutToken);
1298
+ if (verified.sid) {
1299
+ endSession(verified.sid); // that session ONLY
1300
+ }
1301
+ ```
1302
+
1303
+ The verifier is where the security weight sits — the input arrives unsolicited and
1304
+ instructs you to terminate a session. It checks the signature (same JWKS path, same
1305
+ `kid`-required discipline as §12.4), `iss`, `aud`, that `events` carries the
1306
+ back-channel-logout key (**the only thing separating a logout token from an ID token**),
1307
+ that `nonce` is *absent* (its presence is how an ID token gets replayed as one), that
1308
+ something is named, and freshness.
1309
+
1310
+ It returns `sid`/`sub`/`jti` rather than a bare boolean: you have to know *which* session to
1311
+ end. **Dedup on `jti` yourself** — delivery is at-least-once, so a valid token legitimately
1312
+ arrives twice; the SDK has no durable store and an in-memory guard would silently drop a
1313
+ real second logout after a restart.
1314
+
1315
+ See [`examples/logout.ts`](examples/logout.ts).
1316
+
1317
+ ## UMA 2.0 — Protection API and ticket grant (CONTRACT.md §20)
1318
+
1319
+ The resource-server side of User-Managed Access: register what you guard, ask the
1320
+ authorization server what a caller would need, and redeem the resulting ticket.
1321
+
1322
+ The two runnable halves are [`examples/uma-resource-server.ts`](examples/uma-resource-server.ts)
1323
+ and [`examples/uma-client.ts`](examples/uma-client.ts) — run the first, then the second
1324
+ against it.
1325
+
1326
+ ### Making a denial actionable (`axiam-sdk/middleware`)
1327
+
1328
+ ```ts
1329
+ import { requireAccess, type UmaChallenger } from 'axiam-sdk/middleware';
1330
+
1331
+ const challenger: UmaChallenger = {
1332
+ realm: 'invoices',
1333
+ asUri: (await oidc.oidcDiscover()).issuer,
1334
+ pat, // a client-credentials token carrying `uma_protection` (§20.2 rule 1)
1335
+ mint: (token, permissions) => oidc.umaRequestTicket(token, [...permissions]),
1336
+ };
1337
+
1338
+ app.get(
1339
+ '/invoices/:id',
1340
+ requireAccess(session, 'invoices:read', fromParam('id'), { umaChallenge: challenger }),
1341
+ handler,
1342
+ );
1343
+ ```
1344
+
1345
+ Without `umaChallenge` this is an ordinary §11 guard and a denial is a bare 403. With it, the
1346
+ guard mints a permission ticket for the action it just refused and returns
1347
+ `WWW-Authenticate: UMA realm=…, as_uri=…, ticket=…` alongside the 403 — so a UMA-aware client
1348
+ knows where to obtain authority instead of only being told no. The body is unchanged, so a
1349
+ client that does not speak UMA sees exactly the 403 it saw before. Both `requireAccess`
1350
+ (Express) and `requireAccessHook` (Fastify) take the option.
1351
+
1352
+ **It is opt-in, and that is a design decision rather than an oversight.** Emitting a
1353
+ challenge means *minting a credential*: a wire call to the Protection API and a live ticket,
1354
+ produced on a path the caller did not explicitly request. A guard that did that on every
1355
+ denial by default would turn each unauthorized request into a Protection API call — a
1356
+ denial-of-service amplifier pointed at your own authorization server.
1357
+
1358
+ **Failure is not escalation.** If minting fails — expired PAT, Protection API down, a scope
1359
+ the resource never declared — the denial still surfaces as a plain 403 with no challenge. A
1360
+ caller who was going to be refused is refused either way; letting an outage turn a deny into
1361
+ a 500 would give it a second consequence, and letting it turn into an allow would be a
1362
+ security bug.
1363
+
1364
+ ### Consuming the challenge (`axiam-sdk/node`)
1365
+
1366
+ ```ts
1367
+ import { umaParseChallenge } from 'axiam-sdk/node';
1368
+
1369
+ const challenge = umaParseChallenge(response.headers.get('www-authenticate') ?? '');
1370
+ if (challenge?.ticket) {
1371
+ // Deciding whether to trust challenge.asUri is YOUR call — parsing performed no
1372
+ // exchange, deliberately (§20.3): that host was chosen by the server you just
1373
+ // failed against.
1374
+ const rpt = await oidc.umaExchangeTicket({ ticket: challenge.ticket, claimToken: userToken });
1375
+ }
1376
+ ```
1377
+
1378
+ The rest of the surface — `umaRegisterResource`, the other four `rreg` operations,
1379
+ `umaRequestTicket`, `umaExchangeTicket` — plus the rules they enforce (a ticket is never
1380
+ retried, the RPT is never adopted, an update replaces the scope list rather than merging it)
1381
+ is documented on the generated API docs for `axiam-sdk/node`.
1382
+
1383
+ ## Webhook signature verification (`axiam-sdk/node`, CONTRACT.md §13)
1384
+
1385
+ AXIAM signs every webhook delivery with a Stripe-style signed timestamp:
1386
+
1387
+ ```
1388
+ X-Axiam-Signature: t=<unix_seconds>,v1=<hex_lowercase_hmac>
1389
+ ```
1390
+
1391
+ where `v1 = HMAC-SHA256(secret_utf8_bytes, "<timestamp>.<raw_body>")`. `verifyWebhook`
1392
+ recomputes and checks that signature — in constant time, with a two-sided freshness window —
1393
+ so integrators never hand-roll (or skip) the comparison.
1394
+
1395
+ ```typescript
1396
+ import { verifyWebhook, WebhookVerifyError, Sensitive } from 'axiam-sdk/node';
1397
+
1398
+ const secret = new Sensitive(process.env.AXIAM_WEBHOOK_SECRET!);
1399
+
1400
+ try {
1401
+ const { event, id } = verifyWebhook(secret, req.header('X-Axiam-Signature')!, req.rawBody);
1402
+ // `event`/`id` come from the verified body's own `event`/`id` fields; `X-Axiam-Delivery`
1403
+ // is the at-least-once dedup key — keep a short-lived seen-set, since a retry replays a
1404
+ // validly-signed request inside the freshness window.
1405
+ console.log('verified webhook:', event, id);
1406
+ } catch (err) {
1407
+ if (err instanceof WebhookVerifyError) {
1408
+ res.status(400).end(); // err.reason is a stable code; err.message never
1409
+ // contains the secret or the expected signature
1410
+ }
1411
+ }
1412
+ ```
1413
+
1414
+ **The raw body is load-bearing.** `verifyWebhook` MUST receive the *exact* bytes AXIAM sent —
1415
+ `Buffer`, `Uint8Array`, or the identical raw string — never a `JSON.stringify` of the parsed
1416
+ body. Re-serializing changes key order/whitespace and silently breaks the MAC; this is the
1417
+ single most common integration mistake. Most JSON body-parsing middleware discards the raw
1418
+ bytes by default, so capture them explicitly on the webhook route. With Express,
1419
+ `express.json()` alone does **not** keep them — use its `verify` callback, or mount
1420
+ `express.raw({ type: 'application/json' })` on that one route instead:
1421
+
1422
+ ```typescript
1423
+ import express from 'express';
1424
+
1425
+ app.post(
1426
+ '/webhooks/axiam',
1427
+ express.json({
1428
+ verify: (req, _res, buf) => {
1429
+ (req as express.Request & { rawBody: Buffer }).rawBody = buf;
1430
+ },
1431
+ }),
1432
+ (req, res) => {
1433
+ const { rawBody } = req as express.Request & { rawBody: Buffer };
1434
+ const event = verifyWebhook(secret, req.header('X-Axiam-Signature')!, rawBody);
1435
+ // ...
1436
+ },
1437
+ );
1438
+ ```
1439
+
1440
+ The freshness window defaults to 300 s and is two-sided — a future-dated `t=` is rejected just
1441
+ like a stale one — and accepts a `tolerance` override plus a `now` injection seam for tests. A
1442
+ failure always raises the typed `WebhookVerifyError` (never a generic exception whose message
1443
+ could leak the expected signature).
1444
+
1445
+ ## Client quality-of-life (CONTRACT.md §16–§19)
1446
+
1447
+ ### Retry policy (§16)
1448
+
1449
+ Read-only authorization checks — `checkAccess`, `can`, `batchCheck` — retry transient
1450
+ failures under the contract's normative table: **3 attempts** (1 initial + 2 retries),
1451
+ 200 ms base, 5 s cap, **full jitter** (uniform over `[0, backoff]`), and `Retry-After`
1452
+ honored as a **floor**.
1453
+
1454
+ > **This changed in D5.** The previous policy used a 1000 ms base, an 8 s cap, partial
1455
+ > jitter, and let `Retry-After` *replace* the backoff — so a `Retry-After: 0` retried
1456
+ > immediately. Worse, `withRetry` was exported and unit-tested but **never called by
1457
+ > `checkAccess`**, so this SDK performed no read-only retries at all. Both are fixed, and
1458
+ > the conformance tests now assert through the public API rather than against the helper.
1459
+
1460
+ Only failures that could plausibly succeed on a second attempt are retried — transport
1461
+ errors, `408`, `429`, `5xx`. A `401` or `403` is an answer, not a transport failure, and is
1462
+ surfaced after exactly one attempt. Nothing that changes server state is ever retried.
1463
+
1464
+ ```ts
1465
+ // Turn it off if you own your own retry layer — you know your deadline, this SDK doesn't.
1466
+ const client = new AxiamClient({ baseUrl, tenantSlug: 'acme', retryEnabled: false });
1467
+ ```
1468
+
1469
+ There is deliberately no knob for the attempt cap, base delay or delay cap: §16.1 forbids
1470
+ raising them, and eleven SDKs agreeing on one table is the point.
1471
+
1472
+ ### Deterministic shutdown (§18)
1473
+
1474
+ `client.close()` releases the client's local resources. It is idempotent, and any call
1475
+ afterwards rejects with a `NetworkError` naming the cause rather than silently reconnecting.
1476
+
1477
+ **`close()` does not log out.** It never reaches the network. The server-side session
1478
+ deliberately outlives the client object — that is what lets a process restart and resume —
1479
+ so a `close()` that logged out would silently end every user's session on each deploy. Call
1480
+ `logout()` first if ending the session is what you want.
1481
+
1482
+ ### Telemetry hooks (§19)
1483
+
1484
+ Wire metrics without this package depending on any metrics library:
1485
+
1486
+ ```ts
1487
+ const client = new AxiamClient({
1488
+ baseUrl,
1489
+ tenantSlug: 'acme',
1490
+ telemetryHook: (event) => {
1491
+ if (event.type === 'requestEnd') {
1492
+ histogram.record(event.durationMs, { op: event.operation, outcome: event.outcome });
1493
+ } else if (event.type === 'retry') {
1494
+ counter.add(1, { op: event.operation, attempt: event.attempt });
1495
+ }
1496
+ },
1497
+ });
1498
+ ```
1499
+
1500
+ - **A hook that throws cannot fail the operation that fired it.** Telemetry is not permitted
1501
+ to fail an authorization check.
1502
+ - **No event payload can carry a token.** `TelemetryEvent` is a closed union with a fixed
1503
+ field set — this surface exists to be shipped to a metrics backend.
1504
+ - **Path templates, not URLs**, so a metric label cannot become a cardinality bomb.
1505
+
1506
+ One `requestStart`/`requestEnd` pair is emitted **per attempt**, so you can count real wire
1507
+ calls. See [`examples/telemetry-hook.ts`](examples/telemetry-hook.ts), including the
1508
+ OpenTelemetry mapping.
1509
+
1510
+ ### Decision memo (§17) — opt-in, off by default
1511
+
1512
+ An optional TTL-bounded cache for `checkAccess` results. **Disabled by default**, because
1513
+ §11.2 rule 6's ban on caching authorization decisions is still the default behaviour.
1514
+
1515
+ ```ts
1516
+ const client = new AxiamClient({
1517
+ baseUrl,
1518
+ tenantSlug: 'acme',
1519
+ decisionMemoTtlMs: 5000, // 0 = off, which is the default
1520
+ });
1521
+ ```
1522
+
1523
+ **What you are accepting.** The staleness bound is the TTL, in *both* directions: a grant
1524
+ revoked on the server can still read as allowed for up to the TTL, and a grant just added
1525
+ can still read as denied for up to the TTL.
1526
+
1527
+ > **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role and
1528
+ > immediately re-checks is the case that breaks, and it breaks silently. If that is your
1529
+ > workload, leave this off.
1530
+
1531
+ The TTL is clamped to 5000 ms rather than rejected. Allows and denies are memoized
1532
+ identically — asymmetric caching would leak which outcome occurred through latency.
1533
+ Failures are never memoized: caching a transport error as a deny would turn a blip into a
1534
+ TTL-long outage. The memo is cleared on `login`, `verifyMfa`, `refresh` and `logout`, since
1535
+ entries are keyed by subject rather than by session.
1536
+
1537
+ ## Management API (CONTRACT.md §27)
1538
+
1539
+ Everything above assumes a populated tenant. `login` signs a user in,
1540
+ `checkAccess` asks about a resource, `verifyWebhook` checks a delivery signature — and
1541
+ none of them can create the user, declare the resource or register the webhook. The
1542
+ management surface is the part that can: **146 operations across 24 namespaces**,
1543
+ generated from `management-registry.json`, which is the whole server API minus what other
1544
+ contract sections own and minus organization creation and deletion (§27.0 keeps those out
1545
+ of reach of a client library on purpose).
1546
+
1547
+ ```ts
1548
+ const page = await client.users.list({ limit: 50 });
1549
+ const every = await client.users.listAll({ limit: 200 });
1550
+ const found = await client.users.list({ limit: 50, search: 'ada' });
1551
+ const role = await client.roles.get(roleId);
1552
+ await client.roles.assignToUser(roleId, { user_id: userId });
1553
+ ```
1554
+
1555
+ Operations hang off **namespace handles** rather than the client. Twenty namespaces have a
1556
+ `list` and fourteen a `get`, so flattening them would need a disambiguating prefix invented
1557
+ once per operation — and would bury the eight §1 methods most callers want under five times
1558
+ as many they do not. Acquiring a handle performs no I/O. `client.management.users` is the
1559
+ same handle as `client.users`, for call sites that read better with the namespace spelled
1560
+ out.
1561
+
1562
+ Every management call goes through the session's existing axios instance, so it inherits
1563
+ CSRF forwarding (§3), the cookie jar (§4), the `X-Tenant-ID` header (§5), the TLS policy
1564
+ (§6), the reactive single-flight refresh the response interceptor already performs (§9),
1565
+ the retry policy (§16) and telemetry (§19). None of it is reimplemented, and none of it can
1566
+ be forgotten per-operation.
1567
+
1568
+ **Field names are the server's, verbatim** — `resource_type`, `is_global`, `user_id`. A
1569
+ management surface is read alongside the API docs, and a casing translation layer over 136
1570
+ generated types is both a lot of code and a class of bug; what you read in `openapi.json`
1571
+ is what you write here. The hand-curated §1 types (`AccessCheck`) keep their camelCase.
1572
+
1573
+ **`search` is on the page request, and the server does the filtering.** All twenty
1574
+ paginated operations take it:
1575
+
1576
+ ```ts
1577
+ const page = await client.users.list({ limit: 50, search: 'ada' });
1578
+ const all = await client.users.listAll({ limit: 200, search: 'ada' });
1579
+ ```
1580
+
1581
+ It is matched case-insensitively against the identifying fields of whatever is being
1582
+ listed — a name or username, plus the record id, so a UUID out of a log line pastes in
1583
+ as-is. Three consequences worth knowing:
1584
+
1585
+ - **`total` counts matches, not rows**, because the filter is applied before
1586
+ `offset`/`limit`. That is what lets a pager built on it show a page count belonging to
1587
+ the result set it is paging. Filtering a page in JS after the fetch gives you neither.
1588
+ - **`listAll` carries the term across the whole walk**, so it returns the matches and not
1589
+ the matches followed by the unfiltered tail.
1590
+ - **A blank term is no term.** `search: ''` and `search: ' '` send no `search` parameter
1591
+ at all, so a box that fires on every keystroke does not ask a different question once it
1592
+ has been cleared. The server also caps the term's length; this SDK does not copy that
1593
+ cap, because a client-side truncation the server would not have made is a silently
1594
+ different query.
1595
+
1596
+ **Three model fields arrived with contract 1.31 (§27.11).** `Tenant.kind` says whether a
1597
+ tenant is ordinary or its organization's own scope, and is absent on a row written before
1598
+ that scope existed. `MtlsTrustAnchorResponse.trusted_anchors` is absent when nothing was
1599
+ reloaded — which is *not* zero: "the listener trusts no CAs" and "there was no listener to
1600
+ ask" are different states, and only one is a problem. `Certificate.bound_service_account_id`
1601
+ is resolved by `certificates.list()` and absent from `get`; the SDK does not issue a second
1602
+ request to fill it in.
1603
+
1604
+ **Generated enums are open.** Each is a literal union with a trailing `(string & {})` arm,
1605
+ so a value this SDK's copy of the spec does not list reaches you as itself rather than
1606
+ being asserted out of existence. The named arms still autocomplete and still narrow; what
1607
+ the extra arm removes is the illusion that an exhaustive `switch` over them is exhaustive.
1608
+
1609
+ ### Five things that bite
1610
+
1611
+ **Reads retry; writes never do.** Not even the idempotent-looking ones.
1612
+ `certificates.generate()` twice mints two certificates; `serviceAccounts.rotateSecret()`
1613
+ twice invalidates the secret the first call returned and you already stored.
1614
+
1615
+ **Seventeen `PUT`s patch, four replace.** A sparse update sends only the fields you set — an
1616
+ unset field is *absent* from the wire body, not `null`, so it is left unchanged. But
1617
+ `settings.setOrg()`, `emailConfig.setOrg()`, `webauthnPolicy.set()` and
1618
+ `caCertificates.setMtlsTrustAnchor()` **replace**: what you omit is not preserved. Their
1619
+ request types have required fields, so a half-filled one does not typecheck — which is the
1620
+ point, since sending a subset of `SetOrgSettings` resets the other eighteen.
1621
+
1622
+ **Seven calls return a secret exactly once.** Creating a service account or an OAuth2
1623
+ client, minting a SCIM token, generating a certificate, a CA, a signing CA or a PGP key.
1624
+ The field is `Sensitive<string>`: `JSON.stringify` gives `"[SENSITIVE]"`, `.expose()` gives
1625
+ the value. No later `get` returns it again, and the `get` projection has no field where it
1626
+ was — so nothing tells you it is missing.
1627
+
1628
+ **404 means "absent, or not yours."** The server answers 404 for a resource in another
1629
+ tenant deliberately: a distinguishable "exists but not yours" lets a caller enumerate
1630
+ another tenant's ids.
1631
+
1632
+ ```ts
1633
+ try {
1634
+ await client.users.get(id);
1635
+ } catch (e) {
1636
+ if (e instanceof NotFoundError) { /* absent, or another tenant's */ }
1637
+ else if (e instanceof ConflictError) { /* 409 — the name is taken */ }
1638
+ else if (e instanceof ValidationError) { for (const f of e.fields) { /* 400, per field */ } }
1639
+ }
1640
+ ```
1641
+
1642
+ All three are real subclasses of the §2 types — `NotFoundError` and `ConflictError` extend
1643
+ `AuthzError`, `ValidationError` extends `NetworkError` — so `e instanceof AuthzError`
1644
+ written before §27 still catches the first two.
1645
+
1646
+ **`orgId` and `tenantId` default from the client**, and are overridable per handle with
1647
+ `.inOrg(id)` / `.forTenant(id)`. A client built with a *slug* fails locally, with no
1648
+ request, on any route that needs the UUID — the SDK will not resolve a slug behind your
1649
+ back.
1650
+
1651
+ ### Declarative manifests (§27.6, §27.7)
1652
+
1653
+ Calling 146 operations one at a time is rarely what an application wants. What it does at
1654
+ start-up, in a migration, or in a test fixture is assert a shape:
1655
+
1656
+ ```ts
1657
+ import { defineManifest, Sensitive } from 'axiam-sdk/rest';
1658
+
1659
+ export const desired = defineManifest({
1660
+ resources: [
1661
+ { key: 'docs', name: 'documents', resourceType: 'collection',
1662
+ scopes: [{ key: 'draft', name: 'draft', description: 'Unpublished' }] },
1663
+ ],
1664
+ permissions: [{ key: 'read', action: 'document:read', description: 'Read a document' }],
1665
+ roles: [{ key: 'editor', name: 'Editor', description: 'Edits documents',
1666
+ grants: [{ permission: 'read', scopes: ['draft'] }] }],
1667
+ groups: [{ key: 'staff', name: 'Staff', description: 'The team', roles: ['editor'] }],
1668
+ users: [{ key: 'alice', username: 'alice', email: 'alice@example.com',
1669
+ initialPassword: new Sensitive(pw), groups: ['staff'] }],
1670
+ });
1671
+
1672
+ const plan = await client.manifest.plan(desired); // reads only — no writes
1673
+ const report = await client.manifest.apply(desired);
1674
+ ```
1675
+
1676
+ `defineManifest` keeps the literal key types *and* validates immediately — a dangling
1677
+ cross-reference throws where the manifest is written, which for a config module is import
1678
+ time, rather than on the first `plan` against production.
1679
+
1680
+ `plan()` issues `GET`s and nothing else. It matches each spec by its natural key — a user's
1681
+ `username`, a role's `name`, a scope's `name` within its resource — and returns the ordered
1682
+ actions that would reconcile the tenant.
1683
+
1684
+ - **Nothing is ever deleted.** A manifest is usually a *subset* of a tenant's truth, and a
1685
+ prune would turn "make sure these three roles exist" into "delete the other forty". There
1686
+ is no prune option, deliberately.
1687
+ - **A field the manifest does not state is never a difference**, so `apply` is safe against
1688
+ a tenant that also holds hand-made state.
1689
+ - **Applying twice converges**: the second plan is all `no-change`. That is what makes
1690
+ re-running after a failure safe.
1691
+ - **There is no transaction** across 146 independent HTTP endpoints, and `ApplyReport` does
1692
+ not pretend there is. If step 12 of 30 fails, steps 1–11 have happened; the report says
1693
+ which, execution stops rather than continuing blindly, and there is no `rollback` —
1694
+ because this SDK could not honour one.
1695
+
1696
+ Codebases that already declare their domain with classes get decorators instead:
1697
+
1698
+ ```ts
1699
+ @AxiamResource({ key: 'docs', name: 'documents', resourceType: 'collection' })
1700
+ @AxiamScope({ key: 'draft', name: 'draft', description: 'Unpublished' })
1701
+ class Documents {}
1702
+
1703
+ @AxiamRole({ key: 'editor', name: 'Editor', description: 'Edits documents' })
1704
+ @AxiamGrant({ permission: 'read', scopes: ['draft'] })
1705
+ class Editor {}
1706
+
1707
+ const shape = collectManifest(Documents, ReadDocument, Editor);
1708
+ ```
1709
+
1710
+ TypeScript has two decorator dialects and this SDK's own `tsconfig.json` deliberately
1711
+ enables neither — so these are dual-protocol plain functions that work under both, and
1712
+ under neither: `AxiamResource(spec)(Documents)` is exactly what the `@` syntax desugars to.
1713
+
1714
+ ### Examples
1715
+
1716
+ - [`examples/management-basics.ts`](examples/management-basics.ts) — the imperative surface
1717
+ and the rules above, one at a time.
1718
+ - [`examples/management-manifest.ts`](examples/management-manifest.ts) — both declarative
1719
+ forms end to end.
1720
+ - [`examples/device-mtls-provisioning.ts`](examples/device-mtls-provisioning.ts) —
1721
+ provisioning an IoT device and its mTLS identity: anchor the CA, create the service
1722
+ account, generate the certificate, bind it, then authenticate with it. This is the flow
1723
+ §27 exists for; before it, every step but the last had to happen out of band.
1724
+
1725
+ ### Regenerating
1726
+
1727
+ `src/management/models.ts` and `src/management/ops/` are generated and committed. After
1728
+ re-vendoring `management-registry.json` or `openapi.json`:
1729
+
1730
+ ```bash
1731
+ npm run gen-management # regenerate
1732
+ npm run gen-management:check # what CI runs
1733
+ ```
1734
+
288
1735
  ## Error handling
289
1736
 
290
- Every persona throws exactly the three CONTRACT.md §2 error types — `AuthError`,
291
- `AuthzError`, `NetworkError`:
1737
+ Every persona throws the three CONTRACT.md §2 error types — `AuthError`, `AuthzError`,
1738
+ `NetworkError` — plus one `AuthError` **sub-type**, `OAuthProtocolError`, for RFC 6749
1739
+ protocol errors from `/oauth2/*` (its `message` is always `"<error>: <error_description>"`,
1740
+ and `instanceof AuthError` still matches it):
292
1741
 
293
1742
  ```typescript
294
1743
  import { AuthError, AuthzError, NetworkError } from 'axiam-sdk';
@@ -304,6 +1753,17 @@ try {
304
1753
  // transport-level failure
305
1754
  }
306
1755
  }
1756
+
1757
+ // OAuth2 protocol errors are AuthError sub-types (CONTRACT.md §2, §12.3 rule 3)
1758
+ import { OAuthProtocolError } from 'axiam-sdk';
1759
+
1760
+ try {
1761
+ await oidc.oidcRefresh({ refreshToken });
1762
+ } catch (err) {
1763
+ if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {
1764
+ // the refresh token was revoked or already used — re-authenticate
1765
+ }
1766
+ }
307
1767
  ```
308
1768
 
309
1769
  ## Security notes
@@ -311,10 +1771,15 @@ try {
311
1771
  - Token-carrying values are wrapped in `Sensitive<T>` — `toString()`/`toJSON()`/
312
1772
  `util.inspect` all redact to `[SENSITIVE]`; the raw value is only reachable via an
313
1773
  explicit accessor (CONTRACT.md §7).
314
- - Strict TLS verification is always on; the only escape hatch is the constructor's
315
- `customCa` option for self-signed development environments (CONTRACT.md §6).
1774
+ - Strict TLS verification is always on; the only server-trust escape hatch is the
1775
+ constructor's `customCa` option for self-signed development environments (CONTRACT.md §6).
1776
+ - Optional mutual TLS (mTLS): a PEM `clientCert`/`clientKey` client identity (Node only) is
1777
+ presented on both REST and gRPC without ever relaxing server verification (CONTRACT.md §6.1).
316
1778
  - AMQP messages are HMAC-SHA256 verified before your handler ever sees them; verification
317
1779
  failures are nacked without requeue (CONTRACT.md §8).
1780
+ - The OIDC relying-party flow is PKCE **S256**-only (`plain` is not implemented), ID tokens are
1781
+ `EdDSA`-only and validated on every exchange with no opt-out, and login state
1782
+ (`state`/`nonce`/`code_verifier`) is never stored inside the SDK (CONTRACT.md §12).
318
1783
 
319
1784
  ## Release / versioning
320
1785