axiam-sdk 1.0.0-alpha2 → 1.0.0-alpha21

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 (64) hide show
  1. package/README.md +219 -8
  2. package/dist/amqp/index.d.cts +1 -1
  3. package/dist/amqp/index.d.ts +1 -1
  4. package/dist/amqp/index.js +4 -0
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +4 -0
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-xwmCivHH.d.ts → authzCore-DtSN59if.d.ts} +19 -2
  9. package/dist/{authzCore-CV-Td-V1.d.cts → authzCore-DuRI1aJf.d.cts} +19 -2
  10. package/dist/client-B_FqmZ0i.d.cts +72 -0
  11. package/dist/client-Dn1fs5MH.d.ts +72 -0
  12. package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
  13. package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
  14. package/dist/grpc/index.d.cts +113 -6
  15. package/dist/grpc/index.d.ts +113 -6
  16. package/dist/grpc/index.js +435 -18
  17. package/dist/grpc/index.js.map +1 -1
  18. package/dist/grpc/index.mjs +434 -19
  19. package/dist/grpc/index.mjs.map +1 -1
  20. package/dist/index.d.cts +4 -2
  21. package/dist/index.d.ts +4 -2
  22. package/dist/index.js +209 -13
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +204 -14
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/jwks-BgojMGC5.d.cts +152 -0
  27. package/dist/jwks-BgojMGC5.d.ts +152 -0
  28. package/dist/middleware/index.d.cts +208 -8
  29. package/dist/middleware/index.d.ts +208 -8
  30. package/dist/middleware/index.js +1107 -1
  31. package/dist/middleware/index.js.map +1 -1
  32. package/dist/middleware/index.mjs +1100 -3
  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 +3 -0
  37. package/dist/nestjs/index.js.map +1 -1
  38. package/dist/nestjs/index.mjs +3 -0
  39. package/dist/nestjs/index.mjs.map +1 -1
  40. package/dist/node/index.d.cts +50 -94
  41. package/dist/node/index.d.ts +50 -94
  42. package/dist/node/index.js +1039 -15
  43. package/dist/node/index.js.map +1 -1
  44. package/dist/node/index.mjs +1023 -16
  45. package/dist/node/index.mjs.map +1 -1
  46. package/dist/oidcState-BGxqWUun.d.cts +598 -0
  47. package/dist/oidcState-CkFuCjpM.d.ts +598 -0
  48. package/dist/rest/index.d.cts +107 -5
  49. package/dist/rest/index.d.ts +107 -5
  50. package/dist/rest/index.js +209 -13
  51. package/dist/rest/index.js.map +1 -1
  52. package/dist/rest/index.mjs +204 -14
  53. package/dist/rest/index.mjs.map +1 -1
  54. package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
  55. package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
  56. package/dist/session-BWUWhhyB.d.cts +154 -0
  57. package/dist/session-BWUWhhyB.d.ts +154 -0
  58. package/package.json +2 -2
  59. package/dist/client-BPg9kfKV.d.ts +0 -150
  60. package/dist/client-CAeQw1a-.d.cts +0 -150
  61. package/dist/jwks-CX-nhD6A.d.cts +0 -29
  62. package/dist/jwks-CX-nhD6A.d.ts +0 -29
  63. package/dist/sensitive-CWBH_tHr.d.cts +0 -12
  64. package/dist/sensitive-CWBH_tHr.d.ts +0 -12
package/README.md CHANGED
@@ -17,7 +17,8 @@ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanic
17
17
 
18
18
  ## Contract conformance
19
19
 
20
- This SDK conforms to CONTRACT.md §1–§11.
20
+ This SDK conforms to CONTRACT.md §1–§12 (including §6.1 mTLS client certificates and the §12
21
+ OIDC/SSO relying-party helpers).
21
22
 
22
23
  See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contract.
23
24
 
@@ -37,9 +38,10 @@ never contains `@grpc/grpc-js` or `amqplib`):
37
38
  | Entry point | Persona | Contents |
38
39
  |-------------------------|-----------------------------|---------------------------------------------------------------------------|
39
40
  | `axiam-sdk` / `axiam-sdk/rest` | Browser + Node, REST-only | `AxiamClient`: `login`/`verifyMfa`/`refresh`/`logout`, `can`/`batchCheck` over the FND-04 REST authz endpoint |
40
- | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
41
+ | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` and `UserInfoGrpcClient.getUserInfo` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
41
42
  | `axiam-sdk/amqp` | Node only | `consume()` — HMAC-verified AMQP audit/authz event consumer (CONTRACT.md §8) |
42
- | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) — plus `requireAuth`/`requireAccess`/`requireRole` declarative route guards (CONTRACT.md §11) |
43
+ | `axiam-sdk/node` | Node only | The Node persona (`createNodeSession`/`createNodeClient`, cookie jar + local-JWKS verifier) plus the **OIDC/SSO relying-party helpers** — `OidcClient`, `MemoryOidcStateStore`, PKCE primitives (CONTRACT.md §12) |
44
+ | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) — plus `requireAuth`/`requireAccess`/`requireRole` declarative route guards (CONTRACT.md §11) and the `oidcLoginHandlers`/`oidcLoginPlugin` "Login with AXIAM" routes (CONTRACT.md §12) |
43
45
  | `axiam-sdk/nestjs` | Node only, optional | `@RequireAccess`/`@RequireAuth`/`@RequireRole` metadata decorators + `AxiamGuard` (CONTRACT.md §11, Tier 2) |
44
46
 
45
47
  **Browser code should only ever import from `axiam-sdk` or `axiam-sdk/rest`.** Importing
@@ -58,11 +60,43 @@ import { AxiamClient } from 'axiam-sdk';
58
60
  const client = new AxiamClient({
59
61
  baseUrl: 'https://iam.example.com',
60
62
  tenantSlug: 'acme',
63
+ // Organization context is required for login/refresh — a tenant slug is only
64
+ // unique within an organization (CONTRACT.md §5.1). Pass orgSlug (or orgId).
65
+ orgSlug: 'acme',
61
66
  // customCa is optional — PEM-encoded CA cert for self-signed dev environments (§6)
62
67
  // customCa: pemString,
63
68
  });
64
69
  ```
65
70
 
71
+ ### mTLS / client certificates (Node only)
72
+
73
+ For IoT devices and service accounts authenticated by **mutual TLS** (CONTRACT.md §6.1),
74
+ pass a PEM client-certificate chain and its PEM private key. The identity is presented on
75
+ **both** the REST and gRPC transports of the same client. Presenting a client certificate
76
+ **never** relaxes server verification — strict TLS stays on.
77
+
78
+ ```typescript
79
+ import { readFileSync } from 'node:fs';
80
+ import { AxiamClient } from 'axiam-sdk';
81
+
82
+ const client = new AxiamClient({
83
+ baseUrl: 'https://iam.example.com',
84
+ tenantSlug: 'acme',
85
+ orgSlug: 'acme', // organization context required for login/refresh (CONTRACT.md §5.1)
86
+ clientCert: readFileSync('device.crt', 'utf8'), // PEM certificate chain
87
+ clientKey: readFileSync('device.key', 'utf8'), // PEM private key (PKCS#8 or PKCS#1)
88
+ // customCa: readFileSync('ca.crt', 'utf8'), // optional server-trust CA (§6)
89
+ });
90
+ ```
91
+
92
+ - `clientCert` and `clientKey` are **all-or-nothing** — providing exactly one throws at
93
+ construction, and each is validated to be PEM-shaped (as `customCa` is).
94
+ - The private key is secret material: it is passed straight to the Node TLS stack and is
95
+ never retained on a public property, logged, or serialized (CONTRACT.md §7).
96
+ - **Node only.** Browsers cannot present a client certificate from JavaScript, so the
97
+ browser build validates the PEM shape then ignores `clientCert`/`clientKey` — exactly as
98
+ it already ignores `customCa`.
99
+
66
100
  ## Usage per persona
67
101
 
68
102
  ### Browser — login + authz (`axiam-sdk` / `axiam-sdk/rest`)
@@ -70,7 +104,7 @@ const client = new AxiamClient({
70
104
  ```typescript
71
105
  import { AxiamClient } from 'axiam-sdk';
72
106
 
73
- const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
107
+ const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme', orgSlug: 'acme' });
74
108
 
75
109
  const result = await client.login(email, password);
76
110
  switch (result.status) {
@@ -121,6 +155,32 @@ grpcClient.close();
121
155
  The gRPC channel is constructed once and reused; `UNAUTHENTICATED` responses transparently
122
156
  share the same single-flight refresh guard as the REST persona (CONTRACT.md §9).
123
157
 
158
+ #### gRPC userinfo (`UserInfoGrpcClient.getUserInfo`, CONTRACT.md §1.1)
159
+
160
+ `getUserInfo` is a **gRPC-only** operation (contract 1.3) — the low-latency counterpart of
161
+ the server's REST `/oauth2/userinfo` endpoint. It takes no arguments; the caller's identity
162
+ is derived server-side from the bearer token. It reuses the same channel, auth + `x-tenant-id`
163
+ metadata interceptor, and single-flight refresh guard as `AuthzGrpcClient` (a co-located
164
+ client built from the same session shares the pooled connection).
165
+
166
+ ```typescript
167
+ import { UserInfoGrpcClient, createNodeSession } from 'axiam-sdk/grpc';
168
+
169
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
170
+ // ... after a successful login() on an AxiamClient sharing this session ...
171
+ const userInfoClient = new UserInfoGrpcClient(session, { baseUrl: 'https://iam.example.com' });
172
+
173
+ const info = await userInfoClient.getUserInfo();
174
+ // info: { sub, tenantId, orgId, email?, preferredUsername? }
175
+ // email is present only with the "email" scope, preferredUsername only with "profile".
176
+
177
+ userInfoClient.close();
178
+ ```
179
+
180
+ Calling `getUserInfo()` with no token present raises `AuthError` client-side, without a wire
181
+ call (CONTRACT.md §1.1). A `UNAUTHENTICATED` response drives exactly one refresh + one retry,
182
+ identical to `checkAccess`.
183
+
124
184
  ### Node — AMQP consumer (`axiam-sdk/amqp`)
125
185
 
126
186
  ```typescript
@@ -285,10 +345,145 @@ See `examples/nestjs-app.ts` for a complete, compiling example (including the
285
345
  More runnable examples (all compiling under `tsc --noEmit -p examples/tsconfig.json`) live
286
346
  in `examples/` at the package root.
287
347
 
348
+ ## OIDC / SSO relying-party helpers (`axiam-sdk/node`, CONTRACT.md §12)
349
+
350
+ Everything a backend needs to offer **"Login with AXIAM"** — authorization code + PKCE
351
+ against AXIAM's own OIDC provider — plus service-account M2M login, token
352
+ introspection/revocation, and the upstream-IdP federation endpoints. Node-only: PKCE uses
353
+ `node:crypto` and ID-token validation uses `jose`, so these deliberately do not hang off the
354
+ browser-safe `AxiamClient` (a `/rest` browser bundle stays free of Node code, proven by CI).
355
+
356
+ ```typescript
357
+ import { createNodeSession, createOidcClient, MemoryOidcStateStore } from 'axiam-sdk/node';
358
+
359
+ // One session carries the cookie jar (§4), TLS config (§6) and refresh guard (§9)
360
+ // that the OIDC client reuses rather than duplicating.
361
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantId, orgId });
362
+
363
+ const oidc = createOidcClient(session, {
364
+ clientId: 'my-web-app',
365
+ clientSecret: process.env.AXIAM_CLIENT_SECRET, // omit for a public client
366
+ });
367
+ ```
368
+
369
+ ### The nine operations
370
+
371
+ | Operation | Wire call | Notes |
372
+ |-----------|-----------|-------|
373
+ | `oidcDiscover()` | `GET /.well-known/openid-configuration` | Cached per origin, TTL ≥ 5 min, concurrent calls share one fetch |
374
+ | `oidcBegin({ configuration, redirectUri, scope?, extraParams? })` | *none — pure local computation* | CSPRNG `state`/`nonce` (256-bit) + PKCE **S256** challenge; returns `{ url, state, nonce, codeVerifier }` |
375
+ | `oidcExchange({ code, codeVerifier, nonce, redirectUri, tenantId?, configuration? })` | `POST /oauth2/token?tenant_id=…` | `grant_type=authorization_code`; validates the ID token in full before returning |
376
+ | `oidcRefresh({ refreshToken, scope?, tenantId?, configuration? })` | `POST /oauth2/token?tenant_id=…` | `grant_type=refresh_token`, under the §9 single-flight guard. **Distinct from `AxiamClient.refresh()`**, which drives the cookie-session path |
377
+ | `loginClientCredentials({ scope?, tenantId?, adoptAsCredential?, configuration? })` | `POST /oauth2/token?tenant_id=…` | Service-account M2M login; no `openid` scope, no ID token. `adoptAsCredential: true` uses the token as the session's bearer credential |
378
+ | `introspect({ token, tokenTypeHint?, tenantId?, configuration? })` | `POST /oauth2/introspect?tenant_id=…` | RFC 7662; requires a `clientSecret` |
379
+ | `revoke({ token, tokenTypeHint?, tenantId?, configuration? })` | `POST /oauth2/revoke?tenant_id=…` | RFC 7009; returns `void` and is **idempotent** — a `200` for an unknown token is success |
380
+ | `ssoStart({ federationConfigId, redirectUri, tenantId?/tenantSlug?, orgId?/orgSlug? })` | `POST /api/v1/auth/federation/oidc/start` | Upstream-IdP SSO step 1; returns `{ authorizeUrl, state, expiresInSecs }` |
381
+ | `ssoComplete({ state, code })` | `POST /api/v1/auth/federation/oidc/callback` | Step 2; the session arrives as `Set-Cookie`, so it needs the cookie-jar-backed Node session |
382
+
383
+ Wire details worth knowing: the token/introspection/revocation endpoints are
384
+ **form-encoded** (not JSON) and take `tenant_id` as a **required query parameter** in **UUID**
385
+ form — a slug-only client raises `AuthError` client-side rather than sending a slug. Client
386
+ authentication is `client_secret_post` (never HTTP Basic). Endpoint URLs always come from the
387
+ discovery document, never hardcoded.
388
+
389
+ ### The caller owns the login state
390
+
391
+ `oidcBegin` and `oidcExchange` store **nothing** — no `state`, `nonce` or `code_verifier` in
392
+ the SDK, in process-global state, or in any implicit cache. You keep them (typically in your
393
+ own HTTP session) and pass `nonce` + `codeVerifier` back into `oidcExchange`:
394
+
395
+ ```typescript
396
+ // 1. login route
397
+ const configuration = await oidc.oidcDiscover();
398
+ const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile email' });
399
+ req.session.oidc = { state: request.state, nonce: request.nonce, verifier: request.codeVerifier };
400
+ res.redirect(request.url);
401
+
402
+ // 2. callback route — check the returned `state` matches, then exchange
403
+ const tokens = await oidc.oidcExchange({
404
+ code: String(req.query.code),
405
+ codeVerifier: req.session.oidc.verifier,
406
+ nonce: req.session.oidc.nonce,
407
+ redirectUri,
408
+ });
409
+ console.log(tokens.idClaims?.sub); // validated ID-token subject
410
+ ```
411
+
412
+ `MemoryOidcStateStore` is an optional, opt-in reference store for that bookkeeping (10-minute
413
+ TTL, single-use `consume(state)` — mirroring the server's own `federation_login_state`
414
+ semantics). It is single-process; use a shared store (Redis, a database) behind a load
415
+ balancer by implementing `OidcStateStore` yourself. The core operations never require one.
416
+
417
+ ### Framework glue
418
+
419
+ ```typescript
420
+ import { oidcLoginHandlers } from 'axiam-sdk/middleware';
421
+
422
+ const { login, callback } = oidcLoginHandlers({
423
+ client: oidc,
424
+ store: new MemoryOidcStateStore(),
425
+ redirectUri: 'https://app.example.com/auth/callback',
426
+ scope: 'openid profile email',
427
+ // Establishing YOUR app session is your decision — the SDK validates the login
428
+ // and hands you the token set.
429
+ onSuccess: (tokens) => establishMySession(String(tokens.idClaims?.sub)),
430
+ });
431
+
432
+ app.get('/auth/login', login); // 302 -> AXIAM /oauth2/authorize
433
+ app.get('/auth/callback', callback); // consume state -> exchange -> validate ID token
434
+ ```
435
+
436
+ Fastify gets the same flow as a plugin: `fastify.register(oidcLoginPlugin({ …, loginPath,
437
+ callbackPath }))`. Both are thin adapters over the shared `beginOidcLogin`/`completeOidcLogin`
438
+ core, so they cannot drift. Failure mapping is identical: `400` malformed callback, `401`
439
+ authentication failure (unknown/expired/replayed state, IdP error, ID-token failure, OAuth2
440
+ protocol error), `503` when AXIAM is unreachable — never a silent success.
441
+
442
+ The login handler reads an optional `?returnTo=` and stores it with the login state.
443
+ **Validate or allowlist that value in your application** if you accept it from user input —
444
+ an unchecked redirect target is an open-redirect vector, and the SDK cannot know which
445
+ destinations your app considers safe.
446
+
447
+ ### ID-token validation (always on)
448
+
449
+ Every ID token is validated before `oidcExchange` returns, per CONTRACT.md §12.4:
450
+ `alg` must be exactly `EdDSA` (`none` and everything else rejected, checked from the header
451
+ *before* any signature work); the Ed25519 signature must verify against the key selected by
452
+ `kid` from the document's `jwks_uri` (one JWKS re-fetch on an unknown `kid`, then fail);
453
+ `iss` must equal the discovery document's `issuer` by exact string comparison; `aud` must
454
+ contain the `client_id` (with `azp` required when there are multiple audiences); `exp`/`iat`/
455
+ `nbf` must hold within at most 60 s of clock skew; and the `nonce` claim must match the
456
+ `oidcBegin` nonce (constant-time). Any failure raises `AuthError` with a stable
457
+ `reason` code — `invalid_alg`, `unknown_kid`, `invalid_signature`, `invalid_issuer`,
458
+ `invalid_audience`, `token_expired`, `nonce_mismatch` — and **discards the entire token set**;
459
+ the access and refresh tokens from that response never reach the caller. There is no option
460
+ to disable or skip this.
461
+
462
+ ```typescript
463
+ try {
464
+ const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });
465
+ } catch (err) {
466
+ if (err instanceof OAuthProtocolError) {
467
+ console.error(err.error, err.errorDescription); // e.g. "invalid_grant", "code expired"
468
+ } else if (err instanceof AuthError) {
469
+ console.error(err.reason); // e.g. "nonce_mismatch"
470
+ }
471
+ }
472
+ ```
473
+
474
+ `access_token`, `refresh_token`, `id_token`, `client_secret` and `code_verifier` are all
475
+ `Sensitive<T>` (CONTRACT.md §12.5) — they redact to `[SENSITIVE]` in `toString()`,
476
+ `JSON.stringify()` and `console.log`. `state` and `nonce` are not secrets and stay plain
477
+ strings.
478
+
479
+ See `examples/express-oidc-login.ts` for a complete, runnable example.
480
+
288
481
  ## Error handling
289
482
 
290
- Every persona throws exactly the three CONTRACT.md §2 error types — `AuthError`,
291
- `AuthzError`, `NetworkError`:
483
+ Every persona throws the three CONTRACT.md §2 error types — `AuthError`, `AuthzError`,
484
+ `NetworkError` — plus one `AuthError` **sub-type**, `OAuthProtocolError`, for RFC 6749
485
+ protocol errors from `/oauth2/*` (its `message` is always `"<error>: <error_description>"`,
486
+ and `instanceof AuthError` still matches it):
292
487
 
293
488
  ```typescript
294
489
  import { AuthError, AuthzError, NetworkError } from 'axiam-sdk';
@@ -304,6 +499,17 @@ try {
304
499
  // transport-level failure
305
500
  }
306
501
  }
502
+
503
+ // OAuth2 protocol errors are AuthError sub-types (CONTRACT.md §2, §12.3 rule 3)
504
+ import { OAuthProtocolError } from 'axiam-sdk';
505
+
506
+ try {
507
+ await oidc.oidcRefresh({ refreshToken });
508
+ } catch (err) {
509
+ if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {
510
+ // the refresh token was revoked or already used — re-authenticate
511
+ }
512
+ }
307
513
  ```
308
514
 
309
515
  ## Security notes
@@ -311,10 +517,15 @@ try {
311
517
  - Token-carrying values are wrapped in `Sensitive<T>` — `toString()`/`toJSON()`/
312
518
  `util.inspect` all redact to `[SENSITIVE]`; the raw value is only reachable via an
313
519
  explicit accessor (CONTRACT.md §7).
314
- - Strict TLS verification is always on; the only escape hatch is the constructor's
315
- `customCa` option for self-signed development environments (CONTRACT.md §6).
520
+ - Strict TLS verification is always on; the only server-trust escape hatch is the
521
+ constructor's `customCa` option for self-signed development environments (CONTRACT.md §6).
522
+ - Optional mutual TLS (mTLS): a PEM `clientCert`/`clientKey` client identity (Node only) is
523
+ presented on both REST and gRPC without ever relaxing server verification (CONTRACT.md §6.1).
316
524
  - AMQP messages are HMAC-SHA256 verified before your handler ever sees them; verification
317
525
  failures are nacked without requeue (CONTRACT.md §8).
526
+ - The OIDC relying-party flow is PKCE **S256**-only (`plain` is not implemented), ID tokens are
527
+ `EdDSA`-only and validated on every exchange with no opt-out, and login state
528
+ (`state`/`nonce`/`code_verifier`) is never stored inside the SDK (CONTRACT.md §12).
318
529
 
319
530
  ## Release / versioning
320
531
 
@@ -1,4 +1,4 @@
1
- import { S as Sensitive } from '../sensitive-CWBH_tHr.cjs';
1
+ import { S as Sensitive } from '../sensitive-BC_s7Rrd.cjs';
2
2
  import { ConsumeMessage } from 'amqplib';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { S as Sensitive } from '../sensitive-CWBH_tHr.js';
1
+ import { S as Sensitive } from '../sensitive-BC_s7Rrd.js';
2
2
  import { ConsumeMessage } from 'amqplib';
3
3
 
4
4
  /**
@@ -12,6 +12,7 @@ var REDACTED = "[SENSITIVE]";
12
12
  var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
13
13
  var Sensitive = class {
14
14
  #value;
15
+ /** Wrap `value` so it can never be logged or serialized by accident. */
15
16
  constructor(value) {
16
17
  this.#value = value;
17
18
  }
@@ -19,12 +20,15 @@ var Sensitive = class {
19
20
  expose() {
20
21
  return this.#value;
21
22
  }
23
+ /** Returns the `"[SENSITIVE]"` placeholder — never the wrapped value. */
22
24
  toString() {
23
25
  return REDACTED;
24
26
  }
27
+ /** Makes `JSON.stringify()` emit the `"[SENSITIVE]"` placeholder. */
25
28
  toJSON() {
26
29
  return REDACTED;
27
30
  }
31
+ /** Makes `console.log`/`util.inspect` print the `"[SENSITIVE]"` placeholder. */
28
32
  [NODE_INSPECT_CUSTOM]() {
29
33
  return REDACTED;
30
34
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/sensitive.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/consumer.ts"],"names":["createHmac","timingSafeEqual","amqp"],"mappings":";;;;;;;;;;AAYO,IAAM,QAAA,GAAW,aAAA;AAExB,IAAM,mBAAA,mBAAsB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAE5D,IAAM,YAAN,MAAmB;AAAA,EACf,MAAA;AAAA,EAET,YAAY,KAAA,EAAU;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA,EAEA,QAAA,GAAmB;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,MAAA,GAAiB;AACf,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,CAAC,mBAAmB,CAAA,GAAY;AAC9B,IAAA,OAAO,QAAA;AAAA,EACT;AACF;ACbO,SAAS,WAAA,CAAY,KAAa,WAAA,EAA6B;AACpE,EAAA,OAAOA,iBAAA,CAAW,U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AA,CAAQ,IAAA,CAAK,GAAA,EAAK,KAAA,EAAO,KAAK,CAAA;AAC9B,IAAA;AAAA,EACF;AAEA,EAAA,OAAA,CAAQ,IAAI,GAAG,CAAA;AACjB;AAgBA,eAAsB,QACpB,OAAA,EACA,KAAA,EACA,YACA,OAAA,EACA,OAAA,GAA0B,EAAC,EACZ;AACf,EAAA,MAAM,UAAA,GAAa,MAAMC,qBAAA,CAAK,OAAA,CAAQ,OAAO,CAAA;AAC7C,EAAA,MAAM,OAAA,GAAmB,MAAM,UAAA,CAAW,aAAA,EAAc;AACxD,EAAA,MAAM,QAAQ,WAAA,CAAY,KAAA,EAAO,EAAE,OAAA,EAAS,MAAM,CAAA;AAKlD,EAAA,MAAM,aAAA,GAAgC;AAAA,IACpC,GAAG,OAAA;AAAA,IACH,UAAA,EAAY,OAAA,CAAQ,UAAA,IAAc,IAAI,kBAAA;AAAmB,GAC3D;AAEA,EAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,CAAC,GAAA,KAAQ;AACpC,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,KAAK,kBAAkB,OAAA,EAAS,GAAA,EAAK,WAAW,MAAA,EAAO,EAAG,SAAS,aAAa,CAAA;AAAA,EAClF,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\nexport class Sensitive<T> {\n readonly #value: T;\n\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n toString(): string {\n return REDACTED;\n }\n\n toJSON(): string {\n return REDACTED;\n }\n\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// AMQP HMAC-SHA256 sign/verify (CONTRACT.md §8, D-12).\n//\n// Mirror, never import. This module reproduces the server's algorithm in\n// crates/axiam-amqp/src/messages.rs:35-50 (and the Rust SDK's src/amqp/hmac.rs)\n// byte-for-byte using only Node's built-in `node:crypto` module, so the\n// SDK's HMAC output is wire-compatible with the AXIAM server for the same\n// key + canonical JSON payload bytes.\n//\n// Protocol (CONTRACT.md §8.2):\n// a. Extract hmac_signature from the message.\n// b. Set hmac_signature to null/absent in the body.\n// c. Serialize the remaining body to canonical JSON (declaration/insertion\n// order, no re-sorting — see messages.ts and Pitfall 5).\n// d. HMAC-SHA256(key, canonical_json_bytes), hex-encoded.\n// e. Constant-time compare against the received signature.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/**\n * Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.\n *\n * `payloadJson` MUST be the canonical JSON bytes of the message body with\n * `hmac_signature` already removed — otherwise the signature is computed\n * over a payload that includes a placeholder signature, making verification\n * impossible (matches the server's `sign_payload` doc comment).\n */\nexport function signPayload(key: Buffer, payloadJson: Buffer): string {\n return createHmac('sha256', key).update(payloadJson).digest('hex');\n}\n\n/**\n * Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.\n *\n * Returns `true` only if the signature matches, comparing in constant time\n * via `timingSafeEqual`. Never throws: malformed hex or a length mismatch\n * both return `false`.\n */\nexport function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean {\n const expected = createHmac('sha256', key).update(payloadJson).digest();\n let received: Buffer;\n try {\n received = Buffer.from(signatureHex, 'hex');\n } catch {\n return false;\n }\n // timingSafeEqual requires equal-length buffers; a length mismatch is\n // itself not secret information, so a fast-path length check first is\n // safe and matches Rust's hmac crate `verify_slice` behavior.\n if (received.length !== expected.length) return false;\n return timingSafeEqual(received, expected);\n}\n","// AMQP message DTOs mirroring the server's wire format (CONTRACT.md §8).\n//\n// Mirror, never import. These interfaces reproduce field declaration order\n// byte-for-byte from crates/axiam-amqp/src/messages.rs (and\n// the Rust SDK's src/amqp/messages.rs) so that `JSON.stringify` on a parsed\n// object (after deleting `hmac_signature`) produces canonical JSON\n// byte-identical to what the server signs/verifies against — see\n// Pitfall 5: no schema-validator reconstruction step before HMAC\n// verification, or the field order (and therefore the signed bytes) could\n// silently diverge.\n\n/**\n * Authorization check request received from `axiam.authz.request`.\n *\n * Field declaration order matches the server's `AuthzRequest`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * correlation_id, tenant_id, subject_id, action, resource_id, scope,\n * key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and\n * `issued_at` are always emitted (never omitted) so they fall inside the\n * HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay Protection\".\n */\nexport interface AuthzRequest {\n /** Caller-provided ID to correlate request with response. */\n correlation_id: string;\n tenant_id: string;\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /**\n * HMAC-SHA256 of the JSON-serialized message body (this field removed\n * before signing). Computed with the per-tenant AMQP signing key\n * (CONTRACT.md §8). The consumer MUST verify this before processing; a\n * missing signature is rejected in strict mode (the default).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to `axiam.authz.response`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n}\n\n/**\n * Audit event received from external services via `axiam.audit.events`.\n *\n * Field declaration order matches the server's `AuditEventMessage`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,\n * metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,\n * `nonce`, and `issued_at` are always emitted (never omitted) so they fall\n * inside the HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay\n * Protection\".\n */\nexport interface AuditEventMessage {\n tenant_id: string;\n actor_id: string;\n actor_type: string;\n action: string;\n resource_id?: string;\n outcome: string;\n ip_address?: string;\n metadata?: Record<string, unknown>;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */\n hmac_signature?: string;\n}\n\n/**\n * Notification event published to `axiam.notifications`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface NotificationEvent {\n event_type: string;\n tenant_id: string;\n actor_id: string;\n resource_id?: string;\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Message type names subject to HMAC verification per CONTRACT.md §8's\n * message-types table (`axiam.authz.request` -> AuthzRequest,\n * `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and\n * `NotificationEvent` are server-published and never carry\n * `hmac_signature`.\n */\nexport const HMAC_SIGNED_MESSAGE_TYPES = ['AuthzRequest', 'AuditEventMessage'] as const;\n\nexport type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];\n","// Closure-handler AMQP consumer (D-12, CONTRACT.md §8.3g/§8.4).\n//\n// The SDK owns the full ack/nack loop. Every delivery is HMAC-verified\n// (CONTRACT.md §8) BEFORE the caller-supplied handler is ever invoked. On\n// any verification failure (signature mismatch, missing signature in the\n// default strict mode, or a body that fails to parse as JSON) the delivery\n// is nacked WITHOUT requeue and a security event is emitted — the event\n// never contains the received/expected HMAC value or the signing key. Only\n// a verified delivery reaches the handler, and only then is it acked.\n//\n// NEW-4 (CONTRACT.md §8 \"v2 — Replay Protection\", hard cutover): once the\n// HMAC verifies, the delivery is ADDITIONALLY rejected (same nack-without-\n// requeue path) when `key_version < 2`, `issued_at` falls outside the\n// ±skew freshness window, or `nonce` has already been seen. Because this\n// module verifies by re-serializing the parsed body (minus\n// `hmac_signature`) in insertion order (Pitfall 5), `nonce`/`issued_at` are\n// already covered by the HMAC bytes with no canonicalization change — only\n// the three validation gates below are new.\n//\n// This is the TS port of the already-tested Rust `verify_and_dispatch`/\n// `consume` (the Rust SDK's src/amqp/consumer.rs).\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport { verifyPayload } from './hmac.js';\n\n/**\n * Default freshness skew for `issued_at` acceptance (NEW-4): a message is\n * accepted only when its `issued_at` lies within ±5 minutes of the\n * verifier's clock, matching the server's\n * `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`\n * (CONTRACT.md §8 v2).\n */\nexport const DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when\n * `nonce` has already been recorded and its dedup entry has not yet\n * expired (i.e. this delivery is a replay); otherwise it records the nonce\n * with the given TTL and returns `false`.\n */\nexport interface NonceStore {\n checkAndRecord(nonce: string, ttlMs: number): boolean;\n}\n\n/**\n * Default in-memory nonce dedup store (NEW-4). Naturally bounded: each\n * entry expires after `ttlMs` (the caller passes 2x the freshness skew, so\n * a nonce can never still be \"fresh\" once its dedup entry has lapsed) and\n * expired entries are pruned opportunistically on each check — no\n * background timer and no unbounded growth under sustained traffic.\n *\n * Share ONE instance across every delivery from the same consumer (as\n * `consume()` does by default) — a fresh store per call provides no\n * cross-message replay protection.\n */\nexport class InMemoryNonceStore implements NonceStore {\n private readonly seenUntilMs = new Map<string, number>();\n\n checkAndRecord(nonce: string, ttlMs: number): boolean {\n const now = Date.now();\n this.prune(now);\n const expiry = this.seenUntilMs.get(nonce);\n if (expiry !== undefined && expiry > now) {\n return true;\n }\n this.seenUntilMs.set(nonce, now + ttlMs);\n return false;\n }\n\n private prune(now: number): void {\n for (const [nonce, expiry] of this.seenUntilMs) {\n if (expiry <= now) this.seenUntilMs.delete(nonce);\n }\n }\n}\n\ntype ReplayRejectReason = 'key_version' | 'issued_at' | 'nonce';\n\n/**\n * NEW-4 validation gates, checked only AFTER the HMAC has already verified.\n * Returns the failing gate's name, or `undefined` when all three pass.\n * `ttlMs` for the nonce store is 2x `skewMs` — the freshness window plus a\n * margin so a nonce cannot be replayed the instant its dedup entry expires\n * while `issued_at` might still (barely) be judged fresh by a differently-\n * skewed verifier.\n */\nfunction checkReplayProtection(\n body: Record<string, unknown>,\n skewMs: number,\n nonceStore: NonceStore,\n): ReplayRejectReason | undefined {\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || keyVersion < 2) {\n return 'key_version';\n }\n\n const issuedAtRaw = body.issued_at;\n if (typeof issuedAtRaw !== 'string') {\n return 'issued_at';\n }\n const issuedAtMs = Date.parse(issuedAtRaw);\n if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {\n return 'issued_at';\n }\n\n const nonce = body.nonce;\n if (typeof nonce !== 'string' || nonce.length === 0) {\n return 'nonce';\n }\n if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {\n return 'nonce';\n }\n\n return undefined;\n}\n\n/**\n * Minimal seam over the channel operations this module needs\n * (ack/nack/consume). `amqplib`'s `Channel` implements this directly;\n * tests provide a recording fake that never touches a live broker, so the\n * security-sensitive nack-without-requeue behavior can be asserted without\n * a running RabbitMQ instance.\n */\nexport interface ConsumeChannel {\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void | Promise<void>,\n ): Promise<unknown>;\n /** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\nexport interface ConsumeLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface ConsumeOptions {\n logger?: ConsumeLogger;\n /**\n * Strict mode (default true, CONTRACT.md §8.3): a message with no\n * `hmac_signature` is treated as a verification failure (nack-no-requeue),\n * not a pass-through. Lenient mode (false) is a temporary rolling-\n * deployment measure only — strict MUST remain the default.\n */\n strict?: boolean;\n /**\n * Freshness skew window for `issued_at` validation (NEW-4), in\n * milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),\n * matching the server default (CONTRACT.md §8 v2).\n */\n skewMs?: number;\n /**\n * Nonce replay-dedup store (NEW-4). Defaults to a fresh\n * `InMemoryNonceStore` per call when omitted — `consume()` creates and\n * shares ONE store across every delivery on that connection by default;\n * callers invoking `verifyAndDispatch` directly across multiple messages\n * must pass the same store explicitly for dedup to take effect.\n */\n nonceStore?: NonceStore;\n}\n\n/**\n * Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,\n * only on success, invoke `handler` with the parsed body (hmac_signature\n * removed) before acking. On any failure the delivery is nacked without\n * requeue and a security event is emitted that never contains the HMAC\n * value or the signing key.\n *\n * Exported (not just used internally) so it is the same separately-testable\n * unit backing `consume`'s per-message loop, mirroring the Rust SDK's\n * `verify_and_dispatch`.\n */\nexport async function verifyAndDispatch(\n channel: ConsumeChannel,\n msg: ConsumeMessage,\n signingKey: Buffer,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const { logger, strict = true } = options;\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n logger?.warn('axiam_sdk.security', 'AMQP message body failed JSON parse; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n const sig = typeof body.hmac_signature === 'string' ? body.hmac_signature : undefined;\n delete body.hmac_signature;\n const canonical = Buffer.from(JSON.stringify(body), 'utf8');\n\n // Strict mode (default, CONTRACT.md §8.3): a missing signature is treated\n // as a verification failure, not a pass-through. A present signature is\n // always verified regardless of strict/lenient mode; lenient mode only\n // changes the outcome for a MISSING signature (temporary rolling-\n // deployment measure — strict MUST remain the default).\n let verified: boolean;\n if (sig !== undefined) {\n verified = verifyPayload(signingKey, canonical, sig);\n } else {\n verified = !strict;\n }\n\n if (!verified) {\n // Security event (§8.4): timestamp, exchange, routing key, and tenant\n // context (if present in the body) — NEVER the signature value or the\n // signing key.\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn('axiam_sdk.security', 'AMQP HMAC verification failed; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n // NEW-4 (CONTRACT.md §8 v2, hard cutover): only reached once the HMAC has\n // verified. `body` was re-serialized in insertion order to compute\n // `canonical` above, so `nonce`/`issued_at` are already inside the bytes\n // that were just verified — these are the three ADDITIONAL validation\n // gates (key_version, freshness, replay), not re-verification.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);\n if (replayRejectReason) {\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn(\n 'axiam_sdk.security',\n `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,\n {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n },\n );\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n try {\n await handler(body);\n } catch (err) {\n // Do not requeue a handler-crashing message into a hot loop.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n error: err instanceof Error ? err.message : String(err),\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n channel.ack(msg);\n}\n\n/**\n * Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and\n * consume from it — verifying each delivery's HMAC-SHA256 signature\n * (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an\n * unverified message; verification failures are nacked without requeue and\n * logged as a security event.\n *\n * `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK\n * does not fetch it from the server (no such endpoint exists; CONTRACT.md\n * §8.1 assumes out-of-band provisioning).\n *\n * This function owns the full ack/nack loop; `handler` MUST NOT itself call\n * ack/nack (there is no delivery handle exposed to it).\n */\nexport async function consume(\n amqpUrl: string,\n queue: string,\n signingKey: Sensitive<Buffer>,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const connection = await amqp.connect(amqpUrl);\n const channel: Channel = await connection.createChannel();\n await channel.assertQueue(queue, { durable: true });\n\n // NEW-4: one nonce store shared across every delivery on this consumer —\n // a fresh store per message (the per-call default in `verifyAndDispatch`)\n // would defeat replay dedup entirely.\n const sharedOptions: ConsumeOptions = {\n ...options,\n nonceStore: options.nonceStore ?? new InMemoryNonceStore(),\n };\n\n await channel.consume(queue, (msg) => {\n if (!msg) return;\n void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);\n });\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/sensitive.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/consumer.ts"],"names":["createHmac","timingSafeEqual","amqp"],"mappings":";;;;;;;;;;AAYO,IAAM,QAAA,GAAW,aAAA;AAExB,IAAM,mBAAA,mBAAsB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAyB5D,IAAM,YAAN,MAAmB;AAAA,EACf,MAAA;AAAA;AAAA,EAGT,YAAY,KAAA,EAAU;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA;AAAA,EAGA,QAAA,GAAmB;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA;AAAA,EAGA,MAAA,GAAiB;AACf,IAAA,OAAO,QAAA;AAAA,EACT;AAAA;AAAA,EAGA,CAAC,mBAAmB,CAAA,GAAY;AAC9B,IAAA,OAAO,QAAA;AAAA,EACT;AACF;ACx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GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACvD,CAAA;AAED,IAAA,OAAA,CAAQ,IAAA,CAAK,GAAA,EAAK,KAAA,EAAO,KAAK,CAAA;AAC9B,IAAA;AAAA,EACF;AAEA,EAAA,OAAA,CAAQ,IAAI,GAAG,CAAA;AACjB;AAgBA,eAAsB,QACpB,OAAA,EACA,KAAA,EACA,YACA,OAAA,EACA,OAAA,GAA0B,EAAC,EACZ;AACf,EAAA,MAAM,UAAA,GAAa,MAAMC,qBAAA,CAAK,OAAA,CAAQ,OAAO,CAAA;AAC7C,EAAA,MAAM,OAAA,GAAmB,MAAM,UAAA,CAAW,aAAA,EAAc;AACxD,EAAA,MAAM,QAAQ,WAAA,CAAY,KAAA,EAAO,EAAE,OAAA,EAAS,MAAM,CAAA;AAKlD,EAAA,MAAM,aAAA,GAAgC;AAAA,IACpC,GAAG,OAAA;AAAA,IACH,UAAA,EAAY,OAAA,CAAQ,UAAA,IAAc,IAAI,kBAAA;AAAmB,GAC3D;AAEA,EAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,CAAC,GAAA,KAAQ;AACpC,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,KAAK,kBAAkB,OAAA,EAAS,GAAA,EAAK,WAAW,MAAA,EAAO,EAAG,SAAS,aAAa,CAAA;AAAA,EAClF,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// AMQP HMAC-SHA256 sign/verify (CONTRACT.md §8, D-12).\n//\n// Mirror, never import. This module reproduces the server's algorithm in\n// crates/axiam-amqp/src/messages.rs:35-50 (and the Rust SDK's src/amqp/hmac.rs)\n// byte-for-byte using only Node's built-in `node:crypto` module, so the\n// SDK's HMAC output is wire-compatible with the AXIAM server for the same\n// key + canonical JSON payload bytes.\n//\n// Protocol (CONTRACT.md §8.2):\n// a. Extract hmac_signature from the message.\n// b. Set hmac_signature to null/absent in the body.\n// c. Serialize the remaining body to canonical JSON (declaration/insertion\n// order, no re-sorting — see messages.ts and Pitfall 5).\n// d. HMAC-SHA256(key, canonical_json_bytes), hex-encoded.\n// e. Constant-time compare against the received signature.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/**\n * Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.\n *\n * `payloadJson` MUST be the canonical JSON bytes of the message body with\n * `hmac_signature` already removed — otherwise the signature is computed\n * over a payload that includes a placeholder signature, making verification\n * impossible (matches the server's `sign_payload` doc comment).\n */\nexport function signPayload(key: Buffer, payloadJson: Buffer): string {\n return createHmac('sha256', key).update(payloadJson).digest('hex');\n}\n\n/**\n * Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.\n *\n * Returns `true` only if the signature matches, comparing in constant time\n * via `timingSafeEqual`. Never throws: malformed hex or a length mismatch\n * both return `false`.\n */\nexport function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean {\n const expected = createHmac('sha256', key).update(payloadJson).digest();\n let received: Buffer;\n try {\n received = Buffer.from(signatureHex, 'hex');\n } catch {\n return false;\n }\n // timingSafeEqual requires equal-length buffers; a length mismatch is\n // itself not secret information, so a fast-path length check first is\n // safe and matches Rust's hmac crate `verify_slice` behavior.\n if (received.length !== expected.length) return false;\n return timingSafeEqual(received, expected);\n}\n","// AMQP message DTOs mirroring the server's wire format (CONTRACT.md §8).\n//\n// Mirror, never import. These interfaces reproduce field declaration order\n// byte-for-byte from crates/axiam-amqp/src/messages.rs (and\n// the Rust SDK's src/amqp/messages.rs) so that `JSON.stringify` on a parsed\n// object (after deleting `hmac_signature`) produces canonical JSON\n// byte-identical to what the server signs/verifies against — see\n// Pitfall 5: no schema-validator reconstruction step before HMAC\n// verification, or the field order (and therefore the signed bytes) could\n// silently diverge.\n\n/**\n * Authorization check request received from `axiam.authz.request`.\n *\n * Field declaration order matches the server's `AuthzRequest`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * correlation_id, tenant_id, subject_id, action, resource_id, scope,\n * key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and\n * `issued_at` are always emitted (never omitted) so they fall inside the\n * HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay Protection\".\n */\nexport interface AuthzRequest {\n /** Caller-provided ID to correlate request with response. */\n correlation_id: string;\n tenant_id: string;\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /**\n * HMAC-SHA256 of the JSON-serialized message body (this field removed\n * before signing). Computed with the per-tenant AMQP signing key\n * (CONTRACT.md §8). The consumer MUST verify this before processing; a\n * missing signature is rejected in strict mode (the default).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to `axiam.authz.response`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n}\n\n/**\n * Audit event received from external services via `axiam.audit.events`.\n *\n * Field declaration order matches the server's `AuditEventMessage`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,\n * metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,\n * `nonce`, and `issued_at` are always emitted (never omitted) so they fall\n * inside the HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay\n * Protection\".\n */\nexport interface AuditEventMessage {\n tenant_id: string;\n actor_id: string;\n actor_type: string;\n action: string;\n resource_id?: string;\n outcome: string;\n ip_address?: string;\n metadata?: Record<string, unknown>;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */\n hmac_signature?: string;\n}\n\n/**\n * Notification event published to `axiam.notifications`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface NotificationEvent {\n event_type: string;\n tenant_id: string;\n actor_id: string;\n resource_id?: string;\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Message type names subject to HMAC verification per CONTRACT.md §8's\n * message-types table (`axiam.authz.request` -> AuthzRequest,\n * `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and\n * `NotificationEvent` are server-published and never carry\n * `hmac_signature`.\n */\nexport const HMAC_SIGNED_MESSAGE_TYPES = ['AuthzRequest', 'AuditEventMessage'] as const;\n\nexport type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];\n","// Closure-handler AMQP consumer (D-12, CONTRACT.md §8.3g/§8.4).\n//\n// The SDK owns the full ack/nack loop. Every delivery is HMAC-verified\n// (CONTRACT.md §8) BEFORE the caller-supplied handler is ever invoked. On\n// any verification failure (signature mismatch, missing signature in the\n// default strict mode, or a body that fails to parse as JSON) the delivery\n// is nacked WITHOUT requeue and a security event is emitted — the event\n// never contains the received/expected HMAC value or the signing key. Only\n// a verified delivery reaches the handler, and only then is it acked.\n//\n// NEW-4 (CONTRACT.md §8 \"v2 — Replay Protection\", hard cutover): once the\n// HMAC verifies, the delivery is ADDITIONALLY rejected (same nack-without-\n// requeue path) when `key_version < 2`, `issued_at` falls outside the\n// ±skew freshness window, or `nonce` has already been seen. Because this\n// module verifies by re-serializing the parsed body (minus\n// `hmac_signature`) in insertion order (Pitfall 5), `nonce`/`issued_at` are\n// already covered by the HMAC bytes with no canonicalization change — only\n// the three validation gates below are new.\n//\n// This is the TS port of the already-tested Rust `verify_and_dispatch`/\n// `consume` (the Rust SDK's src/amqp/consumer.rs).\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport { verifyPayload } from './hmac.js';\n\n/**\n * Default freshness skew for `issued_at` acceptance (NEW-4): a message is\n * accepted only when its `issued_at` lies within ±5 minutes of the\n * verifier's clock, matching the server's\n * `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`\n * (CONTRACT.md §8 v2).\n */\nexport const DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when\n * `nonce` has already been recorded and its dedup entry has not yet\n * expired (i.e. this delivery is a replay); otherwise it records the nonce\n * with the given TTL and returns `false`.\n */\nexport interface NonceStore {\n checkAndRecord(nonce: string, ttlMs: number): boolean;\n}\n\n/**\n * Default in-memory nonce dedup store (NEW-4). Naturally bounded: each\n * entry expires after `ttlMs` (the caller passes 2x the freshness skew, so\n * a nonce can never still be \"fresh\" once its dedup entry has lapsed) and\n * expired entries are pruned opportunistically on each check — no\n * background timer and no unbounded growth under sustained traffic.\n *\n * Share ONE instance across every delivery from the same consumer (as\n * `consume()` does by default) — a fresh store per call provides no\n * cross-message replay protection.\n */\nexport class InMemoryNonceStore implements NonceStore {\n private readonly seenUntilMs = new Map<string, number>();\n\n checkAndRecord(nonce: string, ttlMs: number): boolean {\n const now = Date.now();\n this.prune(now);\n const expiry = this.seenUntilMs.get(nonce);\n if (expiry !== undefined && expiry > now) {\n return true;\n }\n this.seenUntilMs.set(nonce, now + ttlMs);\n return false;\n }\n\n private prune(now: number): void {\n for (const [nonce, expiry] of this.seenUntilMs) {\n if (expiry <= now) this.seenUntilMs.delete(nonce);\n }\n }\n}\n\ntype ReplayRejectReason = 'key_version' | 'issued_at' | 'nonce';\n\n/**\n * NEW-4 validation gates, checked only AFTER the HMAC has already verified.\n * Returns the failing gate's name, or `undefined` when all three pass.\n * `ttlMs` for the nonce store is 2x `skewMs` — the freshness window plus a\n * margin so a nonce cannot be replayed the instant its dedup entry expires\n * while `issued_at` might still (barely) be judged fresh by a differently-\n * skewed verifier.\n */\nfunction checkReplayProtection(\n body: Record<string, unknown>,\n skewMs: number,\n nonceStore: NonceStore,\n): ReplayRejectReason | undefined {\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || keyVersion < 2) {\n return 'key_version';\n }\n\n const issuedAtRaw = body.issued_at;\n if (typeof issuedAtRaw !== 'string') {\n return 'issued_at';\n }\n const issuedAtMs = Date.parse(issuedAtRaw);\n if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {\n return 'issued_at';\n }\n\n const nonce = body.nonce;\n if (typeof nonce !== 'string' || nonce.length === 0) {\n return 'nonce';\n }\n if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {\n return 'nonce';\n }\n\n return undefined;\n}\n\n/**\n * Minimal seam over the channel operations this module needs\n * (ack/nack/consume). `amqplib`'s `Channel` implements this directly;\n * tests provide a recording fake that never touches a live broker, so the\n * security-sensitive nack-without-requeue behavior can be asserted without\n * a running RabbitMQ instance.\n */\nexport interface ConsumeChannel {\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void | Promise<void>,\n ): Promise<unknown>;\n /** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\nexport interface ConsumeLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface ConsumeOptions {\n logger?: ConsumeLogger;\n /**\n * Strict mode (default true, CONTRACT.md §8.3): a message with no\n * `hmac_signature` is treated as a verification failure (nack-no-requeue),\n * not a pass-through. Lenient mode (false) is a temporary rolling-\n * deployment measure only — strict MUST remain the default.\n */\n strict?: boolean;\n /**\n * Freshness skew window for `issued_at` validation (NEW-4), in\n * milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),\n * matching the server default (CONTRACT.md §8 v2).\n */\n skewMs?: number;\n /**\n * Nonce replay-dedup store (NEW-4). Defaults to a fresh\n * `InMemoryNonceStore` per call when omitted — `consume()` creates and\n * shares ONE store across every delivery on that connection by default;\n * callers invoking `verifyAndDispatch` directly across multiple messages\n * must pass the same store explicitly for dedup to take effect.\n */\n nonceStore?: NonceStore;\n}\n\n/**\n * Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,\n * only on success, invoke `handler` with the parsed body (hmac_signature\n * removed) before acking. On any failure the delivery is nacked without\n * requeue and a security event is emitted that never contains the HMAC\n * value or the signing key.\n *\n * Exported (not just used internally) so it is the same separately-testable\n * unit backing `consume`'s per-message loop, mirroring the Rust SDK's\n * `verify_and_dispatch`.\n */\nexport async function verifyAndDispatch(\n channel: ConsumeChannel,\n msg: ConsumeMessage,\n signingKey: Buffer,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const { logger, strict = true } = options;\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n logger?.warn('axiam_sdk.security', 'AMQP message body failed JSON parse; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n const sig = typeof body.hmac_signature === 'string' ? body.hmac_signature : undefined;\n delete body.hmac_signature;\n const canonical = Buffer.from(JSON.stringify(body), 'utf8');\n\n // Strict mode (default, CONTRACT.md §8.3): a missing signature is treated\n // as a verification failure, not a pass-through. A present signature is\n // always verified regardless of strict/lenient mode; lenient mode only\n // changes the outcome for a MISSING signature (temporary rolling-\n // deployment measure — strict MUST remain the default).\n let verified: boolean;\n if (sig !== undefined) {\n verified = verifyPayload(signingKey, canonical, sig);\n } else {\n verified = !strict;\n }\n\n if (!verified) {\n // Security event (§8.4): timestamp, exchange, routing key, and tenant\n // context (if present in the body) — NEVER the signature value or the\n // signing key.\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn('axiam_sdk.security', 'AMQP HMAC verification failed; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n // NEW-4 (CONTRACT.md §8 v2, hard cutover): only reached once the HMAC has\n // verified. `body` was re-serialized in insertion order to compute\n // `canonical` above, so `nonce`/`issued_at` are already inside the bytes\n // that were just verified — these are the three ADDITIONAL validation\n // gates (key_version, freshness, replay), not re-verification.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);\n if (replayRejectReason) {\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn(\n 'axiam_sdk.security',\n `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,\n {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n },\n );\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n try {\n await handler(body);\n } catch (err) {\n // Do not requeue a handler-crashing message into a hot loop.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n error: err instanceof Error ? err.message : String(err),\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n channel.ack(msg);\n}\n\n/**\n * Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and\n * consume from it — verifying each delivery's HMAC-SHA256 signature\n * (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an\n * unverified message; verification failures are nacked without requeue and\n * logged as a security event.\n *\n * `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK\n * does not fetch it from the server (no such endpoint exists; CONTRACT.md\n * §8.1 assumes out-of-band provisioning).\n *\n * This function owns the full ack/nack loop; `handler` MUST NOT itself call\n * ack/nack (there is no delivery handle exposed to it).\n */\nexport async function consume(\n amqpUrl: string,\n queue: string,\n signingKey: Sensitive<Buffer>,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const connection = await amqp.connect(amqpUrl);\n const channel: Channel = await connection.createChannel();\n await channel.assertQueue(queue, { durable: true });\n\n // NEW-4: one nonce store shared across every delivery on this consumer —\n // a fresh store per message (the per-call default in `verifyAndDispatch`)\n // would defeat replay dedup entirely.\n const sharedOptions: ConsumeOptions = {\n ...options,\n nonceStore: options.nonceStore ?? new InMemoryNonceStore(),\n };\n\n await channel.consume(queue, (msg) => {\n if (!msg) return;\n void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);\n });\n}\n"]}
@@ -6,6 +6,7 @@ var REDACTED = "[SENSITIVE]";
6
6
  var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
7
7
  var Sensitive = class {
8
8
  #value;
9
+ /** Wrap `value` so it can never be logged or serialized by accident. */
9
10
  constructor(value) {
10
11
  this.#value = value;
11
12
  }
@@ -13,12 +14,15 @@ var Sensitive = class {
13
14
  expose() {
14
15
  return this.#value;
15
16
  }
17
+ /** Returns the `"[SENSITIVE]"` placeholder — never the wrapped value. */
16
18
  toString() {
17
19
  return REDACTED;
18
20
  }
21
+ /** Makes `JSON.stringify()` emit the `"[SENSITIVE]"` placeholder. */
19
22
  toJSON() {
20
23
  return REDACTED;
21
24
  }
25
+ /** Makes `console.log`/`util.inspect` print the `"[SENSITIVE]"` placeholder. */
22
26
  [NODE_INSPECT_CUSTOM]() {
23
27
  return REDACTED;
24
28
  }