axiam-sdk 1.0.0-alpha → 1.0.0-alpha10

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 (46) hide show
  1. package/README.md +146 -4
  2. package/dist/authzCore-B7GSd3-t.d.cts +151 -0
  3. package/dist/authzCore-CcTdIf78.d.ts +151 -0
  4. package/dist/{client-B2SB-C7c.d.cts → client-Co_baHgU.d.ts} +75 -59
  5. package/dist/{client-B2SB-C7c.d.ts → client-CzhzwRGg.d.cts} +75 -59
  6. package/dist/grpc/index.d.cts +8 -3
  7. package/dist/grpc/index.d.ts +8 -3
  8. package/dist/grpc/index.js +183 -14
  9. package/dist/grpc/index.js.map +1 -1
  10. package/dist/grpc/index.mjs +183 -14
  11. package/dist/grpc/index.mjs.map +1 -1
  12. package/dist/index.d.cts +2 -1
  13. package/dist/index.d.ts +2 -1
  14. package/dist/index.js +133 -10
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +133 -10
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/{jwks-CX-nhD6A.d.cts → jwks-B8dPy2c6.d.cts} +7 -0
  19. package/dist/{jwks-CX-nhD6A.d.ts → jwks-B8dPy2c6.d.ts} +7 -0
  20. package/dist/middleware/index.d.cts +85 -53
  21. package/dist/middleware/index.d.ts +85 -53
  22. package/dist/middleware/index.js +221 -27
  23. package/dist/middleware/index.js.map +1 -1
  24. package/dist/middleware/index.mjs +210 -28
  25. package/dist/middleware/index.mjs.map +1 -1
  26. package/dist/nestjs/index.d.cts +100 -0
  27. package/dist/nestjs/index.d.ts +100 -0
  28. package/dist/nestjs/index.js +179 -0
  29. package/dist/nestjs/index.js.map +1 -0
  30. package/dist/nestjs/index.mjs +170 -0
  31. package/dist/nestjs/index.mjs.map +1 -0
  32. package/dist/node/index.d.cts +23 -3
  33. package/dist/node/index.d.ts +23 -3
  34. package/dist/node/index.js +166 -11
  35. package/dist/node/index.js.map +1 -1
  36. package/dist/node/index.mjs +166 -11
  37. package/dist/node/index.mjs.map +1 -1
  38. package/dist/rest/index.d.cts +2 -1
  39. package/dist/rest/index.d.ts +2 -1
  40. package/dist/rest/index.js +133 -10
  41. package/dist/rest/index.js.map +1 -1
  42. package/dist/rest/index.mjs +133 -10
  43. package/dist/rest/index.mjs.map +1 -1
  44. package/dist/types-BVkMoqLU.d.cts +59 -0
  45. package/dist/types-BVkMoqLU.d.ts +59 -0
  46. package/package.json +23 -1
package/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # axiam-sdk (TypeScript/JavaScript)
2
2
 
3
+ [![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
+ [![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)
6
+ [![Docs](https://img.shields.io/badge/docs-TypeDoc-blue.svg)](https://ilpanich.github.io/axiam-typescript-sdk/)
7
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
8
+
3
9
  Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanich/axiam) — Access eXtended Identity and Authorization Management.
4
10
 
5
11
  ## Package identity
@@ -11,7 +17,7 @@ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanic
11
17
 
12
18
  ## Contract conformance
13
19
 
14
- This SDK conforms to CONTRACT.md §1–§10.
20
+ This SDK conforms to CONTRACT.md §1–§11 (including §6.1 mTLS client certificates).
15
21
 
16
22
  See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contract.
17
23
 
@@ -33,7 +39,8 @@ never contains `@grpc/grpc-js` or `amqplib`):
33
39
  | `axiam-sdk` / `axiam-sdk/rest` | Browser + Node, REST-only | `AxiamClient`: `login`/`verifyMfa`/`refresh`/`logout`, `can`/`batchCheck` over the FND-04 REST authz endpoint |
34
40
  | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
35
41
  | `axiam-sdk/amqp` | Node only | `consume()` — HMAC-verified AMQP audit/authz event consumer (CONTRACT.md §8) |
36
- | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) |
42
+ | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) — plus `requireAuth`/`requireAccess`/`requireRole` declarative route guards (CONTRACT.md §11) |
43
+ | `axiam-sdk/nestjs` | Node only, optional | `@RequireAccess`/`@RequireAuth`/`@RequireRole` metadata decorators + `AxiamGuard` (CONTRACT.md §11, Tier 2) |
37
44
 
38
45
  **Browser code should only ever import from `axiam-sdk` or `axiam-sdk/rest`.** Importing
39
46
  `axiam-sdk/grpc`, `axiam-sdk/amqp`, or `axiam-sdk/middleware` pulls in Node-only
@@ -56,6 +63,34 @@ const client = new AxiamClient({
56
63
  });
57
64
  ```
58
65
 
66
+ ### mTLS / client certificates (Node only)
67
+
68
+ For IoT devices and service accounts authenticated by **mutual TLS** (CONTRACT.md §6.1),
69
+ pass a PEM client-certificate chain and its PEM private key. The identity is presented on
70
+ **both** the REST and gRPC transports of the same client. Presenting a client certificate
71
+ **never** relaxes server verification — strict TLS stays on.
72
+
73
+ ```typescript
74
+ import { readFileSync } from 'node:fs';
75
+ import { AxiamClient } from 'axiam-sdk';
76
+
77
+ const client = new AxiamClient({
78
+ baseUrl: 'https://iam.example.com',
79
+ tenantSlug: 'acme',
80
+ clientCert: readFileSync('device.crt', 'utf8'), // PEM certificate chain
81
+ clientKey: readFileSync('device.key', 'utf8'), // PEM private key (PKCS#8 or PKCS#1)
82
+ // customCa: readFileSync('ca.crt', 'utf8'), // optional server-trust CA (§6)
83
+ });
84
+ ```
85
+
86
+ - `clientCert` and `clientKey` are **all-or-nothing** — providing exactly one throws at
87
+ construction, and each is validated to be PEM-shaped (as `customCa` is).
88
+ - The private key is secret material: it is passed straight to the Node TLS stack and is
89
+ never retained on a public property, logged, or serialized (CONTRACT.md §7).
90
+ - **Node only.** Browsers cannot present a client certificate from JavaScript, so the
91
+ browser build validates the PEM shape then ignores `clientCert`/`clientKey` — exactly as
92
+ it already ignores `customCa`.
93
+
59
94
  ## Usage per persona
60
95
 
61
96
  ### Browser — login + authz (`axiam-sdk` / `axiam-sdk/rest`)
@@ -170,6 +205,111 @@ Both middleware integrations verify the session against a locally-cached JWKS (n
170
205
  identity into the request context, and surface `AuthError` as HTTP 401 / `AuthzError` as
171
206
  HTTP 403 with a standardized JSON error body (CONTRACT.md §10).
172
207
 
208
+ ### Declarative authorization helpers (`axiam-sdk/middleware`)
209
+
210
+ CONTRACT.md §11 adds a per-endpoint authorization layer on top of the §10 guard above:
211
+ `requireAuth`, `requireAccess`, `requireRole` (Express) and their `*Hook` counterparts
212
+ (Fastify). They never extract or verify a token themselves — they read the identity
213
+ `axiamMiddleware`/`axiamPlugin` already injected (401 if absent) — and `requireAccess`
214
+ additionally needs an authz-capable client on the session (`authzClient`, satisfied by
215
+ `AxiamClient.checkAccess`):
216
+
217
+ ```typescript
218
+ import { AxiamClient } from 'axiam-sdk/rest';
219
+ import { createNodeSession } from 'axiam-sdk/grpc';
220
+ import {
221
+ axiamMiddleware,
222
+ fromParam,
223
+ requireAccess,
224
+ requireRole,
225
+ type AuthzVerifiableSession,
226
+ } from 'axiam-sdk/middleware';
227
+
228
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
229
+ const authzSession: AuthzVerifiableSession = {
230
+ ...session,
231
+ // Adopts the SAME session, so the cookie jar/refresh guard is shared with axiamMiddleware.
232
+ authzClient: new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' }, session),
233
+ };
234
+
235
+ const app = express();
236
+ app.use(axiamMiddleware(session));
237
+
238
+ // action before resource (§1); resource is a literal, `fromParam('id')`, or a `(req) => string` resolver.
239
+ app.get('/documents/:id', requireAccess(authzSession, 'read', fromParam('id')), (req, res) => {
240
+ res.json({ documentId: req.params.id });
241
+ });
242
+
243
+ // Local-only (no server round-trip) role check — NOT a substitute for requireAccess.
244
+ app.get('/admin', requireRole(session, 'admin'), (_req, res) => res.json({ ok: true }));
245
+ ```
246
+
247
+ The Fastify equivalents are `requireAuthHook`/`requireAccessHook`/`requireRoleHook`, each
248
+ returning a plain `preHandler` function:
249
+
250
+ ```typescript
251
+ import { requireAccessHook, fromParam } from 'axiam-sdk/middleware';
252
+
253
+ app.get(
254
+ '/documents/:id',
255
+ { preHandler: requireAccessHook(authzSession, 'read', fromParam('id')) },
256
+ async (request) => ({ documentId: (request.params as { id: string }).id }),
257
+ );
258
+ ```
259
+
260
+ Error mapping (§11.2.5, same `{ error, message }` JSON shape as §10): 401
261
+ `authentication_failed` (no authenticated identity on the request), 403
262
+ `authorization_denied` (denied by policy), 400 `invalid_request` (the resource id
263
+ couldn't be resolved — never a silent allow), 503 `authz_unavailable` on any transport
264
+ failure while calling the authz endpoint (fail closed — a network error never allows).
265
+ The check is always made for the *authenticated request's* user (`subjectId =
266
+ axiamUser.userId`), never the SDK client's own service-account identity, and the decision
267
+ is never cached.
268
+
269
+ #### NestJS (`axiam-sdk/nestjs`, optional)
270
+
271
+ An optional Tier 2 on top of the same `middleware/authzCore.ts` primitives: metadata
272
+ decorators plus an `AxiamGuard` (`CanActivate`) that reads them via `Reflector`.
273
+ `@nestjs/common`/`@nestjs/core` are optional peer dependencies, like `express`/`fastify`
274
+ above. `AxiamGuard` never extracts or verifies a token itself — mount
275
+ `axiamMiddleware`/`axiamPlugin` on the underlying HTTP adapter (Nest runs on top of
276
+ Express or Fastify) so `request.axiamUser` is already set:
277
+
278
+ ```typescript
279
+ import { APP_GUARD, Reflector } from '@nestjs/core';
280
+ import { Controller, Get, Module, Param } from '@nestjs/common';
281
+ import { AXIAM_SESSION, AxiamGuard, RequireAccess, RequireRole } from 'axiam-sdk/nestjs';
282
+
283
+ @Controller('documents')
284
+ class DocumentsController {
285
+ @RequireAccess('read', { param: 'id' })
286
+ @Get(':id')
287
+ getDocument(@Param('id') id: string) {
288
+ return { documentId: id };
289
+ }
290
+
291
+ @RequireRole('admin')
292
+ @Get()
293
+ listDocuments() {
294
+ return { message: 'admin-only listing' };
295
+ }
296
+ }
297
+
298
+ @Module({
299
+ controllers: [DocumentsController],
300
+ providers: [
301
+ { provide: AXIAM_SESSION, useValue: authzSession },
302
+ // AxiamGuard is a plain class with no Nest decorators of its own (this SDK's
303
+ // tsconfig does not enable experimentalDecorators) — wire it via a factory provider.
304
+ { provide: APP_GUARD, useFactory: (r: Reflector) => new AxiamGuard(r, authzSession), inject: [Reflector] },
305
+ ],
306
+ })
307
+ class AppModule {}
308
+ ```
309
+
310
+ See `examples/nestjs-app.ts` for a complete, compiling example (including the
311
+ `axiamMiddleware` wiring `AxiamGuard` depends on).
312
+
173
313
  More runnable examples (all compiling under `tsc --noEmit -p examples/tsconfig.json`) live
174
314
  in `examples/` at the package root.
175
315
 
@@ -199,8 +339,10 @@ try {
199
339
  - Token-carrying values are wrapped in `Sensitive<T>` — `toString()`/`toJSON()`/
200
340
  `util.inspect` all redact to `[SENSITIVE]`; the raw value is only reachable via an
201
341
  explicit accessor (CONTRACT.md §7).
202
- - Strict TLS verification is always on; the only escape hatch is the constructor's
203
- `customCa` option for self-signed development environments (CONTRACT.md §6).
342
+ - Strict TLS verification is always on; the only server-trust escape hatch is the
343
+ constructor's `customCa` option for self-signed development environments (CONTRACT.md §6).
344
+ - Optional mutual TLS (mTLS): a PEM `clientCert`/`clientKey` client identity (Node only) is
345
+ presented on both REST and gRPC without ever relaxing server verification (CONTRACT.md §6.1).
204
346
  - AMQP messages are HMAC-SHA256 verified before your handler ever sees them; verification
205
347
  failures are nacked without requeue (CONTRACT.md §8).
206
348
 
@@ -0,0 +1,151 @@
1
+ import { A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.cjs';
2
+ import { V as Verifier } from './jwks-B8dPy2c6.cjs';
3
+
4
+ /**
5
+ * Minimal session shape the middleware needs: a JWKS verifier (D-11) and the
6
+ * tenant this resource server is configured for (CR-03). JWKS is org-wide,
7
+ * not tenant-scoped (node/jwks.ts) — `tenantHeaderValue` is what lets
8
+ * `authenticateRequest` reject a validly-signed token minted for a
9
+ * DIFFERENT tenant in the same org.
10
+ */
11
+ interface VerifiableSession {
12
+ /** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */
13
+ jwksVerifier: Verifier;
14
+ /** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */
15
+ tenantHeaderValue: string;
16
+ }
17
+ /** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */
18
+ interface AxiamIdentity {
19
+ /** The authenticated end user's id (the token's `sub` claim). */
20
+ userId: string;
21
+ /** The tenant the verified token was minted for (the token's `tenant_id` claim). */
22
+ tenantId: string;
23
+ /** Roles derived from the token's space-separated `scope` claim (§10). */
24
+ roles: string[];
25
+ }
26
+ /**
27
+ * Verify `token` locally against `session`'s cached JWKS and map the
28
+ * verified claims to the identity shape injected by both middleware
29
+ * modules. Roles are derived from the `scope` claim (space-separated) —
30
+ * AXIAM's access token carries no dedicated `roles` claim server-side
31
+ * (mirrors the Rust SDK's src/middleware/actix.rs).
32
+ *
33
+ * Throws `AuthError` on any verification failure (missing/invalid/expired
34
+ * token, or a malformed sub/tenant_id claim).
35
+ */
36
+ declare function authenticateRequest(session: VerifiableSession, token: string): Promise<AxiamIdentity>;
37
+
38
+ /**
39
+ * The minimal shape `requireAccess`/`requireAccessHook` need from an authz
40
+ * transport — satisfied structurally by `AxiamClient` (`checkAccess`
41
+ * already accepts `subjectId`, §1/FND-04) without importing the class
42
+ * itself, so this module pulls in no axios/grpc dependency.
43
+ */
44
+ interface AuthzChecker {
45
+ /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */
46
+ checkAccess(check: AccessCheck): Promise<AccessDecision>;
47
+ }
48
+ /**
49
+ * `VerifiableSession` extended with an optional authz-capable client
50
+ * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base
51
+ * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally
52
+ * require `authzClient` to be set — enforced by {@link assertAuthzClient},
53
+ * which throws synchronously at guard-construction time (route-setup time),
54
+ * not per-request, when it is absent.
55
+ */
56
+ interface AuthzVerifiableSession extends VerifiableSession {
57
+ /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */
58
+ authzClient?: AuthzChecker;
59
+ }
60
+ /** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */
61
+ interface ResourceParamRef {
62
+ /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */
63
+ readonly kind: 'param';
64
+ /** The path/route parameter name the resource id is read from. */
65
+ readonly name: string;
66
+ }
67
+ /**
68
+ * `resource_param` precedence option (§11.2.3.b): resolve the resource id
69
+ * from the named path/route parameter (`req.params[name]` /
70
+ * `request.params[name]`) at request time.
71
+ */
72
+ declare function fromParam(name: string): ResourceParamRef;
73
+ /** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */
74
+ type ResourceResolver<TReq> = (req: TReq) => string;
75
+ /**
76
+ * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:
77
+ * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}
78
+ * (§11.2.3.b), or a resolver callback (§11.2.3.c).
79
+ */
80
+ type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;
81
+ /** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */
82
+ declare class ResourceResolutionError extends Error {
83
+ constructor(message: string);
84
+ }
85
+ /**
86
+ * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).
87
+ * `getParams` abstracts over Express's `req.params` and Fastify's
88
+ * `request.params`, both `Record<string, string | undefined>`-shaped at
89
+ * runtime. A missing/empty resolution — a missing path parameter, or a
90
+ * resolver returning an empty string — is a **programming error** raised as
91
+ * {@link ResourceResolutionError}; it is never a silent allow and never a
92
+ * nil/empty-id fallback (§11.2.3).
93
+ */
94
+ declare function resolveResourceId<TReq>(req: TReq, spec: ResourceSpec<TReq>, getParams: (req: TReq) => Record<string, string | undefined> | undefined): string;
95
+ /** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */
96
+ interface RequireAccessOptions {
97
+ /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */
98
+ scope?: string;
99
+ /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */
100
+ logger?: AuthzLogger;
101
+ }
102
+ /** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */
103
+ interface AuthzLogger {
104
+ /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */
105
+ debug(event: string, message: string, context?: Record<string, unknown>): void;
106
+ }
107
+ /**
108
+ * Validate that `session.authzClient` is configured, returning it. Throws
109
+ * synchronously (guard-construction time, i.e. route-setup time — not
110
+ * per-request) when absent, per the task's "helpers throw at construction
111
+ * if absent" requirement.
112
+ */
113
+ declare function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker;
114
+ /** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */
115
+ interface ErrorBody {
116
+ /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */
117
+ error: string;
118
+ /** Human-readable explanation; never contains token material. */
119
+ message: string;
120
+ }
121
+ /** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */
122
+ type CheckOutcome = {
123
+ /** The check passed — the caller proceeds to the handler. */
124
+ kind: 'allowed';
125
+ } | {
126
+ /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */
127
+ kind: 'denied';
128
+ /** Denial message surfaced in the 403 body. */
129
+ message: string;
130
+ } | {
131
+ /** The authz transport failed — fail-closed → HTTP 503, never an allow. */
132
+ kind: 'unavailable';
133
+ /** Failure message surfaced in the 503 body. */
134
+ message: string;
135
+ };
136
+ /**
137
+ * Call `checker.checkAccess` with `subjectId` set to the *authenticated
138
+ * request's* user id (§11.2.2 — never the app's own service-account
139
+ * identity) and map the outcome per §11.2.5:
140
+ * - `allowed: false` → `denied`
141
+ * - `AuthzError` (server 403/409) → `denied`
142
+ * - `NetworkError`, or any other unexpected failure → `unavailable`
143
+ * (fail-closed: a transport failure is never treated as an allow).
144
+ *
145
+ * Never caches the decision (§11.2.6) — a plain per-call `await`.
146
+ */
147
+ declare function evaluateAccess(checker: AuthzChecker, action: string, resourceId: string, subjectId: string, scope?: string): Promise<CheckOutcome>;
148
+ /** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */
149
+ declare function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean;
150
+
151
+ export { type AxiamIdentity as A, type CheckOutcome as C, type ErrorBody as E, type ResourceSpec as R, type VerifiableSession as V, type AuthzVerifiableSession as a, type RequireAccessOptions as b, type AuthzChecker as c, type AuthzLogger as d, type ResourceParamRef as e, ResourceResolutionError as f, type ResourceResolver as g, assertAuthzClient as h, authenticateRequest as i, evaluateAccess as j, fromParam as k, hasAnyRole as l, resolveResourceId as r };
@@ -0,0 +1,151 @@
1
+ import { A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.js';
2
+ import { V as Verifier } from './jwks-B8dPy2c6.js';
3
+
4
+ /**
5
+ * Minimal session shape the middleware needs: a JWKS verifier (D-11) and the
6
+ * tenant this resource server is configured for (CR-03). JWKS is org-wide,
7
+ * not tenant-scoped (node/jwks.ts) — `tenantHeaderValue` is what lets
8
+ * `authenticateRequest` reject a validly-signed token minted for a
9
+ * DIFFERENT tenant in the same org.
10
+ */
11
+ interface VerifiableSession {
12
+ /** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */
13
+ jwksVerifier: Verifier;
14
+ /** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */
15
+ tenantHeaderValue: string;
16
+ }
17
+ /** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */
18
+ interface AxiamIdentity {
19
+ /** The authenticated end user's id (the token's `sub` claim). */
20
+ userId: string;
21
+ /** The tenant the verified token was minted for (the token's `tenant_id` claim). */
22
+ tenantId: string;
23
+ /** Roles derived from the token's space-separated `scope` claim (§10). */
24
+ roles: string[];
25
+ }
26
+ /**
27
+ * Verify `token` locally against `session`'s cached JWKS and map the
28
+ * verified claims to the identity shape injected by both middleware
29
+ * modules. Roles are derived from the `scope` claim (space-separated) —
30
+ * AXIAM's access token carries no dedicated `roles` claim server-side
31
+ * (mirrors the Rust SDK's src/middleware/actix.rs).
32
+ *
33
+ * Throws `AuthError` on any verification failure (missing/invalid/expired
34
+ * token, or a malformed sub/tenant_id claim).
35
+ */
36
+ declare function authenticateRequest(session: VerifiableSession, token: string): Promise<AxiamIdentity>;
37
+
38
+ /**
39
+ * The minimal shape `requireAccess`/`requireAccessHook` need from an authz
40
+ * transport — satisfied structurally by `AxiamClient` (`checkAccess`
41
+ * already accepts `subjectId`, §1/FND-04) without importing the class
42
+ * itself, so this module pulls in no axios/grpc dependency.
43
+ */
44
+ interface AuthzChecker {
45
+ /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */
46
+ checkAccess(check: AccessCheck): Promise<AccessDecision>;
47
+ }
48
+ /**
49
+ * `VerifiableSession` extended with an optional authz-capable client
50
+ * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base
51
+ * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally
52
+ * require `authzClient` to be set — enforced by {@link assertAuthzClient},
53
+ * which throws synchronously at guard-construction time (route-setup time),
54
+ * not per-request, when it is absent.
55
+ */
56
+ interface AuthzVerifiableSession extends VerifiableSession {
57
+ /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */
58
+ authzClient?: AuthzChecker;
59
+ }
60
+ /** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */
61
+ interface ResourceParamRef {
62
+ /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */
63
+ readonly kind: 'param';
64
+ /** The path/route parameter name the resource id is read from. */
65
+ readonly name: string;
66
+ }
67
+ /**
68
+ * `resource_param` precedence option (§11.2.3.b): resolve the resource id
69
+ * from the named path/route parameter (`req.params[name]` /
70
+ * `request.params[name]`) at request time.
71
+ */
72
+ declare function fromParam(name: string): ResourceParamRef;
73
+ /** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */
74
+ type ResourceResolver<TReq> = (req: TReq) => string;
75
+ /**
76
+ * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:
77
+ * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}
78
+ * (§11.2.3.b), or a resolver callback (§11.2.3.c).
79
+ */
80
+ type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;
81
+ /** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */
82
+ declare class ResourceResolutionError extends Error {
83
+ constructor(message: string);
84
+ }
85
+ /**
86
+ * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).
87
+ * `getParams` abstracts over Express's `req.params` and Fastify's
88
+ * `request.params`, both `Record<string, string | undefined>`-shaped at
89
+ * runtime. A missing/empty resolution — a missing path parameter, or a
90
+ * resolver returning an empty string — is a **programming error** raised as
91
+ * {@link ResourceResolutionError}; it is never a silent allow and never a
92
+ * nil/empty-id fallback (§11.2.3).
93
+ */
94
+ declare function resolveResourceId<TReq>(req: TReq, spec: ResourceSpec<TReq>, getParams: (req: TReq) => Record<string, string | undefined> | undefined): string;
95
+ /** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */
96
+ interface RequireAccessOptions {
97
+ /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */
98
+ scope?: string;
99
+ /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */
100
+ logger?: AuthzLogger;
101
+ }
102
+ /** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */
103
+ interface AuthzLogger {
104
+ /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */
105
+ debug(event: string, message: string, context?: Record<string, unknown>): void;
106
+ }
107
+ /**
108
+ * Validate that `session.authzClient` is configured, returning it. Throws
109
+ * synchronously (guard-construction time, i.e. route-setup time — not
110
+ * per-request) when absent, per the task's "helpers throw at construction
111
+ * if absent" requirement.
112
+ */
113
+ declare function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker;
114
+ /** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */
115
+ interface ErrorBody {
116
+ /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */
117
+ error: string;
118
+ /** Human-readable explanation; never contains token material. */
119
+ message: string;
120
+ }
121
+ /** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */
122
+ type CheckOutcome = {
123
+ /** The check passed — the caller proceeds to the handler. */
124
+ kind: 'allowed';
125
+ } | {
126
+ /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */
127
+ kind: 'denied';
128
+ /** Denial message surfaced in the 403 body. */
129
+ message: string;
130
+ } | {
131
+ /** The authz transport failed — fail-closed → HTTP 503, never an allow. */
132
+ kind: 'unavailable';
133
+ /** Failure message surfaced in the 503 body. */
134
+ message: string;
135
+ };
136
+ /**
137
+ * Call `checker.checkAccess` with `subjectId` set to the *authenticated
138
+ * request's* user id (§11.2.2 — never the app's own service-account
139
+ * identity) and map the outcome per §11.2.5:
140
+ * - `allowed: false` → `denied`
141
+ * - `AuthzError` (server 403/409) → `denied`
142
+ * - `NetworkError`, or any other unexpected failure → `unavailable`
143
+ * (fail-closed: a transport failure is never treated as an allow).
144
+ *
145
+ * Never caches the decision (§11.2.6) — a plain per-call `await`.
146
+ */
147
+ declare function evaluateAccess(checker: AuthzChecker, action: string, resourceId: string, subjectId: string, scope?: string): Promise<CheckOutcome>;
148
+ /** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */
149
+ declare function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean;
150
+
151
+ export { type AxiamIdentity as A, type CheckOutcome as C, type ErrorBody as E, type ResourceSpec as R, type VerifiableSession as V, type AuthzVerifiableSession as a, type RequireAccessOptions as b, type AuthzChecker as c, type AuthzLogger as d, type ResourceParamRef as e, ResourceResolutionError as f, type ResourceResolver as g, assertAuthzClient as h, authenticateRequest as i, evaluateAccess as j, fromParam as k, hasAnyRole as l, resolveResourceId as r };
@@ -1,3 +1,4 @@
1
+ import { L as LoginResult, A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.js';
1
2
  import { AxiosInstance } from 'axios';
2
3
 
3
4
  /** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */
@@ -20,27 +21,48 @@ interface AxiamClientOptions {
20
21
  tenantSlug?: string;
21
22
  /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */
22
23
  tenantId?: string;
24
+ /**
25
+ * Human-readable organization identifier (CONTRACT.md §5). Optional at
26
+ * construction, but the server REQUIRES an org context on login — a tenant
27
+ * slug is only unique *within* an organization — so a client that omits both
28
+ * `orgSlug` and `orgId` will fail login with a 400/401. Forwarded as
29
+ * `org_slug` in the login body. Mutually exclusive with {@link orgId}
30
+ * (if both are given, `orgId` wins, mirroring how `tenantSlug`/`tenantId`
31
+ * resolve).
32
+ */
33
+ orgSlug?: string;
34
+ /**
35
+ * Organization UUID (CONTRACT.md §5). Optional at construction (see
36
+ * {@link orgSlug}). When supplied it is forwarded as `org_id` on login and
37
+ * used to build the `refresh` body; otherwise the resolved organization UUID
38
+ * is decoded from the authenticated session's access-token `org_id` claim
39
+ * after the first successful login. Mutually exclusive with {@link orgSlug}.
40
+ */
41
+ orgId?: string;
23
42
  /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */
24
43
  customCa?: string;
44
+ /**
45
+ * PEM-encoded client-certificate chain for mutual TLS (§6.1). Presented to
46
+ * the server to authenticate an IoT device / service account. MUST be
47
+ * provided together with {@link AxiamClientOptions.clientKey}. Node only —
48
+ * ignored in the browser (browsers cannot present a client certificate from
49
+ * JS). Presenting a client certificate NEVER relaxes server verification.
50
+ */
51
+ clientCert?: string;
52
+ /**
53
+ * PEM-encoded private key (PKCS#8 or PKCS#1) matching {@link
54
+ * AxiamClientOptions.clientCert} (§6.1). Secret material: it is passed
55
+ * straight to the Node TLS stack and is never retained on a public property,
56
+ * logged, or serialized (§7). MUST be provided together with `clientCert`.
57
+ * Node only — ignored in the browser.
58
+ */
59
+ clientKey?: string;
25
60
  /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */
26
61
  connectTimeoutMs?: number;
27
62
  /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */
28
63
  requestTimeoutMs?: number;
29
64
  }
30
65
 
31
- /**
32
- * The outcome of an access check, shared by the REST (`AxiamClient.checkAccess`
33
- * / `.batchCheck`) and gRPC (`AuthzGrpcClient.checkAccess` / `.batchCheck`)
34
- * transports (CONTRACT.md §1). `reason` is present (and non-empty) only when
35
- * `allowed` is `false`.
36
- */
37
- interface AccessDecision {
38
- /** Whether the checked action on the checked resource is permitted. */
39
- allowed: boolean;
40
- /** Present (and non-empty) only when `allowed` is `false`; a human-readable reason the check was denied. */
41
- reason?: string;
42
- }
43
-
44
66
  /**
45
67
  * The single session object every AXIAM transport (REST here, gRPC/AMQP in
46
68
  * 17-03/17-04, middleware in 17-05) attaches to. Constructed once per
@@ -53,6 +75,28 @@ declare class SharedSession {
53
75
  readonly baseUrl: string;
54
76
  /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
55
77
  readonly tenantHeaderValue: string;
78
+ /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */
79
+ readonly tenantId: string | undefined;
80
+ /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */
81
+ readonly tenantSlug: string | undefined;
82
+ /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */
83
+ readonly orgId: string | undefined;
84
+ /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */
85
+ readonly orgSlug: string | undefined;
86
+ /**
87
+ * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`
88
+ * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config
89
+ * when the UUID was supplied, then updated from the access-token `tenant_id`
90
+ * claim after each successful login/refresh (Node persona only — the browser
91
+ * cannot read the httpOnly access-token cookie).
92
+ */
93
+ resolvedTenantId: string | undefined;
94
+ /**
95
+ * Resolved organization UUID used to build the `refresh` body. Seeded from
96
+ * `orgId` config, then updated from the access-token `org_id` claim after a
97
+ * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.
98
+ */
99
+ resolvedOrgId: string | undefined;
56
100
  /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
57
101
  csrfToken: string | undefined;
58
102
  /** Set true once a successful login/verifyMfa has completed. */
@@ -69,6 +113,23 @@ declare class SharedSession {
69
113
  */
70
114
  readonly refreshGuard: RefreshGuard;
71
115
  constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string);
116
+ /**
117
+ * Build the `POST /api/v1/auth/refresh` request body (§1). The server's
118
+ * `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this
119
+ * emits the resolved UUIDs — from the access-token claims after login, or
120
+ * from UUID-form construction options as a fallback. Fields that could not
121
+ * be resolved are omitted (the server then answers with a clear 400), rather
122
+ * than sending a slug where a UUID is required.
123
+ */
124
+ buildRefreshBody(): Record<string, string>;
125
+ /**
126
+ * Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the
127
+ * configured tenant and organization identifiers (UUID or slug form) in
128
+ * addition to the credentials — the server resolves the workspace from the
129
+ * body, not the `X-Tenant-ID` header, and rejects a login that omits org
130
+ * context. Undefined identifiers are omitted.
131
+ */
132
+ buildLoginBody(email: string, password: string): Record<string, string>;
72
133
  /**
73
134
  * Optional session-level hook invoked by rest/auth.ts after a successful
74
135
  * login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser
@@ -91,51 +152,6 @@ declare class SharedSession {
91
152
  isForeignHost(url: string | undefined): boolean;
92
153
  }
93
154
 
94
- /** The authenticated user's identity, as returned by `login()`/`verifyMfa()` on success. */
95
- interface AxiamUserInfo {
96
- /** The user's unique identifier (UUID). */
97
- id: string;
98
- /** The user's login username. */
99
- username: string;
100
- /** The user's email address. */
101
- email: string;
102
- }
103
- /**
104
- * The outcome of AxiamClient.login()/verifyMfa() (D-18).
105
- *
106
- * No raw session-token field exists here or anywhere else in the public
107
- * REST API surface — AXIAM delivers tokens exclusively via `Set-Cookie`
108
- * (T-17-07).
109
- */
110
- type LoginResult = {
111
- /** Discriminant: MFA is required to complete the login. */
112
- status: 'mfa_required';
113
- /** Opaque challenge token to pass to `verifyMfa(mfaToken, code)`. */
114
- mfaToken: string;
115
- /** The MFA methods the user has enrolled and may complete the challenge with. */
116
- availableMethods: string[];
117
- } | {
118
- /** Discriminant: login completed and a session was established. */
119
- status: 'authenticated';
120
- /** The authenticated user's identity. */
121
- user: AxiamUserInfo;
122
- /** Opaque session identifier for this authenticated session. */
123
- sessionId: string;
124
- /** Access token lifetime in seconds from the time of this response. */
125
- expiresIn: number;
126
- };
127
- /** A single access check request, as passed to `checkAccess()`/`can()`/`batchCheck()`. */
128
- interface AccessCheck {
129
- /** The action being performed (e.g. `"read"`, `"write"`, `"delete"`). */
130
- action: string;
131
- /** The identifier of the resource the action targets. */
132
- resourceId: string;
133
- /** Optional sub-resource scope for finer-grained checks. */
134
- scope?: string;
135
- /** Optional subject (user/service account) identifier to check on behalf of; defaults to the caller's own identity when omitted. */
136
- subjectId?: string;
137
- }
138
-
139
155
  /**
140
156
  * The main entry point for the AXIAM TypeScript/JavaScript SDK — an
141
157
  * isomorphic (browser + Node) REST client for authentication and
@@ -204,4 +220,4 @@ declare class AxiamClient {
204
220
  batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]>;
205
221
  }
206
222
 
207
- export { type AccessDecision as A, type LoginResult as L, SharedSession as S, type AxiamClientOptions as a, AxiamClient as b, type AccessCheck as c, type AxiamUserInfo as d };
223
+ export { type AxiamClientOptions as A, SharedSession as S, AxiamClient as a };