axiam-sdk 1.0.0-alpha24 → 1.0.0-alpha27

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 (62) hide show
  1. package/README.md +487 -9
  2. package/dist/amqp/index.d.cts +768 -1
  3. package/dist/amqp/index.d.ts +768 -1
  4. package/dist/amqp/index.js +612 -1
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +578 -3
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-CA9zFm1n.d.cts → authzCore-DQSXszkj.d.ts} +68 -4
  9. package/dist/{authzCore-a-wZL2P3.d.ts → authzCore-Dzr_x_UK.d.cts} +68 -4
  10. package/dist/client-C2MEcxjG.d.cts +284 -0
  11. package/dist/client-YQQcFDTy.d.ts +284 -0
  12. package/dist/{cookieJar-C9fqLqbh.d.ts → cookieJar-BDeX40ZG.d.ts} +3 -3
  13. package/dist/{cookieJar-DeJKczxD.d.cts → cookieJar-C8YixLEs.d.cts} +3 -3
  14. package/dist/grpc/index.d.cts +33 -13
  15. package/dist/grpc/index.d.ts +33 -13
  16. package/dist/grpc/index.js +308 -7
  17. package/dist/grpc/index.js.map +1 -1
  18. package/dist/grpc/index.mjs +308 -7
  19. package/dist/grpc/index.mjs.map +1 -1
  20. package/dist/index.d.cts +5 -4
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.js +310 -38
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +301 -39
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{jwks-DEiwxlku.d.cts → jwks-CSXHo3DS.d.cts} +145 -1
  27. package/dist/{jwks-DEiwxlku.d.ts → jwks-CSXHo3DS.d.ts} +145 -1
  28. package/dist/middleware/index.d.cts +8 -7
  29. package/dist/middleware/index.d.ts +8 -7
  30. package/dist/middleware/index.js +651 -5
  31. package/dist/middleware/index.js.map +1 -1
  32. package/dist/middleware/index.mjs +649 -6
  33. package/dist/middleware/index.mjs.map +1 -1
  34. package/dist/nestjs/index.d.cts +4 -3
  35. package/dist/nestjs/index.d.ts +4 -3
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/nestjs/index.js.map +1 -1
  38. package/dist/nestjs/index.mjs +6 -3
  39. package/dist/nestjs/index.mjs.map +1 -1
  40. package/dist/node/index.d.cts +101 -7
  41. package/dist/node/index.d.ts +101 -7
  42. package/dist/node/index.js +1124 -12
  43. package/dist/node/index.js.map +1 -1
  44. package/dist/node/index.mjs +1103 -14
  45. package/dist/node/index.mjs.map +1 -1
  46. package/dist/{oidcState-tHRAg5bu.d.cts → oidcState-y6UaPeRx.d.cts} +601 -3
  47. package/dist/{oidcState-CfebuJ0n.d.ts → oidcState-ziGS0XYP.d.ts} +601 -3
  48. package/dist/rest/index.d.cts +5 -20
  49. package/dist/rest/index.d.ts +5 -20
  50. package/dist/rest/index.js +310 -38
  51. package/dist/rest/index.js.map +1 -1
  52. package/dist/rest/index.mjs +301 -39
  53. package/dist/rest/index.mjs.map +1 -1
  54. package/dist/{session-ti3C9ZJU.d.cts → session-BJHqprWm.d.ts} +48 -0
  55. package/dist/{session-ti3C9ZJU.d.ts → session-CMgYRxLP.d.cts} +48 -0
  56. package/dist/telemetry-DrGqL4kb.d.cts +124 -0
  57. package/dist/telemetry-DrGqL4kb.d.ts +124 -0
  58. package/dist/{types-BVkMoqLU.d.cts → types-CO10Ainw.d.cts} +23 -1
  59. package/dist/{types-BVkMoqLU.d.ts → types-CO10Ainw.d.ts} +23 -1
  60. package/package.json +1 -1
  61. package/dist/client-CtT9nHQP.d.cts +0 -72
  62. package/dist/client-utwuwc9m.d.ts +0 -72
package/README.md CHANGED
@@ -17,9 +17,13 @@ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanic
17
17
 
18
18
  ## Contract conformance
19
19
 
20
- This SDK conforms to CONTRACT.md §1–§13 (including §6.1 mTLS client certificates, the
21
- §10.1 minimum local-verification set, the §12 OIDC/SSO relying-party helpers, and the §13
22
- `verifyWebhook` signature verifier).
20
+ This SDK conforms to CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19, §20, §21, §22 (including §6.1 mTLS
21
+ client certificates, the §10.1 minimum local-verification set, the §12 OIDC/SSO
22
+ relying-party helpers, and the §13 `verifyWebhook` signature verifier).
23
+
24
+ §12.7, §14, §15 and §22 are named rather than folded into the range because they landed
25
+ after this SDK already claimed §1–§13: widening the range silently would turn a statement
26
+ that was true when written into a different claim without anyone editing it.
23
27
 
24
28
  ### §10.1 minimum local-verification set
25
29
 
@@ -217,14 +221,210 @@ import { consume, Sensitive } from 'axiam-sdk/amqp';
217
221
 
218
222
  const signingKey = new Sensitive(Buffer.from(process.env.AXIAM_AMQP_SIGNING_KEY ?? '', 'hex'));
219
223
 
220
- await consume('amqp://localhost:5672', 'axiam.audit.events', signingKey, async (event) => {
221
- // Only a verified event ever reaches this closure — HMAC-SHA256
222
- // signature checked and stripped by the SDK before your handler runs
223
- // (CONTRACT.md §8). Verification failures are nacked-without-requeue.
224
- console.log('verified audit event:', event);
225
- });
224
+ await consume(
225
+ // §8b: amqps:// only, enforced — a plaintext URL is refused before a socket
226
+ // opens, and there is no fallback for it to take.
227
+ 'amqps://localhost:5671',
228
+ 'axiam.audit.events',
229
+ signingKey,
230
+ async (event) => {
231
+ // Only a verified event ever reaches this closure — HMAC-SHA256
232
+ // signature checked and stripped by the SDK before your handler runs
233
+ // (CONTRACT.md §8). Verification failures are nacked-without-requeue.
234
+ console.log('verified audit event:', event);
235
+ },
236
+ // Optional. The PEM bundle for a privately issued broker certificate — the
237
+ // common in-cluster case (§8b rule 2), and the only TLS knob this SDK has.
238
+ { tls: { caCert: readFileSync('/etc/axiam/broker-ca.pem', 'utf8') } },
239
+ );
240
+ ```
241
+
242
+ #### Transport security (§8b)
243
+
244
+ `consume()` and `reactorServe()` both require `amqps://` and enforce it before
245
+ any socket is opened. HMAC signing (§8) gives authenticity and replay
246
+ protection across broker hops; TLS gives confidentiality. Both are required and
247
+ neither substitutes for the other — a signed `AuthzRequest` still names its
248
+ subject, resource and action in cleartext on an unencrypted wire.
249
+
250
+ | Option | Meaning |
251
+ |---|---|
252
+ | `tls.caCert` | PEM bundle for a privately issued broker certificate. Omit for a publicly issued one (Node's bundled roots verify it). |
253
+ | `tls.clientCert` + `tls.clientKey` | Mutual TLS toward the broker. All-or-nothing: half an identity is rejected before dialling. |
254
+
255
+ There is deliberately no verification-skip option, under any name (§8b rule 4).
256
+ A switch like that appears in a dev compose file, works, and travels unchanged
257
+ into production, where it turns TLS into an expensive no-op against precisely
258
+ the attacker TLS exists to stop. `caCert` covers the legitimate reason people
259
+ reach for one.
260
+
261
+ ### Node — reactors, AMQP extension actors (`axiam-sdk/amqp`, CONTRACT.md §22)
262
+
263
+ A **reactor** is an external process that subscribes to named hook events on the AMQP bus and
264
+ answers back — allow, deny, or a field-allow-listed mutation — inside a timeout the server
265
+ declared. It is AXIAM's answer to Zitadel Actions and Keycloak SPIs, and the difference is the
266
+ whole design: those load third-party code *into* the authorization server, and this keeps it
267
+ outside, reachable only through a signed reply schema the server validates before it believes
268
+ a word of it.
269
+
270
+ ```typescript
271
+ import { Sensitive } from 'axiam-sdk/amqp';
272
+ import { REACTOR_EVENTS, allow, deny, mutate, reactorServe } from 'axiam-sdk/amqp';
273
+
274
+ const signingKey = new Sensitive(Buffer.from(process.env.AXIAM_AMQP_SIGNING_KEY_HEX ?? '', 'hex'));
275
+
276
+ await reactorServe(
277
+ {
278
+ amqpUrl: 'amqps://reactor:secret@broker.example.com:5671',
279
+ tenantId: '11111111-1111-1111-1111-111111111111',
280
+ reactorId: '99999999-9999-9999-9999-999999999999',
281
+ signingKey, // the tenant's HKDF-derived AMQP subkey, never the master key
282
+ },
283
+ (event) => {
284
+ switch (event.event) {
285
+ // token.pre_issue is mutable — the `ext.` namespace, and nothing else.
286
+ case REACTOR_EVENTS.TOKEN_PRE_ISSUE:
287
+ return mutate({ 'ext.cost_center': '42' });
288
+ // login.post_auth is veto-only, plus step-up.
289
+ case REACTOR_EVENTS.LOGIN_POST_AUTH:
290
+ return deny('embargoed region');
291
+ default:
292
+ return allow();
293
+ }
294
+ },
295
+ );
296
+ ```
297
+
298
+ #### Binding handlers per event (§22.14)
299
+
300
+ The `switch` above is the shape every multi-event reactor grows, and its `default:` arm —
301
+ `return allow()` — answers on behalf of code that never ran. That is the defect §22.10
302
+ rule 2 forbids the *runtime* from committing, relocated into your file where the rule does
303
+ not reach it: an operator who set `fail_closed` on the registration has it defeated there.
304
+
305
+ `reactorHandlers` is §22.14's declarative form, in the spirit of the §11 declarative
306
+ authorization helpers:
307
+
308
+ ```typescript
309
+ import { REACTOR_EVENTS, reactorHandlers, reactorServe } from 'axiam-sdk/amqp';
310
+
311
+ await reactorServe(
312
+ options,
313
+ reactorHandlers({
314
+ [REACTOR_EVENTS.TOKEN_PRE_ISSUE]: (event) => mutate({ 'ext.cost_center': '42' }),
315
+ [REACTOR_EVENTS.LOGIN_POST_AUTH]: async (event) => deny('embargoed region'),
316
+ }),
317
+ );
318
+ ```
319
+
320
+ - **A misspelled event is a compile error**, because the map's key type is
321
+ `ReactorEventName` — and it is re-checked at runtime for JavaScript callers, who get no
322
+ such help. That runtime check is also how the three hot-path operations §22.7 excludes are
323
+ refused: they are in no registry row.
324
+ - **An unbound event abstains** — no reply, and the registration's `failure_policy` decides
325
+ (§22.8), exactly as it decides a timeout. Never a synthesized `allow`.
326
+ - Several maps may be passed (`reactorHandlers(tokenHandlers, loginHandlers)`) so handlers
327
+ can be split across modules; binding the same event twice throws rather than silently
328
+ overwriting.
329
+
330
+ It is pure sugar: the value it produces is exactly the `ReactorHandler` `reactorServe`
331
+ already takes. It opens nothing, verifies nothing, signs nothing, does not filter a patch,
332
+ and a handler's own rejection reaches the runtime unchanged so nothing is published.
333
+
334
+ See [`examples/reactor/index.ts`](examples/reactor/index.ts) for a complete three-hook reactor
335
+ with graceful shutdown and a telemetry hook.
336
+
337
+ #### The five hookable events, and their allow-lists
338
+
339
+ | Event | Mutable | Complete allow-list | Default failure policy |
340
+ |---|---|---|---|
341
+ | `token.pre_issue` | yes | the **`ext.`** namespace only | `fail_open` |
342
+ | `login.post_auth` | no | — (veto, or `require_mfa`) | `fail_closed` |
343
+ | `user.pre_create` | yes | `username`, `email`, `metadata.` | `fail_closed` |
344
+ | `user.pre_update` | yes | `username`, `email`, `metadata.` | `fail_closed` |
345
+ | `grant.pre_assign` | no | — (veto only) | `fail_closed` |
346
+
347
+ An entry ending in `.` is a **namespace prefix** and needs at least one character after the
348
+ dot: `ext.` admits `ext.department` and `ext.a.b.c`, and refuses `ext.` itself, `ext`, `extra`,
349
+ `external_id` and `evil.ext.department`. So a reactor can never reach `sub`, `aud`, `exp`,
350
+ `scope` or any other standard claim — a **correctly signed** reply setting `sub` is refused
351
+ exactly as a forged one is.
352
+
353
+ Registrations that name no `failure_policy` get **the strictest default among their events**,
354
+ in either array order — `defaultFailurePolicyFor([...])` computes it, and "take the first
355
+ event's default" is specifically what §22.8 forbids, because it lets the order of a JSON array
356
+ decide whether an unreachable fraud check passes.
357
+
358
+ #### `authz.check` is not hookable, and this SDK does not pretend otherwise
359
+
360
+ `authz.check`, `authz.check_batch` and `token.introspect` are absent from `EVENT_REGISTRY`,
361
+ from `REACTOR_EVENTS` and from every example here (§22.7, a normative MUST NOT). A reactor
362
+ round-trip is milliseconds; the check path's budget is microseconds. An application that needs
363
+ external input on an authorization decision writes a **deny grant**, which the engine
364
+ evaluates in the hot path at hot-path cost — and there is deliberately no client-side
365
+ interceptor in this SDK offering itself as the reactor equivalent.
366
+
367
+ #### What the runtime guarantees
368
+
369
+ - **Both directions are signed.** The server signs the event with the tenant's HKDF-derived
370
+ AMQP subkey; the reactor signs its reply with the same key. An unsigned or stale reply is
371
+ not a weak reply — the server discards it as though the reactor had never answered. Every
372
+ event is verified (`key_version >= 2`, MAC, ±300 s freshness, nonce seen-set) *before* your
373
+ handler is called.
374
+ - **Two canonicalization quirks, both of which are silent failures if missed.** First, a
375
+ reactor body signs `hmac_signature` as **`null`**, where §8's own two message types omit it.
376
+ Second — and this one is TypeScript's alone — `Date.prototype.toISOString()` always emits
377
+ three fractional digits, while the server's `chrono` emits none on a whole second; a reply
378
+ timestamped `…T12:00:00.000Z` is re-serialized server-side as `…T12:00:00Z` and its MAC
379
+ fails with no other symptom. `toChronoRfc3339()` is the fix and the runtime always uses it.
380
+ Both are pinned by server-generated vectors rather than by memory — see
381
+ [`testdata/reactor_v2_reference_vectors.json`](testdata/reactor_v2_reference_vectors.json)
382
+ and [`test/amqp/reactor/vectors.test.ts`](test/amqp/reactor/vectors.test.ts).
383
+ - **It declares no topology.** No `assertQueue`, no `assertExchange`, no `bindQueue` — the
384
+ server owns all three, and the `ReactorChannel` seam this runtime is written against does
385
+ not even offer them. A reactor that can bind is a reactor that can bind itself to
386
+ `*.token.pre_issue` and read another tenant's issuance events.
387
+ - **It fails closed on its own errors.** A handler that throws, a body that will not parse, a
388
+ window that has already closed: each publishes **nothing**, so the registration's
389
+ `failure_policy` decides. Synthesizing an `allow` would override the operator's
390
+ `fail_closed` setting from inside the library. `abstain()` is the explicit form of the same
391
+ thing.
392
+ - **It does not filter your patch.** One forbidden key rejects the whole patch server-side;
393
+ pruning it here would leave you believing a field was set when it was dropped. Check
394
+ yourself with `patchFieldAllowed(spec, field)` if you want to know before you send.
395
+ - **It honours `timeout_ms`.** The handler runs inside the window the server declared, and a
396
+ reply whose window has closed is abandoned rather than published late.
397
+ - **Shutdown drains (§18).** Pass an `AbortSignal`; aborting it cancels the consumer, lets
398
+ every dispatch already running finish — handler, signature, publish — and only then closes
399
+ the channel and connection.
400
+
401
+ #### Registering a reactor (§22.9)
402
+
403
+ Registration is a REST admin call, not part of this runtime:
404
+
405
+ ```bash
406
+ curl -X POST https://axiam.example.com/api/v1/reactors \
407
+ -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
408
+ -d '{"name":"fraud-check","events":["login.post_auth"],"mode":"intercept","timeout_ms":500}'
226
409
  ```
227
410
 
411
+ The response's `id` is what `reactorId` takes, and the server declares the queue.
412
+ `timeout_ms` defaults to **500** and is refused outside `1…5000`; the chain's wall-clock
413
+ ceiling is **5000 ms** and the per-tenant in-flight cap is **64**. This SDK exposes those as
414
+ constants (`DEFAULT_REACTOR_TIMEOUT_MS`, `MAX_REACTOR_TIMEOUT_MS`,
415
+ `DEFAULT_REACTOR_MAX_IN_FLIGHT`) but ships **no typed client for the CRUD endpoints** — call
416
+ them through the REST client, and let the server validate; §22.9 explicitly warns against
417
+ re-deriving `PUT` merge semantics or the `failure_policy` re-derivation client-side.
418
+
419
+ #### Logging
420
+
421
+ The `payload`, `patch`, `reason` and `decision` are tenant business data — readable by design,
422
+ since a handler that cannot inspect the event cannot decide anything, but this runtime never
423
+ logs them at info level and yours should not either (§22.12). The signing key is
424
+ `Sensitive<Buffer>`, is never logged at any level, and never appears in an error payload.
425
+ `nonce`, `correlation_id` and `hmac_signature` are not secrets and may be logged for
426
+ correlation.
427
+
228
428
  ### Express middleware (`axiam-sdk/middleware`)
229
429
 
230
430
  ```typescript
@@ -507,6 +707,192 @@ strings.
507
707
 
508
708
  See `examples/express-oidc-login.ts` for a complete, runnable example.
509
709
 
710
+ ## Device authorization grant (`axiam-sdk/node`, CONTRACT.md §14)
711
+
712
+ RFC 8628 — signing in a device that cannot show a browser: a TV, a CLI, a headless
713
+ commissioning tool.
714
+
715
+ ```ts
716
+ const tokens = await oidc.deviceLogin({
717
+ onUserCode: (auth) => {
718
+ // Called BEFORE the first poll. Display it however the device can —
719
+ // screen, QR code, e-ink panel. The SDK never prints it for you.
720
+ console.log(`visit ${auth.verificationUri} and enter ${auth.userCode}`);
721
+ },
722
+ });
723
+ ```
724
+
725
+ `deviceAuthorize` and `devicePoll` are also public, for an application driving its own
726
+ loop. The polling rules are where implementations go wrong, so they are worth stating:
727
+
728
+ - **`slow_down` raises the interval permanently.** An SDK that backs off for one round and
729
+ returns to the original interval will be told to slow down again, forever.
730
+ - **`access_denied` and `expired_token` stay distinct.** A human said no, versus nobody
731
+ answered — the only information the device can act on.
732
+ - **Polling stops at `expires_in`**, even if the server has not yet said `expired_token`.
733
+ - **A `5xx` mid-poll is not terminal.** A server restart must not lose a grant the user has
734
+ already approved.
735
+
736
+ `deviceCode` is `Sensitive`; `userCode` deliberately is not — it exists to be read aloud,
737
+ and wrapping it would defeat the one thing it is for.
738
+
739
+ Per §14.3 rule 4, `deviceLogin` **returns** the token set rather than adopting it. See
740
+ [`examples/device-login.ts`](examples/device-login.ts).
741
+
742
+ ## Token exchange (`axiam-sdk/node`, CONTRACT.md §15)
743
+
744
+ RFC 8693 — a service holding a user's token exchanging it for a *narrower* one before
745
+ calling the next service.
746
+
747
+ ```ts
748
+ const exchanged = await oidc.tokenExchange({
749
+ subjectToken: new Sensitive(userToken),
750
+ subjectTokenType: ACCESS_TOKEN_TYPE, // required (§15.1), no default
751
+ scopes: ['orders:read'],
752
+ audience: 'orders-service',
753
+ });
754
+ ```
755
+
756
+ Most of what this method does is refuse to be helpful, and each refusal is deliberate:
757
+
758
+ - **No default `actorToken`.** Omitting it asks for *impersonation*; the SDK will not
759
+ quietly substitute the client's own session token and turn that into a delegation.
760
+ - **No auto-narrowing after `invalid_scope`.** The server refuses rather than silently
761
+ narrowing precisely so the caller finds out here.
762
+ - **No refresh token, ever** — `ExchangedToken` has no such field, so there is nothing to
763
+ synthesise. Re-run the exchange.
764
+ - **No adoption.** The issued token is handed onward in one call; adopting it would
765
+ silently re-privilege every later call this client makes. A MUST NOT, where
766
+ `loginClientCredentials` adoption is a MAY.
767
+
768
+ See [`examples/token-exchange.ts`](examples/token-exchange.ts).
769
+
770
+ ### External-IdP subject tokens (CONTRACT.md §15.7)
771
+
772
+ The same method exchanges a token minted by a **trusted external IdP** — a partner's
773
+ Entra, Okta or Keycloak — for an AXIAM token scoped to what the resolved AXIAM user may
774
+ actually do. There is no separate operation:
775
+
776
+ ```ts
777
+ const exchanged = await oidc.tokenExchange({
778
+ subjectToken: new Sensitive(partnerToken),
779
+ subjectTokenType: JWT_TOKEN_TYPE, // named, never guessed
780
+ scopes: ['read:orders'],
781
+ audience: 'https://orders.internal',
782
+ });
783
+ ```
784
+
785
+ - **`subjectTokenType` is yours to state, and is required** (§15.1). The SDK never decodes
786
+ the subject token to pick it, and never overrides what you named. There is no default —
787
+ omitting it does not compile, because a default would be the SDK choosing for you.
788
+ - **No actor token.** Delegation across a trust boundary is unsupported in v1; sending one
789
+ is `invalid_request`, which the SDK will not work around by dropping it and re-sending.
790
+ - **One refusal is distinguishable.** `invalid_grant` whose description is `the subject
791
+ token's issuer is not configured for token exchange` means *fix the AXIAM trust
792
+ configuration*. Every other `invalid_grant` means *fix your token*, and is deliberately
793
+ generic.
794
+ - **Forward the result as-is.** It carries an `ext_exchange` claim naming the partner
795
+ issuer; never strip it, and never read it as an authorization input. It also cannot be
796
+ exchanged again — exchanges do not compose.
797
+
798
+ See [`examples/external-token-exchange.ts`](examples/external-token-exchange.ts) and the
799
+ operator guide, `docs/api/federated-token-exchange.md`.
800
+
801
+ ## Logout — RP-initiated and back-channel (`axiam-sdk/node`, CONTRACT.md §12.7)
802
+
803
+ `logoutUrl` builds the redirect; `verifyLogoutToken` validates a token the OP **pushed** to
804
+ your back-channel endpoint.
805
+
806
+ ```ts
807
+ const url = await oidc.logoutUrl({ idToken });
808
+
809
+ // …and at your registered backchannel_logout_uri:
810
+ const verified = await oidc.verifyLogoutToken(logoutToken);
811
+ if (verified.sid) {
812
+ endSession(verified.sid); // that session ONLY
813
+ }
814
+ ```
815
+
816
+ The verifier is where the security weight sits — the input arrives unsolicited and
817
+ instructs you to terminate a session. It checks the signature (same JWKS path, same
818
+ `kid`-required discipline as §12.4), `iss`, `aud`, that `events` carries the
819
+ back-channel-logout key (**the only thing separating a logout token from an ID token**),
820
+ that `nonce` is *absent* (its presence is how an ID token gets replayed as one), that
821
+ something is named, and freshness.
822
+
823
+ It returns `sid`/`sub`/`jti` rather than a bare boolean: you have to know *which* session to
824
+ end. **Dedup on `jti` yourself** — delivery is at-least-once, so a valid token legitimately
825
+ arrives twice; the SDK has no durable store and an in-memory guard would silently drop a
826
+ real second logout after a restart.
827
+
828
+ See [`examples/logout.ts`](examples/logout.ts).
829
+
830
+ ## UMA 2.0 — Protection API and ticket grant (CONTRACT.md §20)
831
+
832
+ The resource-server side of User-Managed Access: register what you guard, ask the
833
+ authorization server what a caller would need, and redeem the resulting ticket.
834
+
835
+ The two runnable halves are [`examples/uma-resource-server.ts`](examples/uma-resource-server.ts)
836
+ and [`examples/uma-client.ts`](examples/uma-client.ts) — run the first, then the second
837
+ against it.
838
+
839
+ ### Making a denial actionable (`axiam-sdk/middleware`)
840
+
841
+ ```ts
842
+ import { requireAccess, type UmaChallenger } from 'axiam-sdk/middleware';
843
+
844
+ const challenger: UmaChallenger = {
845
+ realm: 'invoices',
846
+ asUri: (await oidc.oidcDiscover()).issuer,
847
+ pat, // a client-credentials token carrying `uma_protection` (§20.2 rule 1)
848
+ mint: (token, permissions) => oidc.umaRequestTicket(token, [...permissions]),
849
+ };
850
+
851
+ app.get(
852
+ '/invoices/:id',
853
+ requireAccess(session, 'invoices:read', fromParam('id'), { umaChallenge: challenger }),
854
+ handler,
855
+ );
856
+ ```
857
+
858
+ Without `umaChallenge` this is an ordinary §11 guard and a denial is a bare 403. With it, the
859
+ guard mints a permission ticket for the action it just refused and returns
860
+ `WWW-Authenticate: UMA realm=…, as_uri=…, ticket=…` alongside the 403 — so a UMA-aware client
861
+ knows where to obtain authority instead of only being told no. The body is unchanged, so a
862
+ client that does not speak UMA sees exactly the 403 it saw before. Both `requireAccess`
863
+ (Express) and `requireAccessHook` (Fastify) take the option.
864
+
865
+ **It is opt-in, and that is a design decision rather than an oversight.** Emitting a
866
+ challenge means *minting a credential*: a wire call to the Protection API and a live ticket,
867
+ produced on a path the caller did not explicitly request. A guard that did that on every
868
+ denial by default would turn each unauthorized request into a Protection API call — a
869
+ denial-of-service amplifier pointed at your own authorization server.
870
+
871
+ **Failure is not escalation.** If minting fails — expired PAT, Protection API down, a scope
872
+ the resource never declared — the denial still surfaces as a plain 403 with no challenge. A
873
+ caller who was going to be refused is refused either way; letting an outage turn a deny into
874
+ a 500 would give it a second consequence, and letting it turn into an allow would be a
875
+ security bug.
876
+
877
+ ### Consuming the challenge (`axiam-sdk/node`)
878
+
879
+ ```ts
880
+ import { umaParseChallenge } from 'axiam-sdk/node';
881
+
882
+ const challenge = umaParseChallenge(response.headers.get('www-authenticate') ?? '');
883
+ if (challenge?.ticket) {
884
+ // Deciding whether to trust challenge.asUri is YOUR call — parsing performed no
885
+ // exchange, deliberately (§20.3): that host was chosen by the server you just
886
+ // failed against.
887
+ const rpt = await oidc.umaExchangeTicket({ ticket: challenge.ticket, claimToken: userToken });
888
+ }
889
+ ```
890
+
891
+ The rest of the surface — `umaRegisterResource`, the other four `rreg` operations,
892
+ `umaRequestTicket`, `umaExchangeTicket` — plus the rules they enforce (a ticket is never
893
+ retried, the RPT is never adopted, an update replaces the scope list rather than merging it)
894
+ is documented on the generated API docs for `axiam-sdk/node`.
895
+
510
896
  ## Webhook signature verification (`axiam-sdk/node`, CONTRACT.md §13)
511
897
 
512
898
  AXIAM signs every webhook delivery with a Stripe-style signed timestamp:
@@ -569,6 +955,98 @@ like a stale one — and accepts a `tolerance` override plus a `now` injection s
569
955
  failure always raises the typed `WebhookVerifyError` (never a generic exception whose message
570
956
  could leak the expected signature).
571
957
 
958
+ ## Client quality-of-life (CONTRACT.md §16–§19)
959
+
960
+ ### Retry policy (§16)
961
+
962
+ Read-only authorization checks — `checkAccess`, `can`, `batchCheck` — retry transient
963
+ failures under the contract's normative table: **3 attempts** (1 initial + 2 retries),
964
+ 200 ms base, 5 s cap, **full jitter** (uniform over `[0, backoff]`), and `Retry-After`
965
+ honored as a **floor**.
966
+
967
+ > **This changed in D5.** The previous policy used a 1000 ms base, an 8 s cap, partial
968
+ > jitter, and let `Retry-After` *replace* the backoff — so a `Retry-After: 0` retried
969
+ > immediately. Worse, `withRetry` was exported and unit-tested but **never called by
970
+ > `checkAccess`**, so this SDK performed no read-only retries at all. Both are fixed, and
971
+ > the conformance tests now assert through the public API rather than against the helper.
972
+
973
+ Only failures that could plausibly succeed on a second attempt are retried — transport
974
+ errors, `408`, `429`, `5xx`. A `401` or `403` is an answer, not a transport failure, and is
975
+ surfaced after exactly one attempt. Nothing that changes server state is ever retried.
976
+
977
+ ```ts
978
+ // Turn it off if you own your own retry layer — you know your deadline, this SDK doesn't.
979
+ const client = new AxiamClient({ baseUrl, tenantSlug: 'acme', retryEnabled: false });
980
+ ```
981
+
982
+ There is deliberately no knob for the attempt cap, base delay or delay cap: §16.1 forbids
983
+ raising them, and eleven SDKs agreeing on one table is the point.
984
+
985
+ ### Deterministic shutdown (§18)
986
+
987
+ `client.close()` releases the client's local resources. It is idempotent, and any call
988
+ afterwards rejects with a `NetworkError` naming the cause rather than silently reconnecting.
989
+
990
+ **`close()` does not log out.** It never reaches the network. The server-side session
991
+ deliberately outlives the client object — that is what lets a process restart and resume —
992
+ so a `close()` that logged out would silently end every user's session on each deploy. Call
993
+ `logout()` first if ending the session is what you want.
994
+
995
+ ### Telemetry hooks (§19)
996
+
997
+ Wire metrics without this package depending on any metrics library:
998
+
999
+ ```ts
1000
+ const client = new AxiamClient({
1001
+ baseUrl,
1002
+ tenantSlug: 'acme',
1003
+ telemetryHook: (event) => {
1004
+ if (event.type === 'requestEnd') {
1005
+ histogram.record(event.durationMs, { op: event.operation, outcome: event.outcome });
1006
+ } else if (event.type === 'retry') {
1007
+ counter.add(1, { op: event.operation, attempt: event.attempt });
1008
+ }
1009
+ },
1010
+ });
1011
+ ```
1012
+
1013
+ - **A hook that throws cannot fail the operation that fired it.** Telemetry is not permitted
1014
+ to fail an authorization check.
1015
+ - **No event payload can carry a token.** `TelemetryEvent` is a closed union with a fixed
1016
+ field set — this surface exists to be shipped to a metrics backend.
1017
+ - **Path templates, not URLs**, so a metric label cannot become a cardinality bomb.
1018
+
1019
+ One `requestStart`/`requestEnd` pair is emitted **per attempt**, so you can count real wire
1020
+ calls. See [`examples/telemetry-hook.ts`](examples/telemetry-hook.ts), including the
1021
+ OpenTelemetry mapping.
1022
+
1023
+ ### Decision memo (§17) — opt-in, off by default
1024
+
1025
+ An optional TTL-bounded cache for `checkAccess` results. **Disabled by default**, because
1026
+ §11.2 rule 6's ban on caching authorization decisions is still the default behaviour.
1027
+
1028
+ ```ts
1029
+ const client = new AxiamClient({
1030
+ baseUrl,
1031
+ tenantSlug: 'acme',
1032
+ decisionMemoTtlMs: 5000, // 0 = off, which is the default
1033
+ });
1034
+ ```
1035
+
1036
+ **What you are accepting.** The staleness bound is the TTL, in *both* directions: a grant
1037
+ revoked on the server can still read as allowed for up to the TTL, and a grant just added
1038
+ can still read as denied for up to the TTL.
1039
+
1040
+ > **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role and
1041
+ > immediately re-checks is the case that breaks, and it breaks silently. If that is your
1042
+ > workload, leave this off.
1043
+
1044
+ The TTL is clamped to 5000 ms rather than rejected. Allows and denies are memoized
1045
+ identically — asymmetric caching would leak which outcome occurred through latency.
1046
+ Failures are never memoized: caching a transport error as a deny would turn a blip into a
1047
+ TTL-long outage. The memo is cleared on `login`, `verifyMfa`, `refresh` and `logout`, since
1048
+ entries are keyed by subject rather than by session.
1049
+
572
1050
  ## Error handling
573
1051
 
574
1052
  Every persona throws the three CONTRACT.md §2 error types — `AuthError`, `AuthzError`,