axiam-sdk 1.0.0-beta16 → 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 (50) hide show
  1. package/README.md +230 -7
  2. package/dist/amqp/index.js.map +1 -1
  3. package/dist/amqp/index.mjs.map +1 -1
  4. package/dist/{authzCore-DJmDAAtw.d.cts → authzCore-BpXRhTLF.d.cts} +33 -6
  5. package/dist/{authzCore-0fObXIqB.d.ts → authzCore-BxCr9i1y.d.ts} +33 -6
  6. package/dist/browser/index.d.cts +2 -2
  7. package/dist/browser/index.d.ts +2 -2
  8. package/dist/{client-BstRBtp8.d.ts → client-CX7MwFct.d.ts} +425 -132
  9. package/dist/{client-Dd_XaOtg.d.cts → client-D3BOv0PD.d.cts} +425 -132
  10. package/dist/{cookieJar-D0FxzBQG.d.ts → cookieJar-B4bMYc7_.d.ts} +3 -3
  11. package/dist/{cookieJar-Dvb1Gnwm.d.cts → cookieJar-Uh-6shG1.d.cts} +3 -3
  12. package/dist/grpc/index.d.cts +218 -11
  13. package/dist/grpc/index.d.ts +218 -11
  14. package/dist/grpc/index.js +1055 -206
  15. package/dist/grpc/index.js.map +1 -1
  16. package/dist/grpc/index.mjs +1054 -207
  17. package/dist/grpc/index.mjs.map +1 -1
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +878 -189
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +872 -190
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/{jwks-CSXHo3DS.d.cts → jwks-DmERws3k.d.cts} +36 -13
  25. package/dist/{jwks-CSXHo3DS.d.ts → jwks-DmERws3k.d.ts} +36 -13
  26. package/dist/middleware/index.d.cts +46 -7
  27. package/dist/middleware/index.d.ts +46 -7
  28. package/dist/middleware/index.js +58 -10
  29. package/dist/middleware/index.js.map +1 -1
  30. package/dist/middleware/index.mjs +58 -11
  31. package/dist/middleware/index.mjs.map +1 -1
  32. package/dist/nestjs/index.d.cts +2 -2
  33. package/dist/nestjs/index.d.ts +2 -2
  34. package/dist/node/index.d.cts +5 -5
  35. package/dist/node/index.d.ts +5 -5
  36. package/dist/node/index.js +883 -192
  37. package/dist/node/index.js.map +1 -1
  38. package/dist/node/index.mjs +883 -192
  39. package/dist/node/index.mjs.map +1 -1
  40. package/dist/{oidcState-CffZ6PkC.d.ts → oidcState-D9o_JxmM.d.ts} +2 -2
  41. package/dist/{oidcState-CSi4DY8h.d.cts → oidcState-E8Z5dXgQ.d.cts} +2 -2
  42. package/dist/rest/index.d.cts +6 -4
  43. package/dist/rest/index.d.ts +6 -4
  44. package/dist/rest/index.js +878 -189
  45. package/dist/rest/index.js.map +1 -1
  46. package/dist/rest/index.mjs +872 -190
  47. package/dist/rest/index.mjs.map +1 -1
  48. package/dist/{session-oiuBA1ZA.d.cts → session-Bsn9t50R.d.cts} +216 -2
  49. package/dist/{session-ymrHvMuJ.d.ts → session-BuqKS5nx.d.ts} +216 -2
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -25,19 +25,35 @@ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanic
25
25
 
26
26
  ## Contract conformance
27
27
 
28
- This SDK conforms to **contract 1.50**: CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19,
28
+ This SDK conforms to **contract 1.52**: CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19,
29
29
  §20, §21, §22, §23, §24, §25, §26, §27, §28 (including §6.1 mTLS client certificates, the
30
30
  §10.1 minimum local-verification set, the §12 OIDC/SSO relying-party helpers, and the §13
31
31
  `verifyWebhook` signature verifier). §12 is implemented in full at its 1.38 shape: all
32
32
  **thirteen** operations, including the four public "Sign in with X" entry points.
33
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
+
34
50
  **§12's operations live on `OidcClient`, not on `AxiamClient`** — the separate host §12.2
35
51
  permits where a packaging constraint requires one, which here is CI's proof that a `/rest`
36
52
  browser bundle pulls in no Node-only code. §12.2 forbids splitting them across two hosts, so
37
53
  the four operations contract 1.38 adds are on `OidcClient` too, with the nine that preceded
38
54
  them, even though three of them need no Node-only code at all.
39
55
 
40
- §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*
41
57
  the §27.6 declarative manifest with its §27.7 `defineManifest` and decorator forms. The
42
58
  contract asks an SDK that ships only one half to say which; this one ships both.
43
59
 
@@ -46,10 +62,10 @@ Express middleware and the Fastify plugin — with all three operations, the
46
62
  `resourceMetadataUrl` guard option and §28.9's five required tests. This SDK is §28.10's
47
63
  reference implementation: it lands first and the ten ports are read against it.
48
64
 
49
- §12.7, §14, §15, §22, §24, §25, §26, §27 and §28 are named rather than folded into the
50
- range because they landed after this SDK already claimed §1–§13: widening the range
51
- silently would turn a statement that was true when written into a different claim without
52
- anyone editing it.
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.
53
69
 
54
70
  ### §10.1 minimum local-verification set
55
71
 
@@ -59,7 +75,32 @@ rule on every inbound token: EdDSA `alg` pinned before the JWKS is consulted, a
59
75
  `exp` (`jose` only checks `exp` *if present*, so `requiredClaims: ['exp']` is passed
60
76
  explicitly), `nbf` honoured when present, `tenant_id` asserted against the session's
61
77
  configured tenant, `iss`/`aud` checked when configured, all under a named 60-second
62
- `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.
63
104
 
64
105
  Because the `/oauth2/jwks` trust anchor is **organization-wide**, the session guarding a
65
106
  resource server must be configured with the tenant **UUID** (`tenantId`), since that is
@@ -195,6 +236,54 @@ const client = new AxiamClient({
195
236
  browser build validates the PEM shape then ignores `clientCert`/`clientKey` — exactly as
196
237
  it already ignores `customCa`.
197
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
+
198
287
  #### RFC 8705 §5 `mtls_endpoint_aliases` (contract 1.40, CONTRACT.md §21.3 rule 2)
199
288
 
200
289
  A TLS listener decides whether to ask for a client certificate during the handshake,
@@ -372,6 +461,42 @@ Calling `getUserInfo()` with no token present raises `AuthError` client-side, wi
372
461
  call (CONTRACT.md §1.1). A `UNAUTHENTICATED` response drives exactly one refresh + one retry,
373
462
  identical to `checkAccess`.
374
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
+
375
500
  ### Node — AMQP consumer (`axiam-sdk/amqp`)
376
501
 
377
502
  ```typescript
@@ -1340,6 +1465,55 @@ produces a `403` — so a UI that offers the switch to everyone has turned a
1340
1465
  distinction the server made into a failure the user discovers. `false` against a
1341
1466
  server older than contract 1.31, which is the safe reading of absent.
1342
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
+
1343
1517
  #### Signing one in (§5.2.1)
1344
1518
 
1345
1519
  The reserved tenant has a fixed slug, `organization`, the same in every
@@ -2176,6 +2350,53 @@ actions that would reconcile the tenant.
2176
2350
  which, execution stops rather than continuing blindly, and there is no `rollback` —
2177
2351
  because this SDK could not honour one.
2178
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
+
2179
2400
  Codebases that already declare their domain with classes get decorators instead:
2180
2401
 
2181
2402
  ```ts
@@ -2194,6 +2415,8 @@ TypeScript has two decorator dialects and this SDK's own `tsconfig.json` deliber
2194
2415
  enables neither — so these are dual-protocol plain functions that work under both, and
2195
2416
  under neither: `AxiamResource(spec)(Documents)` is exactly what the `@` syntax desugars to.
2196
2417
 
2418
+ `@AxiamServiceAccount({ key, name, roles })` (contract 1.51) joins the set the same way.
2419
+
2197
2420
  ### Examples
2198
2421
 
2199
2422
  - [`examples/management-basics.ts`](examples/management-basics.ts) — the imperative surface