axiam-sdk 1.0.0-beta15 → 1.0.0-beta17

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 (56) hide show
  1. package/README.md +455 -12
  2. package/dist/amqp/index.js.map +1 -1
  3. package/dist/amqp/index.mjs.map +1 -1
  4. package/dist/{authzCore-BZahGkBf.d.cts → authzCore-BpXRhTLF.d.cts} +70 -6
  5. package/dist/{authzCore-Biyca_Rm.d.ts → authzCore-BxCr9i1y.d.ts} +70 -6
  6. package/dist/browser/index.d.cts +2 -2
  7. package/dist/browser/index.d.ts +2 -2
  8. package/dist/{client-DLapMy-5.d.ts → client-CX7MwFct.d.ts} +895 -160
  9. package/dist/{client-CzVEJTC5.d.cts → client-D3BOv0PD.d.cts} +895 -160
  10. package/dist/{cookieJar-DIpQK-11.d.ts → cookieJar-B4bMYc7_.d.ts} +3 -3
  11. package/dist/{cookieJar-DoJeU4IN.d.cts → cookieJar-Uh-6shG1.d.cts} +3 -3
  12. package/dist/errors-CxqAZsex.d.cts +168 -0
  13. package/dist/errors-CxqAZsex.d.ts +168 -0
  14. package/dist/grpc/index.d.cts +218 -11
  15. package/dist/grpc/index.d.ts +218 -11
  16. package/dist/grpc/index.js +1086 -200
  17. package/dist/grpc/index.js.map +1 -1
  18. package/dist/grpc/index.mjs +1085 -201
  19. package/dist/grpc/index.mjs.map +1 -1
  20. package/dist/index.d.cts +4 -3
  21. package/dist/index.d.ts +4 -3
  22. package/dist/index.js +910 -183
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +903 -184
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{jwks-CSXHo3DS.d.cts → jwks-DmERws3k.d.cts} +36 -13
  27. package/dist/{jwks-CSXHo3DS.d.ts → jwks-DmERws3k.d.ts} +36 -13
  28. package/dist/middleware/index.d.cts +301 -15
  29. package/dist/middleware/index.d.ts +301 -15
  30. package/dist/middleware/index.js +431 -21
  31. package/dist/middleware/index.js.map +1 -1
  32. package/dist/middleware/index.mjs +426 -22
  33. package/dist/middleware/index.mjs.map +1 -1
  34. package/dist/nestjs/index.d.cts +2 -2
  35. package/dist/nestjs/index.d.ts +2 -2
  36. package/dist/nestjs/index.js +9 -3
  37. package/dist/nestjs/index.js.map +1 -1
  38. package/dist/nestjs/index.mjs +9 -3
  39. package/dist/nestjs/index.mjs.map +1 -1
  40. package/dist/node/index.d.cts +5 -5
  41. package/dist/node/index.d.ts +5 -5
  42. package/dist/node/index.js +914 -186
  43. package/dist/node/index.js.map +1 -1
  44. package/dist/node/index.mjs +914 -186
  45. package/dist/node/index.mjs.map +1 -1
  46. package/dist/{oidcState-CffZ6PkC.d.ts → oidcState-D9o_JxmM.d.ts} +2 -2
  47. package/dist/{oidcState-CSi4DY8h.d.cts → oidcState-E8Z5dXgQ.d.cts} +2 -2
  48. package/dist/rest/index.d.cts +8 -171
  49. package/dist/rest/index.d.ts +8 -171
  50. package/dist/rest/index.js +910 -183
  51. package/dist/rest/index.js.map +1 -1
  52. package/dist/rest/index.mjs +903 -184
  53. package/dist/rest/index.mjs.map +1 -1
  54. package/dist/{session-ymrHvMuJ.d.ts → session-Bsn9t50R.d.cts} +216 -2
  55. package/dist/{session-oiuBA1ZA.d.cts → session-BuqKS5nx.d.ts} +216 -2
  56. package/package.json +1 -1
package/README.md CHANGED
@@ -1,8 +1,13 @@
1
1
  # axiam-sdk (TypeScript/JavaScript)
2
2
 
3
+ <!-- Track the CURRENT channel's dist-tag, not `latest`: releases are prereleases and
4
+ the publish job keeps those off `latest` (see "Release / versioning"), so a plain
5
+ `npm/v/axiam-sdk` badge reports whatever was last published to `latest` — today
6
+ 1.0.0-alpha28, dozens of releases stale. Move `beta` below to `rc`, then drop it
7
+ entirely, as the channel advances. -->
3
8
  [![CI](https://github.com/ilpanich/axiam-typescript-sdk/actions/workflows/sdk-ci-typescript.yml/badge.svg?branch=main)](https://github.com/ilpanich/axiam-typescript-sdk/actions/workflows/sdk-ci-typescript.yml)
4
9
  [![Coverage Status](https://coveralls.io/repos/github/ilpanich/axiam-typescript-sdk/badge.svg?branch=main)](https://coveralls.io/github/ilpanich/axiam-typescript-sdk?branch=main)
5
- [![npm](https://img.shields.io/npm/v/axiam-sdk.svg)](https://www.npmjs.com/package/axiam-sdk)
10
+ [![npm](https://img.shields.io/npm/v/axiam-sdk/beta?label=npm%20beta)](https://www.npmjs.com/package/axiam-sdk)
6
11
  [![Docs](https://img.shields.io/badge/docs-TypeDoc-blue.svg)](https://ilpanich.github.io/axiam-typescript-sdk/)
7
12
  [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
8
13
 
@@ -13,33 +18,54 @@ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanic
13
18
  ## Package identity
14
19
 
15
20
  - **npm package:** `axiam-sdk`
16
- - **Registry:** [npmjs.com/package/axiam-sdk](https://www.npmjs.com/package/axiam-sdk) _(reserved, not yet published)_
21
+ - **Registry:** [npmjs.com/package/axiam-sdk](https://www.npmjs.com/package/axiam-sdk) — published as prereleases, under the `alpha`/`beta` dist-tags
17
22
  - **Source:** [github.com/ilpanich/axiam-typescript-sdk](https://github.com/ilpanich/axiam-typescript-sdk)
18
23
  - **License:** Apache-2.0
19
24
  - **Node:** `>=22` — see [Supported Node versions](#supported-node-versions)
20
25
 
21
26
  ## Contract conformance
22
27
 
23
- This SDK conforms to **contract 1.42**: CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19,
24
- §20, §21, §22, §23, §24, §25, §26, §27 (including §6.1 mTLS client certificates, the §10.1
25
- minimum local-verification set, the §12 OIDC/SSO relying-party helpers, and the §13
28
+ This SDK conforms to **contract 1.52**: CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19,
29
+ §20, §21, §22, §23, §24, §25, §26, §27, §28 (including §6.1 mTLS client certificates, the
30
+ §10.1 minimum local-verification set, the §12 OIDC/SSO relying-party helpers, and the §13
26
31
  `verifyWebhook` signature verifier). §12 is implemented in full at its 1.38 shape: all
27
32
  **thirteen** operations, including the four public "Sign in with X" entry points.
28
33
 
34
+ ### Contract 1.51 — the dogfooding remediation
35
+
36
+ | Item | Status |
37
+ |---|---|
38
+ | §5.2 rule 1 — the acting tenant, `X-Axiam-Tenant` (`AxiamClientOptions.actingTenantId`, `client.actingTenant()`/`.clearActingTenant()`) | Shipped |
39
+ | §6.1 rules 6–10 — `authenticateDevice()`, the mTLS device login | Shipped |
40
+ | §1.1.1 / §10.3 — `TokenGrpcClient.validateToken`/`.introspectToken` | Shipped |
41
+ | §10.1 rule 9 at the default middleware entry point | **Fixed a real defect** — see the §10.1 section below and the CHANGELOG's `[Unreleased]` Breaking entry |
42
+ | §10.1 rule 9 at `Verifier.verifyAccessToken` itself | **Fixed a real defect** — see the §10.1 section below and the CHANGELOG's `[Unreleased]` Breaking entry |
43
+ | §27.6.1 — manifest `resources[].metadata`, the two-shape role binding, `serviceAccounts` | Shipped |
44
+ | §27.6.1 — manifest `webhooks` | **Declined** — named by the contract without being specified, and no consumer has asked for it |
45
+ | §6.1 rule 7 as a typestate | **Declined** — the client-side `AuthError` the rule itself names as conforming is what this SDK ships; a typestate would make `AxiamClient` generic in every caller for the sake of one operation |
46
+
47
+ See each linked section below for the full behaviour, and CHANGELOG.md's `[Unreleased]`
48
+ section for the complete Added/Changed/Fixed/Breaking list.
49
+
29
50
  **§12's operations live on `OidcClient`, not on `AxiamClient`** — the separate host §12.2
30
51
  permits where a packaging constraint requires one, which here is CI's proof that a `/rest`
31
52
  browser bundle pulls in no Node-only code. §12.2 forbids splitting them across two hosts, so
32
53
  the four operations contract 1.38 adds are on `OidcClient` too, with the nine that preceded
33
54
  them, even though three of them need no Node-only code at all.
34
55
 
35
- §27 is implemented **in full**, both halves: the 160-operation imperative surface *and*
56
+ §27 is implemented **in full**, both halves: the 162-operation imperative surface *and*
36
57
  the §27.6 declarative manifest with its §27.7 `defineManifest` and decorator forms. The
37
58
  contract asks an SDK that ships only one half to say which; this one ships both.
38
59
 
39
- §12.7, §14, §15, §22, §24, §25, §26 and §27 are named rather than folded into the range
40
- because they landed after this SDK already claimed §1–§13: widening the range silently
41
- would turn a statement that was true when written into a different claim without anyone
42
- editing it.
60
+ §28 (MCP resource-server helpers) is implemented on **both** framework surfaces — the
61
+ Express middleware and the Fastify plugin — with all three operations, the
62
+ `resourceMetadataUrl` guard option and §28.9's five required tests. This SDK is §28.10's
63
+ reference implementation: it lands first and the ten ports are read against it.
64
+
65
+ §12.7, §14, §15, §17, §19, §20, §21, §22, §23, §24, §25, §26, §27 and §28 are named rather
66
+ than folded into the range because they landed after this SDK already claimed §1–§13:
67
+ widening the range silently would turn a statement that was true when written into a
68
+ different claim without anyone editing it.
43
69
 
44
70
  ### §10.1 minimum local-verification set
45
71
 
@@ -49,7 +75,32 @@ rule on every inbound token: EdDSA `alg` pinned before the JWKS is consulted, a
49
75
  `exp` (`jose` only checks `exp` *if present*, so `requiredClaims: ['exp']` is passed
50
76
  explicitly), `nbf` honoured when present, `tenant_id` asserted against the session's
51
77
  configured tenant, `iss`/`aud` checked when configured, all under a named 60-second
52
- `CLOCK_SKEW_LEEWAY_SEC`.
78
+ `CLOCK_SKEW_LEEWAY_SEC` — **and, since contract 1.51, rule 9**: a token carrying `cnf` is
79
+ refused unless transport evidence backs it. `axiamMiddleware`/`axiamPlugin` derive that
80
+ evidence automatically from the request's own raw socket (the peer certificate the TLS
81
+ layer verified for *this* connection, when Node itself terminates TLS) via the new
82
+ `certificateProofFromSocket`; a deployment behind a proxy that forwards nothing still
83
+ refuses a bound token, correctly, rather than silently accepting it. **This closes a real
84
+ defect**: before 1.51 `authenticateRequest` applied no rule-9 check at all, so a `cnf`-bound
85
+ device token (every token `authenticateDevice()`, §6.1, mints) passed through as an
86
+ ordinary bearer credential. See the CHANGELOG's `[Unreleased]` Breaking entry.
87
+
88
+ **A second, independent defect in the same rule closed alongside it:**
89
+ `Verifier.verifyAccessToken` — the SDK's own documented "anything guarding a
90
+ route MUST use this" entry point (see `verifySignatureOnlyUnchecked`'s doc) —
91
+ applied rules 1–8 only and never read `cnf` at all, because it had no
92
+ transport to ask for a peer certificate. A guard written directly on it, per
93
+ that doc, therefore accepted a certificate- or DPoP-bound token — a device
94
+ token from `authenticateDevice()` among them — as an ordinary bearer
95
+ credential, even though `authenticateRequest` (and so `axiamMiddleware`/
96
+ `axiamPlugin`) was by then already safe. `verifyAccessToken` now takes an
97
+ optional third `proofs` argument — the same shape `authenticateRequest`
98
+ takes and forwards straight through — and defaults it to `{}` (no evidence),
99
+ so a bound token is refused unless the caller supplies matching evidence.
100
+ Internally it reuses `verifyTokenBinding`, the same function
101
+ `authenticateRequest` and a hand-rolled guard call, so local verification
102
+ never disagrees with itself about whether a token is a bearer token. See the
103
+ CHANGELOG's `[Unreleased]` Breaking entry.
53
104
 
54
105
  Because the `/oauth2/jwks` trust anchor is **organization-wide**, the session guarding a
55
106
  resource server must be configured with the tenant **UUID** (`tenantId`), since that is
@@ -74,9 +125,14 @@ See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contra
74
125
  ## Install
75
126
 
76
127
  ```bash
77
- npm install axiam-sdk
128
+ npm install axiam-sdk@beta
78
129
  ```
79
130
 
131
+ Every release so far is a prerelease, and the publish job files each one under its
132
+ channel's dist-tag (`beta` today) rather than `latest` — so name the channel, or pin an
133
+ exact version. A bare `npm install axiam-sdk` resolves `latest`, which no prerelease
134
+ moves.
135
+
80
136
  ## Supported Node versions
81
137
 
82
138
  | | Version | Why this one |
@@ -180,6 +236,54 @@ const client = new AxiamClient({
180
236
  browser build validates the PEM shape then ignores `clientCert`/`clientKey` — exactly as
181
237
  it already ignores `customCa`.
182
238
 
239
+ #### The mTLS device login, `authenticateDevice()` (§6.1 rules 6–10, contract 1.51)
240
+
241
+ A client built with `clientCert`/`clientKey` above authenticates by presenting that
242
+ certificate, rather than a username and password:
243
+
244
+ ```ts
245
+ const device = new AxiamClient({
246
+ baseUrl: 'https://iam.example.com',
247
+ tenantSlug: 'acme',
248
+ clientCert: readFileSync('device.crt', 'utf8'),
249
+ clientKey: readFileSync('device.key', 'utf8'),
250
+ });
251
+
252
+ const token = await device.authenticateDevice(); // POST /api/v1/auth/device, no body
253
+ // token.accessToken: Sensitive<string>, token.tokenType === 'Bearer', token.expiresIn
254
+ await device.management.serviceAccounts.list(); // adopted: carries Authorization: Bearer
255
+ ```
256
+
257
+ - **Reachable only on a client built with a certificate.** Calling it on one that was not
258
+ fails client-side with `AuthError` and **zero wire calls** — the server would answer
259
+ `401` in any case, so going to the wire earns nothing.
260
+ - **Adopted like a `login()` result.** Every subsequent same-origin request carries the
261
+ token as `Authorization: Bearer`, and withholds any cookie a previous session on the same
262
+ client left behind — the server reads the `axiam_access` cookie *before* the
263
+ `Authorization` header, so a stale one would otherwise silently win.
264
+ - **There is no refresh token.** A device re-authenticates by calling
265
+ `authenticateDevice()` again — one TLS handshake. A later `401` on the adopted token
266
+ surfaces as `AuthError` without a refresh attempt, on REST and gRPC alike — gRPC calls
267
+ send the device token too (not the cookie-jar-synced one) once it is adopted.
268
+ - **Held until replaced.** `logout()` clears it; `refresh()` does not. Any later
269
+ session-establishing call replaces it with its own session: `login()`, `verifyMfa()`,
270
+ `loginOpaque()`, a WebAuthn authentication, an SSO/federation completion,
271
+ `loginClientCredentials({ adoptAsCredential: true })`, or another `authenticateDevice()`
272
+ call. A **refused** re-authentication over `authenticateDevice()` leaves the previously
273
+ adopted device credential exactly as it was — it does not fail into "no credential at
274
+ all".
275
+ - **Every refusal is a `401`** — unknown, untrusted, expired, revoked or unbound
276
+ certificate, or a `Server`-type certificate — mapped to `AuthError` verbatim. The route is
277
+ rate-limited per client IP; a `429` maps to `NetworkError`, not `AuthError`, and is never
278
+ retried.
279
+ - **The token is certificate-bound** (`cnf.x5t#S256`) — see the §10.1 rule 9 section below
280
+ for what that means for anything that verifies it.
281
+
282
+ `examples/device_login.rs`-style RFC 8628 device-code polling
283
+ (`axiam-sdk/node`'s `deviceLogin`/`deviceAuthorize`, CONTRACT.md §14) is a completely
284
+ different flow — a *human* completes it on a second screen. This is the machine-only mTLS
285
+ login; the two are unrelated beyond sharing the word "device".
286
+
183
287
  #### RFC 8705 §5 `mtls_endpoint_aliases` (contract 1.40, CONTRACT.md §21.3 rule 2)
184
288
 
185
289
  A TLS listener decides whether to ask for a client certificate during the handshake,
@@ -357,6 +461,42 @@ Calling `getUserInfo()` with no token present raises `AuthError` client-side, wi
357
461
  call (CONTRACT.md §1.1). A `UNAUTHENTICATED` response drives exactly one refresh + one retry,
358
462
  identical to `checkAccess`.
359
463
 
464
+ #### gRPC token validation (`TokenGrpcClient`, CONTRACT.md §1.1.1, §10.3, contract 1.51)
465
+
466
+ `validateToken`/`introspectToken` wrap `axiam.v1.TokenService`, the operations §10.3
467
+ requires so an SDK validating a token over gRPC has somewhere to read `cnf` from at all.
468
+ Same channel/interceptor/refresh machinery as `AuthzGrpcClient`/`UserInfoGrpcClient`:
469
+
470
+ ```typescript
471
+ import { TokenGrpcClient, createNodeSession } from 'axiam-sdk/grpc';
472
+ import { verifyTokenBinding } from 'axiam-sdk/node';
473
+
474
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
475
+ // ... after a successful login() on an AxiamClient sharing this session ...
476
+ const tokenClient = new TokenGrpcClient(session, { baseUrl: 'https://iam.example.com' });
477
+
478
+ const result = await tokenClient.validateToken(inspectedToken); // Sensitive<string> | string
479
+ if (result.valid) {
480
+ // §10.3 rule 2: valid: true is NOT "usable as presented" — verify possession
481
+ // against THIS caller's own connection before treating it as usable.
482
+ verifyTokenBinding({ cnf: result.cnf }, { certificateThumbprint: peerCertThumbprint });
483
+ }
484
+
485
+ tokenClient.close();
486
+ ```
487
+
488
+ - **Two tokens, kept apart.** The caller's own token authenticates the call, through the
489
+ interceptor, exactly as `checkAccess`/`getUserInfo` do. The token being inspected travels
490
+ in the request message and is a required argument — it can never silently fall back to
491
+ the caller's own.
492
+ - **`cnf` converts to the same `CnfClaim` the REST §10 middleware uses** —
493
+ `result.cnf`/`introspectToken`'s result feed directly into `verifyTokenBinding`/
494
+ `verifyCertificateBinding`, so gRPC validation and local REST verification cannot
495
+ disagree about whether a token is a bearer token (§10.3 rule 1).
496
+ - **Boundness comes from `cnf` alone, never `token_type`** — a certificate-bound token is
497
+ reported `"Bearer"` too.
498
+ - With no caller token, both calls raise `AuthError` client-side, with zero wire calls.
499
+
360
500
  ### Node — AMQP consumer (`axiam-sdk/amqp`)
361
501
 
362
502
  ```typescript
@@ -1325,6 +1465,55 @@ produces a `403` — so a UI that offers the switch to everyone has turned a
1325
1465
  distinction the server made into a failure the user discovers. `false` against a
1326
1466
  server older than contract 1.31, which is the safe reading of absent.
1327
1467
 
1468
+ #### Acting on another tenant (§5.2 rule 1, contract 1.51)
1469
+
1470
+ An organization-level principal switches which tenant it acts on with
1471
+ `client.actingTenant(tenantId)` — no re-login, since it already is a principal
1472
+ of every tenant in its organization:
1473
+
1474
+ ```ts
1475
+ const acting = client.actingTenant('99999999-9999-4999-8999-999999999999');
1476
+ await acting.management.groups.list(); // carries X-Axiam-Tenant
1477
+ await client.management.groups.list(); // unaffected — the original handle
1478
+ ```
1479
+
1480
+ `actingTenant()` returns a **new handle** over the same session (§9's refresh
1481
+ guard, §17's decision memo, the cookie jar all stay shared); `client` itself is
1482
+ unchanged. That is what lets a provisioning task hold one login result while
1483
+ acting on several tenants concurrently, without two calls racing to rewrite one
1484
+ shared header. `client.clearActingTenant()` returns a handle that sends none —
1485
+ the inverse. The same option is available at construction,
1486
+ `new AxiamClient({ ..., actingTenantId })`, for a client built to act on another
1487
+ tenant from the start; the construction-time form cannot gate on
1488
+ `organizationLevel` (it precedes the login that would reveal it), so `403` from
1489
+ the server is the answer there.
1490
+
1491
+ `tenantId` must be a UUID — checked client-side, with no wire call, because the
1492
+ server silently ignores a value that fails to parse and answers for the
1493
+ caller's own tenant. Once a login result is held, `actingTenant()` also refuses
1494
+ client-side (`AuthzError`, zero wire calls) for a non-organization-level
1495
+ principal, and for a tenant outside `reachableTenantIds` when the login
1496
+ response narrowed it (§5.2.3) — compared as UUIDs (case- and
1497
+ formatting-insensitive), never as raw strings, so an upper-case `tenantId`
1498
+ still matches a `reachableTenantIds` entry the server reported in its own
1499
+ lower-case canonical form. A login result is held after `login`,
1500
+ `verifyMfa`, OPAQUE login and the MFA and WebAuthn setup completions, whose
1501
+ responses carry the user object. A WebAuthn authentication, any SSO/federation
1502
+ completion (`ssoComplete`, `ssoCompleteOauth2`, `ssoCompleteHandoff`) or the
1503
+ device login resets it, so the header is sent and the server decides.
1504
+
1505
+ `client.logout()` does **not** clear an acting tenant a handle was built with —
1506
+ the handle's `#actingTenantId` is untouched, so a handle returned by
1507
+ `client.actingTenant(id)` still sends `X-Axiam-Tenant: id` on any call made
1508
+ through it after `logout()`, and the server's session-based rejection (no
1509
+ session, no wire call — §27.4 rule 1) is what stops the request, not this
1510
+ header. Only `clearActingTenant()` (or building a fresh handle) removes it.
1511
+
1512
+ **REST-only.** The gRPC interceptor reads no acting-tenant metadata — a gRPC
1513
+ call through any handle still acts on the token's own tenant. `X-Tenant-ID` and
1514
+ a management route's `{tenant_id}` path default (§27.4 rule 3) are unaffected
1515
+ either way; the acting tenant is a different mechanism from both.
1516
+
1328
1517
  #### Signing one in (§5.2.1)
1329
1518
 
1330
1519
  The reserved tenant has a fixed slug, `organization`, the same in every
@@ -1705,6 +1894,211 @@ like a stale one — and accepts a `tolerance` override plus a `now` injection s
1705
1894
  failure always raises the typed `WebhookVerifyError` (never a generic exception whose message
1706
1895
  could leak the expected signature).
1707
1896
 
1897
+ ## MCP resource-server helpers (`axiam-sdk/middleware`, CONTRACT.md §28)
1898
+
1899
+ The resource-server half of the Model Context Protocol authorization handshake: publish the
1900
+ RFC 9728 document that tells an MCP client which authorization server guards this resource,
1901
+ and put the RFC 6750 `WWW-Authenticate` challenge on the 401 that starts its discovery.
1902
+
1903
+ **AXIAM is the authorization server and implements none of this.** Your MCP server is the
1904
+ resource server, and this is its side. Nothing here talks to AXIAM, performs any network I/O
1905
+ or touches the SDK client's own session — all three operations are pure local computation,
1906
+ like `oidcBegin` and `umaParseChallenge`. The *client* half — parsing a challenge, fetching
1907
+ a document, deciding whether to trust the authorization server it names — is deliberately
1908
+ not in the SDK: a helper that read a 401 and acted on it would send a credential to whatever
1909
+ host the 401 asked it to.
1910
+
1911
+ **It is opt-in and off by default.** With `resourceMetadataUrl` unset, every guard behaves
1912
+ byte-for-byte as it did before §28 existed: no header on any response, no status changed, no
1913
+ body changed.
1914
+
1915
+ ### The whole integration
1916
+
1917
+ ```ts
1918
+ import express from 'express';
1919
+ import { createVerifier } from 'axiam-sdk/node';
1920
+ import {
1921
+ axiamMiddleware,
1922
+ protectedResourceMetadata,
1923
+ serveProtectedResourceMetadata,
1924
+ } from 'axiam-sdk/middleware';
1925
+
1926
+ // 1. Describe the resource server. Validated here, at construction — before any
1927
+ // route exists and before any request is served.
1928
+ const metadata = protectedResourceMetadata({
1929
+ resource: 'https://mcp.example.com/mcp',
1930
+ authorizationServers: ['https://axiam.example.com'],
1931
+ scopesSupported: ['mcp:read', 'mcp:tools'],
1932
+ });
1933
+
1934
+ // 2. Configure the guard FROM that value rather than by retyping the strings —
1935
+ // retyping is how the guard and the document come to disagree. The session
1936
+ // is the same plain `VerifiableSession` literal §10.4's feed is attached to.
1937
+ const session = {
1938
+ jwksVerifier: createVerifier('https://axiam.example.com'),
1939
+ tenantHeaderValue: TENANT_UUID,
1940
+ expectedAudience: metadata.document.resource, // https://mcp.example.com/mcp
1941
+ resourceMetadataUrl: metadata.metadataUrl, // https://mcp.example.com/.well-known/…/mcp
1942
+ };
1943
+
1944
+ const app = express();
1945
+ app.use(axiamMiddleware(session));
1946
+
1947
+ // 3. Publish the document. Passing `session` is what lets the SDK check that
1948
+ // the three strings agree; it throws at startup if they do not.
1949
+ serveProtectedResourceMetadata(app, metadata, session);
1950
+
1951
+ app.post('/mcp', handler);
1952
+ ```
1953
+
1954
+ Fastify is the same three calls — `axiamPlugin(session)` instead of `axiamMiddleware`, and
1955
+ the Fastify instance instead of the Express app. `serveProtectedResourceMetadata` takes
1956
+ either.
1957
+
1958
+ A request with no credential now gets what it needs to go and get one:
1959
+
1960
+ ```http
1961
+ HTTP/1.1 401 Unauthorized
1962
+ WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
1963
+ Content-Type: application/json
1964
+
1965
+ {"error":"authentication_failed","message":"..."}
1966
+ ```
1967
+
1968
+ and the document it points at answers without a credential:
1969
+
1970
+ ```json
1971
+ {
1972
+ "resource": "https://mcp.example.com/mcp",
1973
+ "authorization_servers": ["https://axiam.example.com"],
1974
+ "scopes_supported": ["mcp:read", "mcp:tools"],
1975
+ "bearer_methods_supported": ["header"]
1976
+ }
1977
+ ```
1978
+
1979
+ **The path is derived from the resource, not chosen.** RFC 9728 §3.1 inserts
1980
+ `/.well-known/oauth-protected-resource` between the authority and the path, so
1981
+ `https://mcp.example.com/mcp` publishes at `/.well-known/oauth-protected-resource/mcp` and
1982
+ `https://mcp.example.com` at the bare well-known path. A trailing slash is carried through
1983
+ rather than trimmed — it is part of the identifier the client compares, and two resources
1984
+ that differ only by it are two resources. Exactly one route is registered; a deployment
1985
+ fronting several resources calls the helper once per resource.
1986
+
1987
+ **You do not have to order the routes.** Where the guard is mounted globally it exempts the
1988
+ document's path itself, from the `resourceMetadataUrl` it was configured with — which is the
1989
+ only thing that works on Fastify, where a `preHandler` hook applies to every route in its
1990
+ context no matter when it was registered.
1991
+
1992
+ ### Announcing yourself obliges you to check
1993
+
1994
+ **`expectedAudience` is mandatory once `resourceMetadataUrl` is set**, and every guard
1995
+ factory refuses the configuration at construction, naming both options. A resource server
1996
+ that publishes *"tokens for me carry this `aud`"* and then does not check `aud` has published
1997
+ a claim it does not honour — and a token minted for a **different** MCP server opens it. That
1998
+ is the confusion RFC 8707 exists to prevent, so it is impossible to configure rather than
1999
+ merely discouraged:
2000
+
2001
+ ```ts
2002
+ axiamMiddleware({ jwksVerifier, tenantHeaderValue, resourceMetadataUrl: metadata.metadataUrl });
2003
+ // ValidationError: resourceMetadataUrl: requires expectedAudience to be set on the
2004
+ // same session (CONTRACT.md §28.5 rule 2) — …
2005
+ ```
2006
+
2007
+ With both set, a token carrying `aud: "axiam:user"` — a perfectly valid AXIAM token that
2008
+ simply was not minted for this resource — is a 401, exactly like a token minted for
2009
+ `https://other.example.com/mcp`.
2010
+
2011
+ ### The 403 that asks for a scope
2012
+
2013
+ One class of 403 carries a challenge, and only one: a `requireAccess`/`requireAccessHook`
2014
+ that **named a scope** whose decision came back `allowed: false` with `reasonCode:
2015
+ "no_grant"`.
2016
+
2017
+ ```ts
2018
+ app.post('/mcp/tools', requireAccess(session, 'mcp:invoke', 'tools', { scope: 'mcp:tools' }), handler);
2019
+ ```
2020
+
2021
+ ```http
2022
+ HTTP/1.1 403 Forbidden
2023
+ WWW-Authenticate: Bearer error="insufficient_scope", scope="mcp:tools", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
2024
+ Content-Type: application/json
2025
+
2026
+ {"error":"authorization_denied","message":"..."}
2027
+ ```
2028
+
2029
+ `insufficient_scope` is in the header and `authorization_denied` is in the body, and they are
2030
+ not two spellings of one thing: the body is the §11 error taxonomy, unchanged, and the header
2031
+ is the RFC 6750 hint. The scope named is the one the route asked for, **verbatim** — never
2032
+ synthesised, never derived from `action`/`resource`, never substituted from the document's
2033
+ `scopes_supported`, because where a deployment's AXIAM resource-scope names and its OAuth
2034
+ scope names differ, that mapping is the operator's decision and the SDK cannot see it.
2035
+
2036
+ Every other 403 carries no header at all: a `requireAccess` with no `scope` argument, a
2037
+ `requireRole` failure, a CSRF refusal, and — the one that matters — a decision whose
2038
+ `reasonCode` is `denied_by_rule`. `no_grant` means *ask for more*, which is what a challenge
2039
+ invites a client to do; `denied_by_rule` means *an administrator has already decided*, and
2040
+ challenging on it would send an MCP client all the way around the authorization loop to
2041
+ arrive at the identical 403. An absent or unrecognised `reasonCode` is not eligible either.
2042
+
2043
+ Where a route also carries a `umaChallenge` (§20.3), the UMA challenge wins: it is per-route
2044
+ opt-in and carries a live ticket for the exact authority just refused, where this one is the
2045
+ generic hint. Only one `WWW-Authenticate` value is ever emitted.
2046
+
2047
+ ### The challenge says only what RFC 6750 can say
2048
+
2049
+ Expired, not yet valid, wrong tenant, wrong audience, bad signature, `alg` confusion, a `cnf`
2050
+ the guard could not satisfy, a `sid` in the §10.4 revocation feed — all of them are
2051
+ `invalid_token`, indistinguishably. The SDK's own guard never emits an `error_description`,
2052
+ and adds nothing to the response that tells them apart. It is a 401 to an unauthenticated
2053
+ stranger: every distinction it draws is an oracle.
2054
+
2055
+ `bearerChallenge` exists for the challenge you build yourself, for your own 400, and it takes
2056
+ `errorDescription` for that reason alone. It **refuses rather than escapes**: RFC 6750
2057
+ restricts every parameter to a character set that cannot contain `"` or `\`, so a value
2058
+ needing an escape is a value that does not belong in a challenge.
2059
+
2060
+ ```ts
2061
+ bearerChallenge({
2062
+ resourceMetadataUrl: metadata.metadataUrl,
2063
+ error: 'invalid_request',
2064
+ errorDescription: 'The access token is malformed',
2065
+ scope: 'mcp:read mcp:tools',
2066
+ });
2067
+ // Bearer error="invalid_request", error_description="The access token is malformed",
2068
+ // scope="mcp:read mcp:tools", resource_metadata="https://mcp.example.com/.well-known/…/mcp"
2069
+
2070
+ bearerChallenge({ resourceMetadataUrl: metadata.metadataUrl, errorDescription: 'he said "no"' });
2071
+ // ValidationError — never a challenge containing \"
2072
+ ```
2073
+
2074
+ ### Validation refuses; it never repairs
2075
+
2076
+ Every §28.2 rule is checked by `protectedResourceMetadata` itself, and a violation throws
2077
+ `ValidationError` (§2's taxonomy, unchanged — §28 adds no error type). Nothing is normalised,
2078
+ trimmed, lowercased or re-encoded to make it pass: that would publish a document describing a
2079
+ resource server that does not exist. The rules, in one list:
2080
+
2081
+ | Member | Rule |
2082
+ |---|---|
2083
+ | `resource` | absolute URI with a scheme and an authority, **no query and no fragment**; a trailing slash is significant |
2084
+ | any URL | `https`, except on `127.0.0.1`, `[::1]` or `localhost` — there is no flag, env var or debug build that widens this |
2085
+ | `authorizationServers` | at least one entry, each an issuer **verbatim** (no `?tenant_id=`), no query, no fragment, no duplicates |
2086
+ | `scopesSupported` | RFC 6749 `NQCHAR` tokens, order preserved, no duplicates; an empty list **omits the member** |
2087
+ | `bearerMethodsSupported` | exactly `["header"]` — this SDK's guard reads a bearer credential from the `Authorization` header alone |
2088
+ | `resourceDocumentation` | an absolute URL, query and fragment permitted; omitted when absent, never `null` |
2089
+
2090
+ **Nothing in the document may come from a request.** `resource` and `authorizationServers`
2091
+ are configuration, and this SDK offers no option to build either from the `Host` header, the
2092
+ `Forwarded`/`X-Forwarded-*` family or the request URL. A document assembled from the request
2093
+ is a document an attacker can point at an authorization server of their choosing — the whole
2094
+ handshake redirected with one header.
2095
+
2096
+ Nothing in §28 is wrapped in `Sensitive<T>`, and that is a rule rather than an omission: the
2097
+ document is published unauthenticated to the world and the challenge goes to a caller who has
2098
+ just failed to authenticate, so both must stay readable. The corollary is the one that
2099
+ matters — **no part of the presented credential reaches either of them**, in any parameter,
2100
+ any header, any body or any log line the guard writes on the 401 path.
2101
+
1708
2102
  ## Client quality-of-life (CONTRACT.md §16–§19)
1709
2103
 
1710
2104
  ### Retry policy (§16)
@@ -1956,6 +2350,53 @@ actions that would reconcile the tenant.
1956
2350
  which, execution stops rather than continuing blindly, and there is no `rollback` —
1957
2351
  because this SDK could not honour one.
1958
2352
 
2353
+ #### Metadata, resource-scoped bindings, and service accounts (§27.6.1, contract 1.51)
2354
+
2355
+ ```ts
2356
+ const desired = defineManifest({
2357
+ resources: [
2358
+ { key: 'site1', name: 'site-1', resourceType: 'site', metadata: { owner: 'ops' } },
2359
+ ],
2360
+ roles: [{ key: 'concierge', name: 'Concierge', description: 'Concierge' }],
2361
+ users: [
2362
+ {
2363
+ key: 'ann', username: 'ann', email: 'ann@example.com',
2364
+ initialPassword: new Sensitive(pw),
2365
+ // A role key is still plain — this keeps compiling and meaning what it
2366
+ // always meant. The scoped shape is a resource-scoped object instead.
2367
+ roles: [{ role: 'concierge', resource: 'site1', inherit: false }],
2368
+ },
2369
+ ],
2370
+ serviceAccounts: [
2371
+ { key: 'fleet', name: 'device-fleet', roles: ['concierge'] },
2372
+ ],
2373
+ });
2374
+
2375
+ const report = await client.manifest.apply(desired);
2376
+ const created = report.steps.find((s) => s.action.target === 'service-account')!;
2377
+ if (created.outcome.status === 'created' && created.outcome.serviceAccountSecret) {
2378
+ // The ONLY place this manifest ever surfaces a service account's secret —
2379
+ // apply() never rotates one to reconcile anything. Store it now.
2380
+ saveSecret(created.outcome.serviceAccountSecret.expose());
2381
+ }
2382
+ ```
2383
+
2384
+ - **`resources[].metadata`** drifts by JSON equality of the whole object, independent of
2385
+ key order, never a key-by-key merge; an unstated `metadata` is silent, and a stated
2386
+ `{}` matches what the server holds for none.
2387
+ - **A role binding takes either shape** — a plain key (as before 1.51) or
2388
+ `{ role, resource?, inherit? }`. `inherit` reaches the wire only as `false`. Changing a
2389
+ binding's resource or `inherit` is `unassign` then `assign` (there is no update
2390
+ endpoint); the server's existing `tenant_scope` carries across unchanged, and a failed
2391
+ re-assign restores the previous binding, reporting both outcomes as a `'rebind-failed'`
2392
+ step. One role bound twice to one subject — plain and scoped combined — is refused
2393
+ before any request; so is a global role bound here with `inherit: false`.
2394
+ - **`serviceAccounts`** reconciles by `name`, which the server does not enforce as unique —
2395
+ `plan()` fails client-side, before any write, if more than one existing account matches.
2396
+ Only `description` is reconciled by `Update`.
2397
+ - **Declines.** `webhooks` is not a manifest namespace in this SDK — the contract names it
2398
+ without specifying it, and no consumer has asked for it.
2399
+
1959
2400
  Codebases that already declare their domain with classes get decorators instead:
1960
2401
 
1961
2402
  ```ts
@@ -1974,6 +2415,8 @@ TypeScript has two decorator dialects and this SDK's own `tsconfig.json` deliber
1974
2415
  enables neither — so these are dual-protocol plain functions that work under both, and
1975
2416
  under neither: `AxiamResource(spec)(Documents)` is exactly what the `@` syntax desugars to.
1976
2417
 
2418
+ `@AxiamServiceAccount({ key, name, roles })` (contract 1.51) joins the set the same way.
2419
+
1977
2420
  ### Examples
1978
2421
 
1979
2422
  - [`examples/management-basics.ts`](examples/management-basics.ts) — the imperative surface