axiam-sdk 1.1.3 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +73 -3
  2. package/dist/amqp/index.js.map +1 -1
  3. package/dist/amqp/index.mjs.map +1 -1
  4. package/dist/browser/index.d.cts +1 -1
  5. package/dist/browser/index.d.ts +1 -1
  6. package/dist/{client-BGFn1VQh.d.cts → client-Bp7riC4k.d.cts} +147 -3
  7. package/dist/{client-DrQZZ1js.d.ts → client-CaurIxje.d.ts} +147 -3
  8. package/dist/{cookieJar-BTmpjXZe.d.ts → cookieJar-DC4GLKrJ.d.ts} +2 -2
  9. package/dist/{cookieJar-BqYOnNN-.d.cts → cookieJar-oKazfbN1.d.cts} +2 -2
  10. package/dist/{errors-DZ3k8a8i.d.cts → errors-CWlh-wcm.d.cts} +7 -1
  11. package/dist/{errors-DZ3k8a8i.d.ts → errors-CWlh-wcm.d.ts} +7 -1
  12. package/dist/{errors-dlGXAsbh.d.ts → errors-DDo3oxcH.d.ts} +1 -1
  13. package/dist/{errors-RvGlTyUj.d.cts → errors-DHauOsqx.d.cts} +1 -1
  14. package/dist/grpc/index.d.cts +4 -4
  15. package/dist/grpc/index.d.ts +4 -4
  16. package/dist/grpc/index.js +26 -5
  17. package/dist/grpc/index.js.map +1 -1
  18. package/dist/grpc/index.mjs +26 -5
  19. package/dist/grpc/index.mjs.map +1 -1
  20. package/dist/index.d.cts +4 -4
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +26 -5
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +26 -5
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/middleware/index.d.cts +5 -5
  27. package/dist/middleware/index.d.ts +5 -5
  28. package/dist/middleware/index.js +164 -12
  29. package/dist/middleware/index.js.map +1 -1
  30. package/dist/middleware/index.mjs +164 -12
  31. package/dist/middleware/index.mjs.map +1 -1
  32. package/dist/nestjs/index.js.map +1 -1
  33. package/dist/nestjs/index.mjs.map +1 -1
  34. package/dist/node/index.d.cts +15 -4
  35. package/dist/node/index.d.ts +15 -4
  36. package/dist/node/index.js +186 -14
  37. package/dist/node/index.js.map +1 -1
  38. package/dist/node/index.mjs +185 -15
  39. package/dist/node/index.mjs.map +1 -1
  40. package/dist/{oidcState-C3VLn3eD.d.ts → oidcState-CZhj0MBP.d.ts} +123 -5
  41. package/dist/{oidcState-BaJ-SM_R.d.cts → oidcState-EnEJmoF5.d.cts} +123 -5
  42. package/dist/rest/index.d.cts +6 -6
  43. package/dist/rest/index.d.ts +6 -6
  44. package/dist/rest/index.js +26 -5
  45. package/dist/rest/index.js.map +1 -1
  46. package/dist/rest/index.mjs +26 -5
  47. package/dist/rest/index.mjs.map +1 -1
  48. package/dist/{session-B03NsqVs.d.ts → session-Beo11VT_.d.ts} +9 -0
  49. package/dist/{session-plDr4lFu.d.cts → session-CeIUXgpE.d.cts} +9 -0
  50. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/errors.ts","../../src/core/sensitive.ts","../../src/core/config.ts","../../src/core/telemetry.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/transport.ts","../../src/amqp/consumer.ts","../../src/amqp/reactor/registry.ts","../../src/amqp/reactor/protocol.ts","../../src/amqp/reactor/runtime.ts","../../src/amqp/reactor/handlers.ts"],"names":["createHmac","timingSafeEqual","amqp","randomUUID","createHash"],"mappings":";;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAiHO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string = '') {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// 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","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\nimport type { TelemetryHook } from './telemetry.js';\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /**\n * Human-readable organization identifier (CONTRACT.md §5). Optional at\n * construction, but the server REQUIRES an org context on login — a tenant\n * slug is only unique *within* an organization — so a client that omits both\n * `orgSlug` and `orgId` will fail login with a 400/401. Forwarded as\n * `org_slug` in the login body. Mutually exclusive with {@link orgId}\n * (if both are given, `orgId` wins, mirroring how `tenantSlug`/`tenantId`\n * resolve).\n */\n orgSlug?: string;\n /**\n * Organization UUID (CONTRACT.md §5). Optional at construction (see\n * {@link orgSlug}). When supplied it is forwarded as `org_id` on login and\n * used to build the `refresh` body; otherwise the resolved organization UUID\n * is decoded from the authenticated session's access-token `org_id` claim\n * after the first successful login. Mutually exclusive with {@link orgSlug}.\n */\n orgId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /**\n * Enable the CONTRACT.md §16 bounded read-only retry policy. **Default:\n * `true`.**\n *\n * Set `false` to make every operation exactly one attempt. That is the right\n * choice for a caller who owns their own retry layer — they know their\n * deadline and this SDK does not — but it is not a way to make failures\n * quieter: a transient `NetworkError` simply surfaces immediately.\n *\n * §16.1 permits this switch but forbids raising the attempt cap, base delay\n * or delay cap above the contract's values, so there is no knob for those:\n * eleven SDKs agreeing on one table is the point.\n */\n retryEnabled?: boolean;\n /**\n * Enable the CONTRACT.md §17 client-side decision memo, in milliseconds.\n * **Default: `0`, which means disabled** — not \"cache for zero milliseconds\".\n *\n * ## What you are accepting\n *\n * The staleness bound is this TTL, **in both directions**. A grant revoked on\n * the server can still read as allowed for up to the TTL, and a grant just\n * added can still read as denied for up to the TTL.\n *\n * **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role\n * and immediately re-checks is the case that breaks, and it breaks silently.\n * If that is your workload, leave this off.\n *\n * Clamped to 5000 ms rather than rejected, so asking for a minute gets you\n * five seconds. Allows and denies are memoized identically (asymmetric\n * caching leaks the outcome through latency), failures are never memoized,\n * and the memo is cleared on any credential change.\n */\n decisionMemoTtlMs?: number;\n /**\n * Install a CONTRACT.md §19 telemetry sink.\n *\n * Receives request start/end, §16 retry and §9 refresh events, so metrics can\n * be wired without this package depending on any metrics library. See\n * `examples/telemetry-hook.ts`.\n *\n * A hook that throws cannot fail the operation that fired it (§19.2 rule 2),\n * and no event payload can carry a token — {@link TelemetryEvent} is a closed\n * union with a fixed field set (§19.2 rule 3). Invoked on the calling path,\n * so it must not block; buffer on your side if you need async delivery.\n */\n telemetryHook?: TelemetryHook;\n /**\n * PEM-encoded client-certificate chain for mutual TLS (§6.1). Presented to\n * the server to authenticate an IoT device / service account. MUST be\n * provided together with {@link AxiamClientOptions.clientKey}. Node only —\n * ignored in the browser (browsers cannot present a client certificate from\n * JS). Presenting a client certificate NEVER relaxes server verification.\n */\n clientCert?: string;\n /**\n * PEM-encoded private key (PKCS#8 or PKCS#1) matching {@link\n * AxiamClientOptions.clientCert} (§6.1). Secret material: it is passed\n * straight to the Node TLS stack and is never retained on a public property,\n * logged, or serialized (§7). MUST be provided together with `clientCert`.\n * Node only — ignored in the browser.\n */\n clientKey?: string;\n /**\n * Expected `iss` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 5). Optional and unset by default — the rule is conditional on\n * configuration, and the SDK never hardcodes an issuer. When set, the §10\n * middleware rejects a token whose `iss` differs.\n */\n expectedIssuer?: string;\n /**\n * Expected `aud` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 6). Optional and unset by default. A resource server guarding\n * user-facing routes SHOULD set `\"axiam:user\"`; a machine-to-machine one\n * `\"axiam:m2m\"`. When set, the §10 middleware rejects a token whose `aud`\n * does not contain it.\n */\n expectedAudience?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n /**\n * Act on another tenant of the caller's organization from construction —\n * CONTRACT.md §5.2 rule 1 (contract 1.51). Every `/api/v1` REST request\n * then also carries `X-Axiam-Tenant: <this value>`, distinct from the\n * `X-Tenant-ID` header {@link tenantSlug}/{@link tenantId} controls, which\n * is unaffected.\n *\n * Meaningful only for an **organization-level** principal; the server\n * answers `403` for an ordinary tenant principal. Construction cannot gate\n * on that — it precedes the login that would reveal it — so only the UUID\n * shape is checked here, client-side, with no wire call; a client already\n * holding a login result should prefer the on-client {@link\n * AxiamClient.actingTenant}, which also gates on `organizationLevel` and\n * `reachableTenantIds`. REST-only: the gRPC interceptor sends no\n * acting-tenant metadata.\n */\n actingTenantId?: string;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** PEM header that must appear in a certificate chain (§6/§6.1). */\nexport const CERT_PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * PEM header for a private key — PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1\n * (`BEGIN RSA PRIVATE KEY`), or an EC key (`BEGIN EC PRIVATE KEY`) (§6.1).\n */\nconst PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;\n\n/**\n * A validated mTLS client identity (§6.1). The private key is held behind\n * {@link Sensitive} so it can never leak through a debug/log/serialize path\n * (§7); call `key.expose()` only at the point of handing it to the TLS stack.\n */\nexport interface ClientIdentity {\n /** PEM certificate chain (not secret). */\n cert: string;\n /** PEM private key, redaction-wrapped (§7). */\n key: Sensitive<string>;\n}\n\n/**\n * Validate the §6.1 client-certificate options and, when configured, return\n * the resolved identity. Throws at construction time (consistent with §6's\n * PEM-only rule) when:\n * - exactly one of clientCert/clientKey is present (they are all-or-nothing);\n * - clientCert is not a PEM certificate chain;\n * - clientKey is not a PEM private key.\n *\n * Returns `undefined` when neither is configured. This validation runs on\n * every persona (including the browser, which then ignores the identity) so\n * construction fails fast and identically everywhere.\n */\nexport function resolveClientIdentity(options: {\n clientCert?: string;\n clientKey?: string;\n}): ClientIdentity | undefined {\n const hasCert = options.clientCert !== undefined;\n const hasKey = options.clientKey !== undefined;\n if (hasCert !== hasKey) {\n throw new Error(\n 'clientCert and clientKey must be provided together for mutual TLS ' +\n '(one was given without the other) (CONTRACT.md §6.1).',\n );\n }\n if (!hasCert || !hasKey) {\n return undefined;\n }\n if (!options.clientCert!.includes(CERT_PEM_MARKER)) {\n throw new Error(\n 'clientCert must be a PEM-encoded certificate chain (expected to contain ' +\n '\"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6.1).',\n );\n }\n if (!PRIVATE_KEY_PEM_RE.test(options.clientKey!)) {\n throw new Error(\n 'clientKey must be a PEM-encoded private key (expected to contain ' +\n '\"-----BEGIN PRIVATE KEY-----\" or \"-----BEGIN RSA PRIVATE KEY-----\") ' +\n '(CONTRACT.md §6.1).',\n );\n }\n return { cert: options.clientCert!, key: new Sensitive(options.clientKey!) };\n}\n","// Telemetry hooks — CONTRACT.md §19.\n//\n// An optional callback surface so callers can wire OpenTelemetry, Prometheus,\n// or a log line **without this package depending on any of them**. No hook\n// installed costs one undefined check per request.\n//\n// Two rules from §19.2 are enforced here rather than left to documentation:\n//\n// * A hook cannot break the SDK. `TelemetryDispatcher.emit` swallows anything\n// a sink throws, so a broken hook cannot fail an authorization check.\n// * No secrets, ever. `TelemetryEvent` is a closed discriminated union with a\n// fixed field set and no index signature, so there is no way to put a token\n// into a payload bound for a metrics backend. The type system, not a review\n// comment, is what keeps them out.\n\n/** Why a request finished. */\nexport type Outcome = 'success' | 'failure';\n\n/** Whether this caller performed a §9 refresh or waited on another's. */\nexport type RefreshRole = 'leader' | 'follower';\n\n/** Emitted before an outbound call leaves the SDK. */\nexport interface RequestStartEvent {\n /** Discriminant. */\n type: 'requestStart';\n /** Canonical operation name, e.g. `checkAccess`. */\n operation: string;\n /** HTTP method. */\n method: string;\n /**\n * Path **template** — `/api/v1/authz/check`, never a URL with ids\n * substituted in. A metric label carrying a UUID is a cardinality bomb.\n */\n pathTemplate: string;\n /** 1 for the first attempt, incrementing per §16 retry. */\n attempt: number;\n}\n\n/** Emitted after a call completes, success or failure. */\nexport interface RequestEndEvent {\n /** Discriminant. */\n type: 'requestEnd';\n /** Canonical operation name. */\n operation: string;\n /** HTTP method. */\n method: string;\n /** Path template — see {@link RequestStartEvent.pathTemplate}. */\n pathTemplate: string;\n /** Attempt this event closes. */\n attempt: number;\n /** HTTP status, or `undefined` when the call never got a response. */\n status?: number;\n /** Wall-clock duration of this attempt, in milliseconds. */\n durationMs: number;\n /** Success or failure. */\n outcome: Outcome;\n}\n\n/**\n * Emitted before each §16 retry wait.\n *\n * §16.5 requires this: a retried-then-succeeded operation is otherwise\n * invisible — the caller sees a slow success and no signal that the server is\n * failing. That silence is the standing objection to automatic retry.\n */\nexport interface RetryEvent {\n /** Discriminant. */\n type: 'retry';\n /** Canonical operation name. */\n operation: string;\n /** The attempt that just failed. */\n attempt: number;\n /** The delay about to be taken, after jitter and any `Retry-After`. */\n delayMs: number;\n /** Redacted failure description. Never carries a token (§2 redaction rules). */\n reason: string;\n}\n\n/** Emitted around a §9 single-flight refresh. */\nexport interface RefreshEvent {\n /** Discriminant. */\n type: 'refresh';\n /** Whether this caller performed the refresh or waited on another's. */\n role: RefreshRole;\n /** How long the refresh (or the wait for one) took, in milliseconds. */\n durationMs: number;\n}\n\n/**\n * Emitted at construction, once per caller-supplied setting the SDK clamped\n * (§19.1, §19.2 rule 6).\n *\n * Two places in the contract require clamping rather than rejecting: §16.1's\n * attempt cap, base delay and delay cap, and §17.1 rule 2's memo TTL. Both\n * clamps are right — rejecting would break a caller whose configuration was\n * merely optimistic, and honoring would let one client become the herd §16\n * exists to prevent. Doing it *silently* is the part that is wrong.\n *\n * An operator who set a 60-second memo TTL believes they have one. They have\n * five seconds, and their staleness reasoning is off by a factor of twelve with\n * nothing anywhere to say so.\n *\n * Not emitted for a value already within its limit: an event that fires when\n * nothing happened trains its reader to ignore it.\n */\nexport interface ConfigClampedEvent {\n /** Discriminant. */\n type: 'configClamped';\n /** The setting's name, e.g. `decisionMemoTtlMs`. */\n setting: string;\n /** The value the caller asked for, rendered. */\n requested: string;\n /** The value actually in force, rendered. */\n effective: string;\n /** The §-reference for the limit, e.g. `§17.1 rule 2`. */\n contractReference: string;\n}\n\n/** Why an SSF poll left SETs unjudged: the JWKS (or discovery) fetch, or the replay store. */\nexport type SsfUnjudgedCategory = 'key_fetch' | 'replay_store';\n\n/**\n * Emitted when `SsfReceiver.poll` returns normally leaving at least one SET\n * unjudged (contract 1.60, §19.1's SHOULD; §34.2 P1) — one event per failure\n * category present in the batch.\n *\n * A poll that accepted some SETs cannot raise without losing them, so it\n * returns and lists the rest in `unjudged`; this event is what makes that\n * outage visible to an operator who never inspects the list. It carries a\n * count, never a `jti` or a SET.\n */\nexport interface SsfUnjudgedEvent {\n /** Discriminant. */\n type: 'ssfUnjudged';\n /** Canonical operation name: `ssf.poll`. */\n operation: string;\n /** How many SETs of the batch this category left unjudged. */\n count: number;\n /** The failure that left them unjudged. */\n category: SsfUnjudgedCategory;\n}\n\n/** A §19 telemetry event. Closed union — see the file header for why. */\nexport type TelemetryEvent =\n | RequestStartEvent\n | RequestEndEvent\n | RetryEvent\n | RefreshEvent\n | ConfigClampedEvent\n | SsfUnjudgedEvent;\n\n/**\n * A caller-supplied telemetry sink (§19).\n *\n * Invoked on the calling path, so it must not block: §19.2 rule 4 makes\n * buffering the caller's job so they can pick the policy. Every mature metrics\n * library already buffers.\n */\nexport type TelemetryHook = (event: TelemetryEvent) => void;\n\n/**\n * Internal dispatcher. `undefined` is the overwhelmingly common case and costs\n * one check.\n */\nexport class TelemetryDispatcher {\n constructor(private readonly hook?: TelemetryHook) {}\n\n /**\n * Emit an event, swallowing anything the caller's hook throws.\n *\n * §19.2 rule 2: telemetry is not permitted to fail an authorization check.\n */\n emit(event: TelemetryEvent): void {\n if (!this.hook) return;\n try {\n this.hook(event);\n } catch {\n // Deliberately swallowed. A hook that throws is the caller's bug, and\n // surfacing it here would turn a metrics problem into an authorization\n // failure.\n }\n }\n\n /** Whether a hook is installed. */\n get installed(): boolean {\n return this.hook !== undefined;\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","// AMQP transport security (CONTRACT.md §8b).\n//\n// HMAC signing (§8) gives authenticity and replay protection. It does not give\n// confidentiality: a signed `AuthzRequest` still names a subject, a resource\n// and an action in cleartext on the wire, and a signed reactor reply is still\n// an instruction to change a token. TLS gives confidentiality; HMAC gives\n// end-to-end authenticity across broker hops, which TLS cannot, because TLS\n// terminates at the broker and the broker then re-sends. §8b's framing is\n// exact: both are required, and neither substitutes for the other.\n//\n// This module is the one place in the SDK that turns a broker URL and some\n// optional PEM material into arguments for `amqplib.connect`. Both AMQP entry\n// points — `consume()` (§8) and `reactorServe()` (§22) — go through it, so\n// there is a single answer to \"what does this SDK accept as a broker URL\"\n// rather than one answer per call site.\n//\n// # Why this file exists at all\n//\n// It is a fix, not a feature. Both entry points previously called\n// `amqp.connect(url)` with no scheme check and no TLS options, while their own\n// doc comments stated that the URL \"must be `amqps://` (§8b) — there is no\n// verification-skip switch and no plaintext fallback\". Every word of that was\n// true of the intent and none of it was true of the code: a plaintext\n// `amqp://` URL connected without complaint, and a privately-issued broker\n// certificate — the common case for an in-cluster broker, and the whole reason\n// §8b rule 2 is a MUST — could not be trusted at all, because there was no way\n// to supply a CA bundle. Documented-but-unenforced is the worst of the three\n// states: it reads as a guarantee at review time and behaves as an invitation\n// at runtime.\n\nimport type { ConnectionOptions as TlsConnectionOptions } from 'node:tls';\nimport { NetworkError } from '../core/errors.js';\nimport { resolveClientIdentity } from '../core/config.js';\n\nconst PEM_CERT_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * TLS material for an `amqps://` broker connection (§8b).\n *\n * Every field is optional: with none set, an `amqps://` URL still connects and\n * still verifies, against Node's bundled root store. The fields exist for the\n * two cases that store cannot serve — a privately-issued broker certificate,\n * and mutual TLS toward the broker.\n *\n * # There is deliberately no verification-skip option\n *\n * Not as an omission to be filled in later. §8b rule 4 forbids surfacing one\n * under any name, and the reasoning is that such a switch is the single most\n * reliably misused option in TLS: it appears in a dev compose file, it works,\n * and it travels unchanged into production, where it turns TLS into an\n * expensive no-op against precisely the attacker TLS exists to stop.\n * {@link caCert} covers the legitimate reason people reach for it (rule 2)\n * without covering the rest.\n *\n * This paragraph names no concrete bypass flag, and that is not squeamishness:\n * CI greps `src/` for the literal disabling forms and fails the build on a hit.\n * A comment explaining why the SDK does not do the thing would trip the same\n * grep as code doing it — the check cannot tell prose from an assignment — so\n * the prose stays abstract and the check stays blunt. Both are better that way.\n *\n * `amqplib` would happily accept `rejectUnauthorized` in its socket options,\n * which is exactly why {@link buildAmqpConnectOptions} constructs that object\n * itself from these three fields rather than accepting a caller-supplied one.\n */\nexport interface AmqpTlsOptions {\n /**\n * PEM bundle of the CA(s) that issued the broker's certificate (§8b rule 2).\n *\n * Unset = verify against Node's bundled roots. Set this when the broker\n * certificate comes from a private CA — including one issued by AXIAM's own\n * organization CA, which is the recommended dogfooding path.\n *\n * Unlike the server's own `AXIAM__AMQP__TLS__CA_CERT_PATH`, this **replaces**\n * the trust set rather than adding to it: Node's `tls.connect` treats `ca` as\n * the complete root list. Supplying your broker's CA here therefore does\n * narrow trust to it, which is usually what someone setting this actually\n * wants.\n */\n readonly caCert?: string;\n /**\n * PEM client certificate chain, for mutual TLS toward the broker (§8b\n * rule 3).\n *\n * Must be supplied together with {@link clientKey}. Half a client identity is\n * never what anyone meant, and connecting anyway would silently drop the\n * mutual half of mutual TLS — so it is rejected before dialling.\n */\n readonly clientCert?: string;\n /** PEM private key matching {@link clientCert}. Secret material (§7). */\n readonly clientKey?: string;\n}\n\n/**\n * Reject any broker URL that is not `amqps://` (§8b rules 1 and 5).\n *\n * A plaintext URL is refused here rather than downgraded, and there is no\n * fallback path for it to take — rule 5 exists because a fallback that works\n * is a fallback that gets used, and the failure it produces is invisible\n * exactly when it matters.\n *\n * The `://` separator is load-bearing: matching on `amqps` alone would let a\n * hypothetical `amqpsomething://` through.\n *\n * @throws {NetworkError} when `url` is not an `amqps://` URL.\n */\nexport function assertAmqpsUrl(url: string, what = 'AMQP URL'): void {\n if (!url.trim().toLowerCase().startsWith('amqps://')) {\n throw new NetworkError(\n `${what} must use amqps:// (CONTRACT.md §8b rules 1 and 5) — got ` +\n `${JSON.stringify(url)}. Broker traffic carries authorization requests, ` +\n 'audit events and reactor replies across a trust boundary; HMAC signing ' +\n 'gives them authenticity and replay protection, not confidentiality. ' +\n 'There is no plaintext fallback and no verification-skip switch — supply ' +\n \"a private broker CA with `caCert` if the broker's certificate is not \" +\n 'publicly issued.',\n );\n }\n}\n\n/**\n * Validate `url` and build the socket options `amqplib.connect` should dial\n * with (§8b).\n *\n * `amqplib` forwards its second argument to `tls.connect` for an `amqps://`\n * URL, so the returned object is a `tls.ConnectionOptions` carrying at most\n * `ca`, `cert` and `key`. It never carries `rejectUnauthorized`, which leaves\n * Node's strict default (`true`) in force — see {@link AmqpTlsOptions}.\n *\n * The certificate/key pairing is validated by `resolveClientIdentity`, the same\n * §6.1 helper the REST and gRPC transports use, so mutual TLS is validated\n * identically on every transport this SDK speaks rather than once per protocol.\n *\n * @throws {NetworkError} when `url` is not `amqps://`.\n * @throws {Error} when the TLS material is internally inconsistent (a client\n * certificate without its key, or PEM that is not PEM).\n */\nexport function buildAmqpConnectOptions(\n url: string,\n tls: AmqpTlsOptions = {},\n what = 'AMQP URL',\n): TlsConnectionOptions | undefined {\n assertAmqpsUrl(url, what);\n\n if (tls.caCert !== undefined && !tls.caCert.includes(PEM_CERT_MARKER)) {\n throw new Error(\n `caCert must be a PEM-encoded certificate (expected to contain ` +\n `\"${PEM_CERT_MARKER}\") (CONTRACT.md §8b rule 2).`,\n );\n }\n\n // Reuses §6.1's all-or-nothing check and PEM validation rather than\n // re-implementing it: an SDK that validated a client identity two different\n // ways would eventually validate it two different amounts.\n const identity = resolveClientIdentity({\n clientCert: tls.clientCert,\n clientKey: tls.clientKey,\n });\n\n if (tls.caCert === undefined && identity === undefined) {\n // Nothing to configure. `undefined` lets amqplib use its own defaults,\n // which for an amqps:// URL means Node's bundled roots with verification\n // on — the correct behaviour for a publicly-issued broker certificate, and\n // the reason `caCert` is optional rather than required.\n return undefined;\n }\n\n return {\n ...(tls.caCert !== undefined ? { ca: tls.caCert } : {}),\n ...(identity !== undefined\n ? { cert: identity.cert, key: identity.key.expose() }\n : {}),\n };\n}\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';\nimport { buildAmqpConnectOptions, type AmqpTlsOptions } from './transport.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 * TLS material for the `amqps://` broker connection (CONTRACT.md §8b).\n *\n * Optional, and omitting it does not weaken anything: the URL must be\n * `amqps://` either way, and with no material supplied the broker is verified\n * against Node's bundled roots. Set {@link AmqpTlsOptions.caCert} when the\n * broker certificate comes from a private CA — the common case for an\n * in-cluster broker, and the reason §8b rule 2 is a MUST.\n */\n tls?: AmqpTlsOptions;\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 *\n * `amqpUrl` MUST be `amqps://` (CONTRACT.md §8b). It is checked before any\n * socket is opened, so a plaintext URL fails with a message naming the rule\n * rather than connecting and quietly putting signed-but-readable authorization\n * requests and audit events on the wire.\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 // §8b: validated BEFORE dialling. A bad URL or half a client identity is a\n // configuration fault, and finding out at connect time turns it into a\n // network error message that says nothing about what to fix.\n const socketOptions = buildAmqpConnectOptions(amqpUrl, options.tls, 'consume() amqpUrl');\n const connection = await amqp.connect(amqpUrl, socketOptions);\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","// The reactor event registry and its mutable-field allow-lists\n// (CONTRACT.md §22.5, §22.7, §22.8).\n//\n// Mirror, never import. This is the same data as the server's\n// `EVENT_REGISTRY` in `crates/axiam-core/src/models/reactor.rs`, restated here\n// so a reactor author can name an event, ask what it may mutate, and compute a\n// registration's default failure policy without a network call. The live copy\n// is served at `GET /api/v1/reactors/events` and is the one an admin UI SHOULD\n// read; this table is the offline equivalent.\n//\n// What is deliberately absent (§22.7 — normative MUST NOT): `authz.check`,\n// `authz.check_batch` and `token.introspect`. They are not hookable and this\n// SDK does not present them as such — they appear in no constant, no array and\n// no example here. A reactor round-trip is milliseconds; the check path's\n// budget is microseconds. An application that needs external input on an\n// authorization decision writes a deny grant, which the engine evaluates in the\n// hot path at hot-path cost.\n\n/**\n * What the server does when an interceptor produces no usable reply\n * (CONTRACT.md §22.8).\n *\n * \"No usable reply\" is one closed set and every member takes the same path:\n * timeout, transport failure, a budget exhausted before this reactor was\n * reached, the in-flight cap, and every §22.4 rejection — including a valid\n * signature carrying a forbidden patch field.\n */\nexport type FailurePolicy = 'fail_open' | 'fail_closed';\n\n/**\n * How a reactor participates in an event (CONTRACT.md §22.5, §22.9).\n *\n * `listen` is fire-and-forget observation: the server never waits and never\n * reads a reply, so a listener cannot affect any outcome — and\n * {@link reactorServe} publishes nothing at all in that mode.\n */\nexport type ReactorMode = 'intercept' | 'listen';\n\n/**\n * One hookable event: its name, what a reply may change, and what happens when\n * the reactor does not answer (CONTRACT.md §22.5).\n */\nexport interface ReactorEventSpec {\n /** Wire name, and the second half of the routing key (`<tenant_id>.<event>`). */\n readonly name: string;\n /** Whether an interceptor may register for this event at all. */\n readonly interceptable: boolean;\n /** Whether an interceptor's reply may carry a `patch`. */\n readonly mutable: boolean;\n /**\n * The **complete** allow-list. An entry ending in `.` is a namespace prefix\n * — see {@link patchFieldAllowed}.\n */\n readonly mutableFields: readonly string[];\n /** The `failure_policy` a registration gets when it names none. */\n readonly defaultFailurePolicy: FailurePolicy;\n /** One line, as the admin surface shows it. */\n readonly description: string;\n}\n\n/**\n * The five v1 event names.\n *\n * Handlers compare against these rather than string literals so a typo is a\n * type error rather than an event that silently never fires.\n */\nexport const REACTOR_EVENTS = {\n /** Before an access token is minted. Mutable: the `ext.` claim namespace. */\n TOKEN_PRE_ISSUE: 'token.pre_issue',\n /**\n * After credentials verify, before a session is issued. Veto or step-up.\n *\n * Fires on password authentication, on SAML ACS and on the OIDC callback\n * (§22.5, SEC-095). MFA completion and the WebAuthn `authenticate/finish`\n * ceremony are **not** separate firings — both continue a login that was\n * already gated at its first step.\n *\n * The federated paths have no step-up branch, so a `require_mfa` answer on\n * those is **refused** (the sign-in fails) rather than silently dropped: a\n * reactor that needs step-up there answers `deny` and drives enrolment out of\n * band.\n */\n LOGIN_POST_AUTH: 'login.post_auth',\n /** Before a user row is written. Mutable: `username`, `email`, `metadata.`. */\n USER_PRE_CREATE: 'user.pre_create',\n /** Before a user row is updated. Mutable: `username`, `email`, `metadata.`. */\n USER_PRE_UPDATE: 'user.pre_update',\n /** Before a role or permission is assigned. Veto only. */\n GRANT_PRE_ASSIGN: 'grant.pre_assign',\n} as const;\n\n/** The union of the five v1 registry event names. */\nexport type ReactorEventName = (typeof REACTOR_EVENTS)[keyof typeof REACTOR_EVENTS];\n\n/**\n * Every hookable event in v1 — five of them (CONTRACT.md §22.5).\n *\n * The order matches the server's `EVENT_REGISTRY`. Nothing on the authorization\n * hot path appears here, and nothing may be added to it locally: an event\n * outside the registry dispatches to nothing and resolves to `allow`, which is\n * what makes §22.7's exclusion structural rather than advisory.\n */\nexport const EVENT_REGISTRY: readonly ReactorEventSpec[] = [\n {\n name: REACTOR_EVENTS.TOKEN_PRE_ISSUE,\n interceptable: true,\n mutable: true,\n // Custom claims only. `iss`, `sub`, `aud`, `exp`, `iat`, `nbf`, `jti`,\n // `scope`, `scp`, `azp`, `act` and `client_id` are all unreachable because\n // none of them begins with `ext.` — a hook that can rewrite `sub` is a hook\n // that can mint a token for anyone.\n mutableFields: ['ext.'],\n defaultFailurePolicy: 'fail_open',\n description: 'Enrich or veto token issuance. May add claims under `ext.` only.',\n },\n {\n name: REACTOR_EVENTS.LOGIN_POST_AUTH,\n interceptable: true,\n mutable: false,\n mutableFields: [],\n defaultFailurePolicy: 'fail_closed',\n description:\n 'After credentials verify, before session issuance: veto or require step-up MFA.',\n },\n {\n name: REACTOR_EVENTS.USER_PRE_CREATE,\n interceptable: true,\n mutable: true,\n mutableFields: ['username', 'email', 'metadata.'],\n defaultFailurePolicy: 'fail_closed',\n description: \"Validate or normalize a new user's profile fields.\",\n },\n {\n name: REACTOR_EVENTS.USER_PRE_UPDATE,\n interceptable: true,\n mutable: true,\n mutableFields: ['username', 'email', 'metadata.'],\n defaultFailurePolicy: 'fail_closed',\n description: 'Validate or normalize a profile update.',\n },\n {\n name: REACTOR_EVENTS.GRANT_PRE_ASSIGN,\n interceptable: true,\n mutable: false,\n mutableFields: [],\n defaultFailurePolicy: 'fail_closed',\n description: 'Veto a role or permission assignment (four-eyes workflows). Veto-only.',\n },\n];\n\n/**\n * Look an event up by wire name. `undefined` for anything outside the registry\n * — including the three hot-path operations §22.7 excludes.\n */\nexport function eventSpec(name: string): ReactorEventSpec | undefined {\n return EVENT_REGISTRY.find((spec) => spec.name === name);\n}\n\n/**\n * Whether `field` may appear in a `patch` for `spec` (CONTRACT.md §22.5).\n *\n * An allow-list entry ending in `.` is a **namespace prefix**, and it matches a\n * field that starts with the entry and has **at least one character after the\n * dot**. So `ext.` admits `ext.department` and `ext.a.b.c`, and refuses `ext.`\n * itself (it names the namespace, not a claim), `ext` (not in the namespace),\n * `extra` / `external_id` (a prefix match on the *string* is not a match on the\n * namespace) and `evil.ext.department` (not a suffix match either).\n *\n * ## This is a lookup, not a filter\n *\n * It exists so a handler can check its own patch before returning it.\n * {@link reactorServe} does **not** call it to prune a patch: §22.4 rule 1 and\n * §22.10 rule 3 forbid filtering a handler's patch down to the allowed subset,\n * because one forbidden key rejects the *whole* patch server-side and dropping\n * it silently would leave the author believing a field was set when it was not.\n */\nexport function patchFieldAllowed(spec: ReactorEventSpec, field: string): boolean {\n if (!spec.mutable) return false;\n return spec.mutableFields.some((allowed) =>\n allowed.endsWith('.')\n ? field.length > allowed.length && field.startsWith(allowed)\n : field === allowed,\n );\n}\n\n/**\n * The `failure_policy` a registration gets when it names none: **the strictest\n * default among its events** (CONTRACT.md §22.8).\n *\n * A reactor registered for both `token.pre_issue` (open) and `login.post_auth`\n * (closed) can veto a login, so it inherits `fail_closed` — **in either array\n * order**. Reimplementing this as \"take the first event's default\" would let\n * the order of a JSON array decide whether an unreachable fraud check passes.\n *\n * An unknown event name contributes `fail_closed`: it will be refused at\n * registration anyway, and guessing `fail_open` for a name this SDK does not\n * recognise is the one guess that could weaken a decision. An empty list is\n * likewise `fail_closed` — a registration with no events is invalid, not\n * permissive.\n */\nexport function defaultFailurePolicyFor(eventNames: readonly string[]): FailurePolicy {\n if (eventNames.length === 0) return 'fail_closed';\n for (const name of eventNames) {\n const spec = eventSpec(name);\n if (!spec || spec.defaultFailurePolicy === 'fail_closed') return 'fail_closed';\n }\n return 'fail_open';\n}\n\n/** Default `timeout_ms` when a registration does not name one (§22.8). */\nexport const DEFAULT_REACTOR_TIMEOUT_MS = 500;\n\n/** Lowest accepted `timeout_ms` at registration (§22.8). `0` is refused. */\nexport const MIN_REACTOR_TIMEOUT_MS = 1;\n\n/**\n * Hard ceiling on a registration's `timeout_ms`, and on the whole chain's wall\n * clock (§22.8). A reactor that needs longer than five seconds to answer is not\n * an interceptor, it is an outage.\n */\nexport const MAX_REACTOR_TIMEOUT_MS = 5_000;\n\n/**\n * Per-tenant in-flight interception cap, enforced server-side with a\n * non-blocking acquire (§22.8). Stated here so a reactor author sizing a worker\n * pool knows the ceiling they are working under.\n */\nexport const DEFAULT_REACTOR_MAX_IN_FLIGHT = 64;\n","// The reactor wire protocol — the signed event and the signed reply\n// (CONTRACT.md §22.1–§22.4).\n//\n// Mirror, never import. These shapes reproduce the field order and serde\n// behaviour of the server's `ReactorEventMessage` / `ReactorReply`\n// (`crates/axiam-amqp/src/reactor/protocol.rs`) byte-for-byte using only Node\n// built-ins. `testdata/reactor_v2_reference_vectors.json` — generated by the\n// server's own sign path — is what pins them.\n//\n// ## The one canonicalization difference that will cost you a day\n//\n// §8's own two message types (`AuthzRequest`, `AuditEventMessage`) sign a body\n// with `hmac_signature` OMITTED. A reactor event and a reactor reply sign it\n// SERIALIZED AS `null`:\n//\n// {\"correlation_id\":\"…\",\"tenant_id\":\"…\", … ,\"hmac_signature\":null}\n// ^^^^ present\n//\n// Everything else about §8 v2 is unchanged: the HKDF-derived per-tenant subkey,\n// HMAC-SHA256 hex-encoded and compared in constant time, `key_version = 2` as a\n// hard floor, a ±300 s freshness window checked in BOTH directions, and a fresh\n// UUIDv4 `nonce` inside the signed bytes.\n//\n// ## The second thing that will cost you a day, and is TypeScript-specific\n//\n// `Date.prototype.toISOString()` ALWAYS emits three fractional digits\n// (`…T12:00:00.000Z`). The server's `issued_at` is a `chrono::DateTime<Utc>`,\n// which re-serializes with `SecondsFormat::AutoSi` — no fractional part at all\n// when the nanoseconds are zero. So a reply timestamped with a bare\n// `toISOString()` on a whole second is re-serialized by the server as\n// `…T12:00:00Z`, over different bytes than the reactor signed, and the\n// signature fails with no other symptom. {@link toChronoRfc3339} is the fix and\n// it is not optional.\n\nimport { createHash, randomUUID } from 'node:crypto';\nimport { signPayload, verifyPayload } from '../hmac.js';\nimport { eventSpec, type ReactorEventSpec } from './registry.js';\n\n/** Topic exchange every reactor event is published to (§22.1). */\nexport const REACTOR_EXCHANGE = 'axiam.reactor.events';\n\n/**\n * Envelope key version this SDK emits, and the floor it accepts (§22.2). A body\n * carrying less than this is refused before anything else about it is\n * considered.\n */\nexport const REACTOR_KEY_VERSION = 2;\n\n/**\n * Freshness window for `issued_at`, in milliseconds, in **both** directions\n * (§22.2). A future timestamp is not \"extra fresh\" — it is the shape of a\n * captured message held for later.\n */\nexport const REACTOR_FRESHNESS_SKEW_MS = 300_000;\n\n/**\n * The routing key an event is published with: `<tenant_id>.<event>` (§22.1).\n *\n * Stated so an SDK can assert against it; a reactor runtime never *binds* with\n * it. See {@link reactorQueueName}.\n */\nexport function reactorRoutingKey(tenantId: string, event: string): string {\n return `${tenantId}.${event}`;\n}\n\n/**\n * The durable per-reactor queue name:\n * `axiam.reactor.q.<tenant_id>.<reactor_id>` (§22.1).\n *\n * **The server declares this queue; a reactor only consumes from it.** This SDK\n * derives the name for the reactor it is configured as and for no other: a\n * reactor that can declare and bind is a reactor that can bind itself to\n * `*.token.pre_issue` and read another tenant's issuance events, and refusing to\n * hold that capability at all is cheaper than proving each actor does not misuse\n * it.\n */\nexport function reactorQueueName(tenantId: string, reactorId: string): string {\n return `axiam.reactor.q.${tenantId}.${reactorId}`;\n}\n\n/**\n * Render `date` the way the server's `chrono::DateTime<Utc>` serializes it:\n * RFC 3339, UTC, with **no** fractional part when the milliseconds are zero and\n * exactly three digits otherwise.\n *\n * This is not cosmetic. The server verifies a reply by re-serializing the body\n * it parsed, so a timestamp this SDK wrote as `…T12:00:00.000Z` comes back out\n * as `…T12:00:00Z` — different bytes, different MAC, and a `bad_signature`\n * rejection with nothing in the payload to explain it.\n */\nexport function toChronoRfc3339(date: Date): string {\n const iso = date.toISOString();\n return iso.endsWith('.000Z') ? `${iso.slice(0, -5)}Z` : iso;\n}\n\n/** `true` when `issuedAt` lies within `±skewMs` of `now` — both directions. */\nexport function isFresh(issuedAtMs: number, nowMs: number, skewMs: number): boolean {\n return Math.abs(nowMs - issuedAtMs) <= skewMs;\n}\n\n// ---------------------------------------------------------------------------\n// Event (server → reactor)\n// ---------------------------------------------------------------------------\n\n/**\n * One hook firing, delivered to a reactor (CONTRACT.md §22.3).\n *\n * Field order is load-bearing: it is the order the server serializes, and\n * therefore the order the canonical signed bytes carry.\n */\nexport interface ReactorEvent {\n /**\n * The tenant this firing belongs to. The signing subkey is derived from it,\n * so an event cannot be replayed into another tenant.\n */\n readonly tenant_id: string;\n /** A registry name (§22.5) — also the second half of the routing key. */\n readonly event: string;\n /**\n * The single-use handle for this dispatch. The runtime echoes it into the\n * reply **body**; copying it only into the AMQP property produces a reply the\n * server discards.\n */\n readonly correlation_id: string;\n /**\n * Event-specific body. Never carries a credential, a token, or a signing key\n * — a reactor is told *what is being decided*, not handed the means to act on\n * it elsewhere.\n *\n * On a chained event this object also carries `_reactor_patch`, the patch an\n * earlier reactor in the chain already returned (§22.3). Treat it as\n * **read-only context**: echoing it back inside your own `patch` is not how a\n * field is preserved — the server merges (§22.6).\n */\n readonly payload: Record<string, unknown>;\n /**\n * How long the server will actually wait for *this* dispatch, in\n * milliseconds. Inside the signed body, so it cannot be widened in transit.\n *\n * §22.3 sends it so an actor can shed load rather than answer into a closed\n * window: a late reply is discarded, and the CPU spent producing it was spent\n * for nothing.\n */\n readonly timeout_ms: number;\n /** §8 v2 envelope key version. Always `2` or higher. */\n readonly key_version: number;\n /** Fresh UUIDv4 per message, inside the signed bytes. */\n readonly nonce: string;\n /** Producer-side send time, RFC 3339, for the freshness gate. */\n readonly issued_at: string;\n /** HMAC-SHA256 over this body with the field serialized as `null`. */\n readonly hmac_signature: string | null;\n}\n\n/**\n * Why a delivered event was not usable, in the order §22.3 requires the checks\n * to run.\n */\nexport type EventRejection =\n /** The body is not a JSON object, or is missing a mandatory field. */\n | 'malformed'\n /**\n * `key_version` below the §8 v2 floor — refused **before** the signature is\n * even computed.\n */\n | 'key_version_too_old'\n /** Missing or wrong MAC. */\n | 'bad_signature'\n /** `issued_at` outside ±skew, in either direction. */\n | 'stale'\n /** This `nonce` was already seen inside the freshness window. */\n | 'replayed_nonce';\n\n/**\n * Why the server would not use a reply (CONTRACT.md §22.4).\n *\n * Every member resolves to the registration's `failure_policy` and every member\n * is audited: a rejected reply is **not** a softer failure than no reply at all.\n * This SDK exposes the taxonomy so a reactor author can assert against it and\n * read it in a log line, and refuses locally only what it can detect without\n * guessing (see {@link reactorServe}).\n */\nexport type ReplyRejection =\n | 'wrong_correlation'\n | 'tenant_mismatch'\n | 'event_mismatch'\n | 'key_version_too_old'\n | 'stale'\n | 'bad_signature'\n | 'require_mfa_not_supported'\n | 'not_mutable'\n | 'forbidden_patch_field'\n | 'malformed_mutation';\n\n/**\n * The canonical bytes of a delivered event: the body exactly as it arrived,\n * with `hmac_signature` **set to `null` in place** (§22.2).\n *\n * Setting the value rather than deleting the key is the whole difference from\n * §8's own two message types, and re-serializing the *parsed* body (rather than\n * a rebuilt struct) is what makes the payload's own key order and nesting\n * reproduce byte-for-byte — `JSON.parse` preserves insertion order for string\n * keys, and assigning to an existing key keeps its position.\n *\n * Returns `undefined` when the body carries no `hmac_signature` at all: an\n * unsigned event is not a weak event, it is not an event, and inserting the key\n * ourselves would put it in the wrong position anyway.\n */\nexport function canonicalEventBytes(body: Record<string, unknown>): Buffer | undefined {\n if (!('hmac_signature' in body)) return undefined;\n const canonical: Record<string, unknown> = { ...body, hmac_signature: null };\n return Buffer.from(JSON.stringify(canonical), 'utf8');\n}\n\n/** A successfully verified event, or the reason it was refused. */\nexport type VerifyEventResult =\n | { ok: true; event: ReactorEvent }\n | { ok: false; rejection: EventRejection };\n\n/**\n * Verify a delivered event and decode it, in the order §22.3 fixes:\n * **`key_version`, then the MAC, then freshness**. The fourth check, the nonce\n * seen-set, is the runtime's rather than this function's, because it is state\n * rather than a property of the message.\n *\n * A runtime that hands an unverified payload to user code has already lost: the\n * handler will act on it, and \"we checked afterwards\" is not a check.\n */\nexport function verifyEvent(\n body: Record<string, unknown>,\n signingKey: Buffer,\n nowMs: number = Date.now(),\n skewMs: number = REACTOR_FRESHNESS_SKEW_MS,\n): VerifyEventResult {\n // 1. key_version, before anything else about the body is considered.\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || !Number.isInteger(keyVersion)) {\n return { ok: false, rejection: 'malformed' };\n }\n if (keyVersion < REACTOR_KEY_VERSION) {\n return { ok: false, rejection: 'key_version_too_old' };\n }\n\n // 2. the MAC, over the body with hmac_signature serialized as null.\n const signature = body.hmac_signature;\n if (typeof signature !== 'string') {\n return { ok: false, rejection: 'bad_signature' };\n }\n const canonical = canonicalEventBytes(body);\n if (!canonical || !verifyPayload(signingKey, canonical, signature)) {\n return { ok: false, rejection: 'bad_signature' };\n }\n\n // Only now is the body's shape trusted enough to read.\n if (\n typeof body.tenant_id !== 'string' ||\n typeof body.event !== 'string' ||\n typeof body.correlation_id !== 'string' ||\n typeof body.nonce !== 'string' ||\n typeof body.issued_at !== 'string' ||\n typeof body.timeout_ms !== 'number' ||\n typeof body.payload !== 'object' ||\n body.payload === null ||\n Array.isArray(body.payload)\n ) {\n return { ok: false, rejection: 'malformed' };\n }\n\n // 3. freshness, in both directions.\n const issuedAtMs = Date.parse(body.issued_at);\n if (Number.isNaN(issuedAtMs) || !isFresh(issuedAtMs, nowMs, skewMs)) {\n return { ok: false, rejection: 'stale' };\n }\n\n return {\n ok: true,\n event: {\n tenant_id: body.tenant_id,\n event: body.event,\n correlation_id: body.correlation_id,\n payload: body.payload as Record<string, unknown>,\n timeout_ms: body.timeout_ms,\n key_version: keyVersion,\n nonce: body.nonce,\n issued_at: body.issued_at,\n hmac_signature: signature,\n },\n };\n}\n\n/**\n * The accumulated patch an earlier reactor in the chain returned, if this is a\n * chained dispatch (§22.3's `_reactor_patch`).\n *\n * Read-only context: it tells you what the state will be if the chain commits,\n * so you can decide against that rather than against the original. It is **not**\n * something to copy into your own patch.\n */\nexport function chainedPatch(event: ReactorEvent): unknown {\n return event.payload._reactor_patch;\n}\n\n/** The registry spec for an event's name, if this SDK knows it. */\nexport function specForEvent(event: ReactorEvent): ReactorEventSpec | undefined {\n return eventSpec(event.event);\n}\n\n// ---------------------------------------------------------------------------\n// Reply (reactor → server)\n// ---------------------------------------------------------------------------\n\n/** The closed set of decision values (§22.4). Lowercase on the wire. */\nexport type ReplyDecision = 'allow' | 'deny' | 'mutate';\n\n/**\n * A reactor's answer to one event (CONTRACT.md §22.4), as it appears on the\n * wire.\n *\n * The three conditionally-present fields are load-bearing. A reply that\n * serializes `\"require_mfa\": false` rather than omitting it produces different\n * canonical bytes and therefore a different MAC — the omission rule, not just\n * the values, is part of the wire format. {@link buildReactorReply} is what\n * enforces it; do not assemble one of these by hand.\n */\nexport interface ReactorReply {\n readonly correlation_id: string;\n readonly tenant_id: string;\n readonly event: string;\n readonly decision: ReplyDecision;\n /** Audited on a `deny`. **Omitted when absent.** */\n readonly reason?: string;\n /** Flat `string → string` map, sorted by key. **Omitted when absent.** */\n readonly patch?: Record<string, string>;\n /** `login.post_auth` only. **Omitted when `false`.** */\n readonly require_mfa?: true;\n readonly key_version: number;\n /**\n * A **fresh** UUIDv4 per reply. It is inside the signed bytes, so a unique one\n * is what keeps two replies from being byte-identical — which is what makes a\n * captured reply distinguishable from a fresh one. Emitting a constant nonce\n * removes the only uniqueness a reply body carries beyond its timestamp.\n */\n readonly nonce: string;\n readonly issued_at: string;\n readonly hmac_signature: string | null;\n}\n\n/** What {@link buildReactorReply} needs beyond the event it answers. */\nexport interface ReplyInput {\n readonly decision: ReplyDecision;\n readonly reason?: string;\n readonly patch?: Record<string, string>;\n readonly requireMfa?: boolean;\n /** Overridable for tests; defaults to a fresh UUIDv4 per reply. */\n readonly nonce?: string;\n /** Overridable for tests; defaults to now. */\n readonly issuedAt?: Date;\n}\n\n/**\n * Build an **unsigned** reply answering `event`, with `correlation_id`,\n * `tenant_id` and `event` copied from the event body (§22.1, §22.4), in the\n * server's field order and with every omission rule applied.\n *\n * The patch's keys are emitted in sorted order, because the server's `patch` is\n * a `BTreeMap` and the signed bytes are the sorted rendering.\n */\nexport function buildReactorReply(\n event: Pick<ReactorEvent, 'correlation_id' | 'tenant_id' | 'event'>,\n input: ReplyInput,\n): ReactorReply {\n // Assembled by assignment, in declaration order, because JSON.stringify\n // serializes string keys in insertion order and that order IS the wire format.\n const reply: Record<string, unknown> = {\n correlation_id: event.correlation_id,\n tenant_id: event.tenant_id,\n event: event.event,\n decision: input.decision,\n };\n // `reason` and `patch` are omitted when absent — not emitted as null.\n if (input.reason !== undefined) reply.reason = input.reason;\n if (input.patch !== undefined) reply.patch = sortedPatch(input.patch);\n // `require_mfa` is omitted when false. A reply carrying `false` explicitly\n // signs different bytes and its MAC will not verify.\n if (input.requireMfa === true) reply.require_mfa = true;\n reply.key_version = REACTOR_KEY_VERSION;\n reply.nonce = input.nonce ?? randomUUID();\n reply.issued_at = toChronoRfc3339(input.issuedAt ?? new Date());\n reply.hmac_signature = null;\n return reply as unknown as ReactorReply;\n}\n\n/** A patch object whose keys iterate in sorted order (the server's `BTreeMap`). */\nfunction sortedPatch(patch: Record<string, string>): Record<string, string> {\n const sorted: Record<string, string> = {};\n for (const key of Object.keys(patch).sort()) {\n sorted[key] = patch[key] as string;\n }\n return sorted;\n}\n\n/**\n * The exact bytes a reply is signed over: itself, in declaration order, with\n * `hmac_signature` set to `null`.\n *\n * Clearing the field here rather than asking the caller to remember is what\n * makes it impossible to sign over a body that already contains a signature.\n */\nexport function canonicalReplyBytes(reply: ReactorReply): Buffer {\n const unsigned: Record<string, unknown> = { ...reply, hmac_signature: null };\n return Buffer.from(JSON.stringify(unsigned), 'utf8');\n}\n\n/**\n * Sign a reply with the tenant's derived AMQP subkey, returning a new object\n * carrying the MAC. The input is not mutated.\n */\nexport function signReactorReply(reply: ReactorReply, signingKey: Buffer): ReactorReply {\n const signature = signPayload(signingKey, canonicalReplyBytes(reply));\n return { ...reply, hmac_signature: signature };\n}\n\n/**\n * Verify a reply's own signature — the check the server performs, exposed so an\n * SDK test (or a proxy) can run it locally.\n */\nexport function reactorReplySignatureValid(reply: ReactorReply, signingKey: Buffer): boolean {\n if (typeof reply.hmac_signature !== 'string') return false;\n return verifyPayload(signingKey, canonicalReplyBytes(reply), reply.hmac_signature);\n}\n\n/**\n * HKDF-SHA256 is **not** performed by this SDK: §8.1 assumes the per-tenant\n * subkey is provisioned out of band, and {@link reactorServe} takes that\n * already-derived key. This helper exists only so a caller can fingerprint the\n * key they were handed for an operational log without ever printing it.\n *\n * The digest is truncated to eight hex characters — enough to tell two keys\n * apart in a log line, far too little to attack.\n */\nexport function signingKeyFingerprint(signingKey: Buffer): string {\n return createHash('sha256').update(signingKey).digest('hex').slice(0, 8);\n}\n","// `reactorServe` — the SDK reactor runtime (CONTRACT.md §22.10).\n//\n// One helper. It connects (TLS per §8b and §6), consumes the SERVER-DECLARED\n// queue, and for each delivery: verifies §8 v2 (`key_version`, MAC, freshness,\n// nonce), decodes the event, dispatches to a user-supplied handler, then signs\n// and publishes the reply. It drains in-flight events on shutdown per §18.\n//\n// ## The four rules on the helper itself (§22.10)\n//\n// 1. It declares no topology. There is no `assertQueue`, `assertExchange` or\n// `bindQueue` anywhere in this module, and the channel seam it is written\n// against (`ReactorChannel`) exposes no such operation — so the rule is\n// structural rather than remembered. A reactor that can bind is a reactor\n// that can bind itself to `*.token.pre_issue`.\n// 2. It fails closed on its own errors. A handler that throws, a payload that\n// will not decode, a window that has already closed — every one of them\n// produces NO REPLY, letting the server's `failure_policy` decide.\n// Answering `allow` on behalf of a handler that crashed would override the\n// operator's `fail_closed` setting from inside the library.\n// 3. It does not filter a patch. A handler's patch is published exactly as\n// returned, forbidden keys and all (§22.4 rule 1).\n// 4. It honours `timeout_ms`. The handler runs under the event's own window,\n// and a reply whose window has closed is abandoned rather than published\n// late.\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../../core/index.js';\nimport { TelemetryDispatcher, type TelemetryHook } from '../../core/index.js';\nimport { InMemoryNonceStore, type NonceStore } from '../consumer.js';\nimport { buildAmqpConnectOptions, type AmqpTlsOptions } from '../transport.js';\nimport {\n REACTOR_FRESHNESS_SKEW_MS,\n buildReactorReply,\n reactorQueueName,\n signReactorReply,\n verifyEvent,\n type ReactorEvent,\n} from './protocol.js';\nimport { REACTOR_EVENTS, eventSpec, type ReactorMode } from './registry.js';\n\n/** Telemetry operation name for one reactor dispatch (§19.1). */\nconst TELEMETRY_OPERATION = 'reactorDispatch';\n\n// ---------------------------------------------------------------------------\n// The handler's answer\n// ---------------------------------------------------------------------------\n\n/**\n * What a handler decided about one event (CONTRACT.md §22.10).\n *\n * Three answers plus one absence. `allow`, `deny` and `mutate` are the three the\n * wire carries; `abstain` is the *absence* of a reply, which the server resolves\n * through the registration's `failure_policy` (§22.8) exactly as it resolves a\n * timeout.\n *\n * Build one with {@link allow}, {@link requireStepUp}, {@link deny} or\n * {@link mutate} rather than by hand.\n */\nexport type ReactorDecision =\n | {\n readonly kind: 'allow';\n /**\n * Proceed **only after step-up authentication**. `login.post_auth` only —\n * it is not a separate decision value, and sending it on any other event\n * is refused (§22.4 rule 3).\n */\n readonly requireMfa: boolean;\n }\n | {\n readonly kind: 'deny';\n /**\n * Audited reason. A deny with no reason still denies; the server\n * substitutes `\"denied by reactor\"` when it is absent.\n */\n readonly reason?: string;\n }\n | {\n readonly kind: 'mutate';\n /**\n * The fields to set — a flat `string → string` map. Published\n * **unfiltered**: one forbidden key rejects the whole patch server-side,\n * and pruning it here would leave you believing a field was set when it\n * was dropped (§22.4 rule 1). Check it yourself with `patchFieldAllowed`\n * if you want to know before you send.\n */\n readonly patch: Record<string, string>;\n }\n | {\n /**\n * Publish nothing at all.\n *\n * The right answer when the window has already closed (§22.3: shed load\n * rather than answer into a closed window) or when the handler cannot\n * decide. It is **not** a quiet `allow`: the server applies the\n * registration's `failure_policy`, which for every event except\n * `token.pre_issue` defaults to `fail_closed`.\n */\n readonly kind: 'abstain';\n };\n\n/** Proceed unchanged. */\nexport function allow(): ReactorDecision {\n return { kind: 'allow', requireMfa: false };\n}\n\n/** Proceed, but demand step-up authentication first. `login.post_auth` only. */\nexport function requireStepUp(): ReactorDecision {\n return { kind: 'allow', requireMfa: true };\n}\n\n/**\n * Refuse. Pass a reason for the audit trail; omitting it still denies, and the\n * audit record reads `\"denied by reactor\"`.\n */\nexport function deny(reason?: string): ReactorDecision {\n return reason === undefined ? { kind: 'deny' } : { kind: 'deny', reason };\n}\n\n/** Proceed, applying a patch. */\nexport function mutate(patch: Record<string, string>): ReactorDecision {\n return { kind: 'mutate', patch };\n}\n\n/** Publish nothing; let the registration's `failure_policy` decide. */\nexport function abstain(): ReactorDecision {\n return { kind: 'abstain' };\n}\n\n/**\n * A reactor handler: one function from a verified event to one of three answers\n * (CONTRACT.md §22.10).\n */\nexport type ReactorHandler = (event: ReactorEvent) => ReactorDecision | Promise<ReactorDecision>;\n\n// ---------------------------------------------------------------------------\n// The channel seam\n// ---------------------------------------------------------------------------\n\n/**\n * The operations one reactor delivery needs — **and no others**.\n *\n * There is deliberately no `assertQueue`, `assertExchange` or `bindQueue` here:\n * §22.1's \"actors consume; they never declare topology\" is enforced by the\n * seam's shape, so it cannot be violated by a later edit that forgets the rule.\n * `amqplib`'s `Channel` satisfies it structurally; tests provide a recording\n * fake that never touches a broker.\n */\nexport interface ReactorChannel {\n /** `channel.ack(msg)` — `allUpTo` intentionally omitted/false. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans. */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n /** Publish the signed reply to the `reply_to` queue, echoing the correlation id. */\n sendToQueue(\n queue: string,\n content: Buffer,\n options?: { correlationId?: string; contentType?: string },\n ): boolean;\n}\n\n/** Where this runtime writes its security events. */\nexport interface ReactorLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n// ---------------------------------------------------------------------------\n// Per-delivery dispatch\n// ---------------------------------------------------------------------------\n\n/** Everything one dispatch needs that does not come from the delivery. */\nexport interface ReactorDispatchContext {\n /** The tenant's HKDF-derived AMQP subkey. */\n readonly signingKey: Buffer;\n /** The tenant this reactor is registered in. */\n readonly tenantId: string;\n /** `intercept` (answers) or `listen` (observes, publishes nothing). */\n readonly mode: ReactorMode;\n /** `issued_at` acceptance window, in milliseconds. */\n readonly skewMs: number;\n /** Shared across every delivery on one consumer, or replay dedup does nothing. */\n readonly nonceStore: NonceStore;\n readonly logger?: ReactorLogger;\n readonly telemetry?: TelemetryDispatcher;\n}\n\n/**\n * Verify one delivery, dispatch it to `handler`, and publish the answer.\n *\n * Every path that cannot produce a **usable** reply publishes nothing at all,\n * which is what hands the decision to the registration's `failure_policy`\n * (§22.8) rather than to this library.\n *\n * Exported because it is the separately-testable unit backing\n * {@link reactorServe}'s per-message loop, mirroring the §8 consumer's\n * `verifyAndDispatch`.\n */\nexport async function dispatchReactorDelivery(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n handler: ReactorHandler,\n): Promise<void> {\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n reject(channel, msg, ctx, 'malformed', 'reactor delivery body failed JSON parse');\n return;\n }\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n reject(channel, msg, ctx, 'malformed', 'reactor delivery body is not a JSON object');\n return;\n }\n\n // §22.3, in order: key_version, MAC, freshness. Only then is anything in the\n // payload looked at.\n const verified = verifyEvent(body, ctx.signingKey, Date.now(), ctx.skewMs);\n if (!verified.ok) {\n reject(channel, msg, ctx, verified.rejection, 'reactor event failed §8 v2 verification');\n return;\n }\n const event = verified.event;\n\n // The fourth §22.3 check: the nonce seen-set.\n if (ctx.nonceStore.checkAndRecord(event.nonce, ctx.skewMs * 2)) {\n reject(channel, msg, ctx, 'replayed_nonce', 'reactor event nonce was already seen');\n return;\n }\n\n // A queue is per-tenant and the subkey is per-tenant, so this can only fire on\n // a misconfiguration — but a reactor answering for a tenant it was not\n // configured as is exactly the confusion §22.1 refuses to allow.\n if (event.tenant_id !== ctx.tenantId) {\n reject(\n channel,\n msg,\n ctx,\n 'malformed',\n 'reactor event names a different tenant than this reactor is configured for',\n );\n return;\n }\n\n const startedAt = Date.now();\n const deadline = startedAt + event.timeout_ms;\n const eventLabel = registryLabel(event.event);\n ctx.telemetry?.emit({\n type: 'requestStart',\n operation: TELEMETRY_OPERATION,\n method: 'AMQP',\n pathTemplate: eventLabel,\n attempt: 1,\n });\n\n // §22.10 rules 2 and 4 together: the handler runs inside the window the server\n // declared, and a throw is caught rather than propagated — both resolve to *no\n // reply*, never to a synthesized `allow`.\n let decision: ReactorDecision | undefined;\n try {\n decision = await withDeadline(handler(event), event.timeout_ms);\n } catch (err) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'reactor handler threw or outran timeout_ms; publishing no reply so the registration’s failure_policy decides',\n {\n event: event.event,\n correlationId: event.correlation_id,\n timeoutMs: event.timeout_ms,\n error: err instanceof Error ? err.message : String(err),\n },\n );\n }\n\n ctx.telemetry?.emit({\n type: 'requestEnd',\n operation: TELEMETRY_OPERATION,\n method: 'AMQP',\n pathTemplate: eventLabel,\n attempt: 1,\n durationMs: Date.now() - startedAt,\n outcome: decision === undefined ? 'failure' : 'success',\n });\n\n // A listener never publishes: the server does not wait for it and does not\n // read a reply, so anything it sent would be noise on a queue nobody is\n // draining (§22.5).\n if (ctx.mode === 'listen') {\n channel.ack(msg);\n return;\n }\n\n if (decision !== undefined) {\n publishAnswer(channel, msg, ctx, event, decision, deadline);\n }\n\n // The event verified and was consumed. Acking is what keeps `last_seen_at`\n // moving — a heartbeat derived from real work (§22.9) — and requeueing an\n // event whose correlation is already spent would only re-run a handler against\n // a window that has closed.\n channel.ack(msg);\n}\n\n/** Build, sign and publish the reply for `decision`, or publish nothing and say why. */\nfunction publishAnswer(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n event: ReactorEvent,\n decision: ReactorDecision,\n deadlineMs: number,\n): void {\n if (decision.kind === 'abstain') {\n return;\n }\n\n let requireMfa = false;\n let reason: string | undefined;\n let patch: Record<string, string> | undefined;\n let wire: 'allow' | 'deny' | 'mutate';\n\n if (decision.kind === 'allow') {\n wire = 'allow';\n requireMfa = decision.requireMfa;\n } else if (decision.kind === 'deny') {\n wire = 'deny';\n reason = decision.reason;\n } else {\n wire = 'mutate';\n patch = decision.patch;\n if (Object.keys(patch).length === 0) {\n // `mutate` with an empty patch is `malformed_mutation` server-side (§22.4\n // row 10). Refusing it here is not filtering — no field is being dropped,\n // the reply has no content to carry.\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'handler returned a mutation with an empty patch (malformed_mutation); publishing no reply',\n { event: event.event, correlationId: event.correlation_id },\n );\n return;\n }\n }\n\n // §22.4 row 7 / rule 3: `require_mfa` rides on `allow`, on `login.post_auth`,\n // and nowhere else. §22.13 allows an SDK to refuse this client-side; doing so\n // puts the mistake in the reactor author's log instead of only in the server's\n // audit trail.\n if (requireMfa && event.event !== REACTOR_EVENTS.LOGIN_POST_AUTH) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'require_mfa is only valid on login.post_auth (require_mfa_not_supported); publishing no reply',\n { event: event.event, correlationId: event.correlation_id },\n );\n return;\n }\n\n const reply = signReactorReply(\n buildReactorReply(event, { decision: wire, reason, patch, requireMfa }),\n ctx.signingKey,\n );\n\n // §22.3 / §22.10 rule 4: a late reply is discarded, and the CPU spent\n // producing it was spent for nothing. Do not spend the network on it too.\n if (Date.now() >= deadlineMs) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'the event’s window closed before the reply was ready; not publishing',\n {\n event: event.event,\n correlationId: event.correlation_id,\n timeoutMs: event.timeout_ms,\n },\n );\n return;\n }\n\n const replyTo = msg.properties.replyTo;\n if (typeof replyTo !== 'string' || replyTo.length === 0) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'delivery carried no reply_to property; nowhere to publish the reply',\n { correlationId: event.correlation_id },\n );\n return;\n }\n\n // The AMQP property is the RPC convention; what the server AUTHENTICATES is\n // the correlation_id inside the signed body, which `buildReactorReply` copied\n // from the event.\n const propertyCorrelation =\n typeof msg.properties.correlationId === 'string'\n ? msg.properties.correlationId\n : event.correlation_id;\n\n channel.sendToQueue(replyTo, Buffer.from(JSON.stringify(reply), 'utf8'), {\n correlationId: propertyCorrelation,\n contentType: 'application/json',\n });\n}\n\n/**\n * Nack without requeue and log the reason. The reason never carries the signing\n * key, and never the received or expected MAC.\n */\nfunction reject(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n rejection: string,\n message: string,\n): void {\n ctx.logger?.warn('axiam_sdk.security', `${message}; nacking without requeue`, {\n timestamp: new Date().toISOString(),\n rejection,\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n channel.nack(msg, false, false);\n}\n\n/**\n * Map a wire event name onto the registry's own string, so a telemetry label can\n * never be an attacker-chosen string or a cardinality bomb.\n */\nfunction registryLabel(name: string): string {\n return eventSpec(name)?.name ?? 'unknown_event';\n}\n\n/**\n * Settle `work`, or reject once `timeoutMs` has elapsed.\n *\n * The timer is always cleared — a pending `setTimeout` would keep a Node process\n * alive past the shutdown §18 promises is deterministic.\n */\nfunction withDeadline<T>(work: T | Promise<T>, timeoutMs: number): Promise<T> {\n return new Promise<T>((resolve, reject_) => {\n const timer = setTimeout(() => {\n reject_(new Error(`reactor handler exceeded timeout_ms=${timeoutMs}`));\n }, Math.max(timeoutMs, 0));\n Promise.resolve(work).then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject_(err instanceof Error ? err : new Error(String(err)));\n },\n );\n });\n}\n\n// ---------------------------------------------------------------------------\n// reactorServe\n// ---------------------------------------------------------------------------\n\n/** How to reach the broker and which reactor this process is (§22.1, §22.9). */\nexport interface ReactorConfig {\n /**\n * Broker URL. Must be `amqps://` (§8b rules 1 and 5) — there is no\n * verification-skip switch and no plaintext fallback, and this is now\n * *enforced* before the socket opens rather than merely stated here.\n */\n readonly amqpUrl: string;\n /**\n * TLS material for {@link amqpUrl} (§8b).\n *\n * Optional. With none supplied the broker is verified against Node's bundled\n * roots, which is correct for a publicly-issued broker certificate. Set\n * {@link AmqpTlsOptions.caCert} for a privately-issued one — the common case\n * for an in-cluster broker, and why §8b rule 2 is a MUST — and\n * `clientCert`/`clientKey` together for mutual TLS toward the broker\n * (rule 3).\n */\n readonly tls?: AmqpTlsOptions;\n /** The tenant this reactor is registered in. */\n readonly tenantId: string;\n /**\n * This reactor's registration id, from `POST /api/v1/reactors` (§22.9).\n *\n * It names the **one** queue this process may consume. Passing another\n * reactor's id is not a supported way to share a runtime: §22.1 forbids\n * deriving a queue name for a reactor other than the one you are.\n */\n readonly reactorId: string;\n /**\n * The tenant's HKDF-derived AMQP subkey (§8 v2, §22.2) — **not** the master\n * key. Obtain it from the AXIAM management API for this tenant; hard-coding\n * one is prohibited. Wrapped in `Sensitive` (§22.12) so it cannot be logged,\n * printed or serialized by accident.\n */\n readonly signingKey: Sensitive<Buffer>;\n /**\n * `intercept` (default) or `listen`.\n *\n * In `listen` mode the runtime publishes **nothing**: a listener cannot affect\n * any outcome, and §22.5 requires the handler be written idempotently because\n * a redelivery after a broker hiccup is normal.\n */\n readonly mode?: ReactorMode;\n /**\n * Override the ±300 s `issued_at` acceptance window. The same window, doubled,\n * bounds how long a `nonce` is remembered for replay detection.\n */\n readonly skewMs?: number;\n /** Nonce dedup store. One is created and shared across the consumer by default. */\n readonly nonceStore?: NonceStore;\n readonly logger?: ReactorLogger;\n /**\n * A §19 telemetry hook. One `requestStart`/`requestEnd` pair is emitted per\n * dispatch, with the registry event name as the path template — a bounded\n * label set, never a correlation id.\n */\n readonly telemetryHook?: TelemetryHook;\n /**\n * Deterministic shutdown (§18). Aborting it cancels the consumer, waits for\n * every in-flight dispatch to finish — handler, signature and publish — and\n * only then closes the channel and connection. Shutdown drains rather than\n * truncates.\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Run a reactor: consume the server-declared queue, answer every event\n * (CONTRACT.md §22.10).\n *\n * `handler` is called **only** with an event whose `key_version`, MAC, freshness\n * and nonce have all passed. It returns one of {@link ReactorDecision}'s three\n * answers, or {@link abstain} to publish nothing.\n *\n * Resolves when `signal` aborts (after the drain) or when the broker closes the\n * connection.\n *\n * @example\n * ```ts\n * import { Sensitive } from 'axiam-sdk/amqp';\n * import { REACTOR_EVENTS, allow, deny, mutate, reactorServe } from 'axiam-sdk/amqp';\n *\n * await reactorServe(\n * {\n * amqpUrl: 'amqps://reactor:secret@broker.example.com:5671',\n * tenantId: '11111111-1111-1111-1111-111111111111',\n * reactorId: '99999999-9999-9999-9999-999999999999',\n * signingKey: new Sensitive(subkey),\n * },\n * (event) => {\n * if (event.event === REACTOR_EVENTS.TOKEN_PRE_ISSUE) {\n * return mutate({ 'ext.cost_center': '42' });\n * }\n * if (event.event === REACTOR_EVENTS.LOGIN_POST_AUTH && fromEmbargoedRegion(event)) {\n * return deny('embargoed region');\n * }\n * return allow();\n * },\n * );\n * ```\n *\n * ## Security\n *\n * The `payload`, `patch`, `reason` and `decision` are tenant business data:\n * readable by design (a handler that cannot inspect the event cannot decide\n * anything) but **not** logged at info level by this runtime, and they should not\n * be logged at info level by yours either (§22.12). The signing key is\n * `Sensitive` and never appears in a log line or an error payload.\n */\nexport async function reactorServe(config: ReactorConfig, handler: ReactorHandler): Promise<void> {\n const queue = reactorQueueName(config.tenantId, config.reactorId);\n const skewMs = config.skewMs ?? REACTOR_FRESHNESS_SKEW_MS;\n const ctx: ReactorDispatchContext = {\n signingKey: config.signingKey.expose(),\n tenantId: config.tenantId,\n mode: config.mode ?? 'intercept',\n skewMs,\n // One store shared across every delivery on this consumer — a fresh store\n // per message would defeat replay dedup entirely.\n nonceStore: config.nonceStore ?? new InMemoryNonceStore(),\n logger: config.logger,\n telemetry: config.telemetryHook ? new TelemetryDispatcher(config.telemetryHook) : undefined,\n };\n\n // §8b: a reactor connects across a trust boundary, and its reply is an\n // instruction to allow, deny or rewrite a token. Validated before dialling —\n // a plaintext URL or half a client identity is a configuration fault, and\n // discovering it as a connect-time network error tells nobody what to fix.\n const socketOptions = buildAmqpConnectOptions(\n config.amqpUrl,\n config.tls,\n 'reactorServe() amqpUrl',\n );\n const connection = await amqp.connect(config.amqpUrl, socketOptions);\n const channel: Channel = await connection.createChannel();\n\n // NOTE: there is no assertQueue / assertExchange / bindQueue here, and there\n // must never be one. §22.1: the server declares the exchange, the queue and\n // the bindings; actors consume.\n const inFlight = new Set<Promise<void>>();\n let stopped = false;\n\n const { consumerTag } = await channel.consume(queue, (msg) => {\n if (!msg) return;\n // A delivery that arrives after the signal is nacked back rather than\n // half-processed: §18's drain covers what is already in flight, not what\n // the broker pushed afterwards.\n if (stopped) {\n channel.nack(msg, false, true);\n return;\n }\n const work = dispatchReactorDelivery(channel, msg, ctx, handler).finally(() => {\n inFlight.delete(work);\n });\n inFlight.add(work);\n });\n\n const closed = new Promise<void>((resolve) => {\n connection.on('close', () => resolve());\n });\n\n const aborted = config.signal\n ? new Promise<void>((resolve) => {\n const signal = config.signal as AbortSignal;\n if (signal.aborted) {\n resolve();\n return;\n }\n signal.addEventListener('abort', () => resolve(), { once: true });\n })\n : new Promise<void>(() => {\n /* never resolves; only the connection closing ends the run */\n });\n\n await Promise.race([closed, aborted]);\n stopped = true;\n\n // Drain (§18): stop taking new deliveries, then let every dispatch already\n // running finish — handler, signature, publish — before tearing down.\n try {\n await channel.cancel(consumerTag);\n } catch {\n // The channel may already be gone if the connection closed on us; the\n // drain below is what matters.\n }\n await Promise.allSettled([...inFlight]);\n try {\n await channel.close();\n await connection.close();\n } catch {\n // Idempotent teardown: closing an already-closed channel or connection is\n // the state the caller asked for, not an error to surface.\n }\n}\n","// Declarative reactor handler binding — CONTRACT.md §22.14.\n//\n// `reactorServe` takes ONE function from an event to one answer, which is the\n// right shape for the wire and the wrong shape for the code. A reactor\n// registered for three events opens with a `switch (event.event)`, and that\n// switch carries two defects.\n//\n// The first is cheap: a misspelled event name is a valid string literal, matches\n// no case, and is discovered as an event that never fires. The second is not. It\n// is the `default:` arm, which is almost always written `return allow()`. That\n// answers on behalf of code that never ran — the defect §22.10 rule 2 forbids\n// the RUNTIME from committing, relocated into user code where the rule does not\n// reach it. An operator who set `fail_closed` on a registration has it defeated\n// by a `default` arm in a file they never read.\n//\n// `reactorHandlers` is the declarative form. It is PURE SUGAR (§22.14 rule 1):\n// it produces exactly the `ReactorHandler` `reactorServe` already takes, opens\n// nothing, verifies nothing, signs nothing, and does not filter a patch. What it\n// adds is the two answers the switch got wrong — an unregistered event name is\n// refused when you BIND it, and an event with no handler ABSTAINS.\n\nimport { REACTOR_EVENTS, eventSpec, type ReactorEventName } from './registry.js';\nimport { abstain, type ReactorDecision, type ReactorHandler } from './runtime.js';\nimport type { ReactorEvent } from './protocol.js';\n\n/**\n * One handler per hook event.\n *\n * The key type is {@link ReactorEventName}, so a misspelled event is a\n * **compile-time** error in TypeScript — and `reactorHandlers` re-checks at\n * runtime for JavaScript callers, who get no such help. Duplicate keys within a\n * single object literal are a compile-time error too (TS1117), which is §22.14\n * rule 3 enforced by the language; passing two groups that both bind the same\n * event is the case the runtime check exists for.\n */\nexport type ReactorHandlerMap = Partial<Record<ReactorEventName, ReactorHandler>>;\n\n/**\n * The event names `reactorHandlers` accepts, sorted.\n *\n * Built from what IS hookable, deliberately: §22.13 requires the three hot-path\n * operations to be absent from every event constant this SDK exposes, so a list\n * naming them — even only to say they are refused — is the thing that would\n * break it (§22.14 rule 2).\n */\nexport function hookableEvents(): readonly string[] {\n return Object.values(REACTOR_EVENTS).slice().sort();\n}\n\n/**\n * Compose one handler per event into the single handler `reactorServe` takes\n * (CONTRACT.md §22.14).\n *\n * ```ts\n * await reactorServe(options, reactorHandlers({\n * [REACTOR_EVENTS.TOKEN_PRE_ISSUE]: enrichToken,\n * [REACTOR_EVENTS.LOGIN_POST_AUTH]: screenLogin,\n * }));\n * ```\n *\n * Several groups may be passed, so handlers can be split across modules and\n * merged here:\n *\n * ```ts\n * reactorHandlers(tokenHandlers, loginHandlers)\n * ```\n *\n * @param groups one or more event → handler maps.\n * @returns the `ReactorHandler` `reactorServe` accepts.\n * @throws TypeError if a key is outside the §22.5 registry — which is also how\n * §22.7's three hot-path operations are refused, since they are in no registry\n * row — if a value is not a function, if two groups bind the same event, or if\n * nothing is bound at all.\n */\nexport function reactorHandlers(...groups: readonly ReactorHandlerMap[]): ReactorHandler {\n const bound = new Map<string, ReactorHandler>();\n\n for (const group of groups) {\n for (const [event, handler] of Object.entries(group)) {\n if (eventSpec(event) === undefined) {\n throw new TypeError(\n `${event} is not a hookable reactor event; the registry is [${hookableEvents().join(', ')}]`,\n );\n }\n if (typeof handler !== 'function') {\n throw new TypeError(`the handler bound to ${event} is not a function`);\n }\n if (bound.has(event)) {\n throw new TypeError(`reactor event ${event} is already bound`);\n }\n bound.set(event, handler);\n }\n }\n\n if (bound.size === 0) {\n throw new TypeError('reactorHandlers received no bindings; bind at least one event');\n }\n\n return async (event: ReactorEvent): Promise<ReactorDecision> => {\n const handler = bound.get(event.event);\n if (handler === undefined) {\n // §22.14 rule 4. NOT allow(): publishing nothing lets the registration's\n // `failure_policy` resolve this exactly as it resolves a timeout (§22.8),\n // and this function does not know what the registration was for. The\n // operator's policy does.\n return abstain();\n }\n // Awaited without a try/catch on purpose (§22.14 rule 5): a handler's own\n // rejection must reach the runtime unchanged so it publishes nothing.\n // Catching it here would satisfy the letter of §22.10 rule 2 while\n // defeating it.\n return await handler(event);\n };\n}\n\n"]}
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/core/sensitive.ts","../../src/core/config.ts","../../src/core/telemetry.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/transport.ts","../../src/amqp/consumer.ts","../../src/amqp/reactor/registry.ts","../../src/amqp/reactor/protocol.ts","../../src/amqp/reactor/runtime.ts","../../src/amqp/reactor/handlers.ts"],"names":["createHmac","timingSafeEqual","amqp","randomUUID","createHash"],"mappings":";;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,M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W;AAKzB,MAAA,OAAO,OAAA,EAAQ;AAAA,IACjB;AAKA,IAAA,OAAO,MAAM,QAAQ,KAAK,CAAA;AAAA,EAC5B,CAAA;AACF","file":"index.js","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// 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","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\nimport type { TelemetryHook } from './telemetry.js';\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /**\n * Human-readable organization identifier (CONTRACT.md §5). Optional at\n * construction, but the server REQUIRES an org context on login — a tenant\n * slug is only unique *within* an organization — so a client that omits both\n * `orgSlug` and `orgId` will fail login with a 400/401. Forwarded as\n * `org_slug` in the login body. Mutually exclusive with {@link orgId}\n * (if both are given, `orgId` wins, mirroring how `tenantSlug`/`tenantId`\n * resolve).\n */\n orgSlug?: string;\n /**\n * Organization UUID (CONTRACT.md §5). Optional at construction (see\n * {@link orgSlug}). When supplied it is forwarded as `org_id` on login and\n * used to build the `refresh` body; otherwise the resolved organization UUID\n * is decoded from the authenticated session's access-token `org_id` claim\n * after the first successful login. Mutually exclusive with {@link orgSlug}.\n */\n orgId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /**\n * Enable the CONTRACT.md §16 bounded read-only retry policy. **Default:\n * `true`.**\n *\n * Set `false` to make every operation exactly one attempt. That is the right\n * choice for a caller who owns their own retry layer — they know their\n * deadline and this SDK does not — but it is not a way to make failures\n * quieter: a transient `NetworkError` simply surfaces immediately.\n *\n * §16.1 permits this switch but forbids raising the attempt cap, base delay\n * or delay cap above the contract's values, so there is no knob for those:\n * eleven SDKs agreeing on one table is the point.\n */\n retryEnabled?: boolean;\n /**\n * Enable the CONTRACT.md §17 client-side decision memo, in milliseconds.\n * **Default: `0`, which means disabled** — not \"cache for zero milliseconds\".\n *\n * ## What you are accepting\n *\n * The staleness bound is this TTL, **in both directions**. A grant revoked on\n * the server can still read as allowed for up to the TTL, and a grant just\n * added can still read as denied for up to the TTL.\n *\n * **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role\n * and immediately re-checks is the case that breaks, and it breaks silently.\n * If that is your workload, leave this off.\n *\n * Clamped to 5000 ms rather than rejected, so asking for a minute gets you\n * five seconds. Allows and denies are memoized identically (asymmetric\n * caching leaks the outcome through latency), failures are never memoized,\n * and the memo is cleared on any credential change.\n */\n decisionMemoTtlMs?: number;\n /**\n * Install a CONTRACT.md §19 telemetry sink.\n *\n * Receives request start/end, §16 retry and §9 refresh events, so metrics can\n * be wired without this package depending on any metrics library. See\n * `examples/telemetry-hook.ts`.\n *\n * A hook that throws cannot fail the operation that fired it (§19.2 rule 2),\n * and no event payload can carry a token — {@link TelemetryEvent} is a closed\n * union with a fixed field set (§19.2 rule 3). Invoked on the calling path,\n * so it must not block; buffer on your side if you need async delivery.\n */\n telemetryHook?: TelemetryHook;\n /**\n * PEM-encoded client-certificate chain for mutual TLS (§6.1). Presented to\n * the server to authenticate an IoT device / service account. MUST be\n * provided together with {@link AxiamClientOptions.clientKey}. Node only —\n * ignored in the browser (browsers cannot present a client certificate from\n * JS). Presenting a client certificate NEVER relaxes server verification.\n */\n clientCert?: string;\n /**\n * PEM-encoded private key (PKCS#8 or PKCS#1) matching {@link\n * AxiamClientOptions.clientCert} (§6.1). Secret material: it is passed\n * straight to the Node TLS stack and is never retained on a public property,\n * logged, or serialized (§7). MUST be provided together with `clientCert`.\n * Node only — ignored in the browser.\n */\n clientKey?: string;\n /**\n * Expected `iss` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 5). Optional and unset by default — the rule is conditional on\n * configuration, and the SDK never hardcodes an issuer. When set, the §10\n * middleware rejects a token whose `iss` differs.\n */\n expectedIssuer?: string;\n /**\n * Expected `aud` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 6). Optional and unset by default. A resource server guarding\n * user-facing routes SHOULD set `\"axiam:user\"`; a machine-to-machine one\n * `\"axiam:m2m\"`. When set, the §10 middleware rejects a token whose `aud`\n * does not contain it.\n */\n expectedAudience?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n /**\n * Act on another tenant of the caller's organization from construction —\n * CONTRACT.md §5.2 rule 1 (contract 1.51). Every `/api/v1` REST request\n * then also carries `X-Axiam-Tenant: <this value>`, distinct from the\n * `X-Tenant-ID` header {@link tenantSlug}/{@link tenantId} controls, which\n * is unaffected.\n *\n * Meaningful only for an **organization-level** principal; the server\n * answers `403` for an ordinary tenant principal. Construction cannot gate\n * on that — it precedes the login that would reveal it — so only the UUID\n * shape is checked here, client-side, with no wire call; a client already\n * holding a login result should prefer the on-client {@link\n * AxiamClient.actingTenant}, which also gates on `organizationLevel` and\n * `reachableTenantIds`. REST-only: the gRPC interceptor sends no\n * acting-tenant metadata.\n */\n actingTenantId?: string;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** PEM header that must appear in a certificate chain (§6/§6.1). */\nexport const CERT_PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * PEM header for a private key — PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1\n * (`BEGIN RSA PRIVATE KEY`), or an EC key (`BEGIN EC PRIVATE KEY`) (§6.1).\n */\nconst PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;\n\n/**\n * A validated mTLS client identity (§6.1). The private key is held behind\n * {@link Sensitive} so it can never leak through a debug/log/serialize path\n * (§7); call `key.expose()` only at the point of handing it to the TLS stack.\n */\nexport interface ClientIdentity {\n /** PEM certificate chain (not secret). */\n cert: string;\n /** PEM private key, redaction-wrapped (§7). */\n key: Sensitive<string>;\n}\n\n/**\n * Validate the §6.1 client-certificate options and, when configured, return\n * the resolved identity. Throws at construction time (consistent with §6's\n * PEM-only rule) when:\n * - exactly one of clientCert/clientKey is present (they are all-or-nothing);\n * - clientCert is not a PEM certificate chain;\n * - clientKey is not a PEM private key.\n *\n * Returns `undefined` when neither is configured. This validation runs on\n * every persona (including the browser, which then ignores the identity) so\n * construction fails fast and identically everywhere.\n */\nexport function resolveClientIdentity(options: {\n clientCert?: string;\n clientKey?: string;\n}): ClientIdentity | undefined {\n const hasCert = options.clientCert !== undefined;\n const hasKey = options.clientKey !== undefined;\n if (hasCert !== hasKey) {\n throw new Error(\n 'clientCert and clientKey must be provided together for mutual TLS ' +\n '(one was given without the other) (CONTRACT.md §6.1).',\n );\n }\n if (!hasCert || !hasKey) {\n return undefined;\n }\n if (!options.clientCert!.includes(CERT_PEM_MARKER)) {\n throw new Error(\n 'clientCert must be a PEM-encoded certificate chain (expected to contain ' +\n '\"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6.1).',\n );\n }\n if (!PRIVATE_KEY_PEM_RE.test(options.clientKey!)) {\n throw new Error(\n 'clientKey must be a PEM-encoded private key (expected to contain ' +\n '\"-----BEGIN PRIVATE KEY-----\" or \"-----BEGIN RSA PRIVATE KEY-----\") ' +\n '(CONTRACT.md §6.1).',\n );\n }\n return { cert: options.clientCert!, key: new Sensitive(options.clientKey!) };\n}\n","// Telemetry hooks — CONTRACT.md §19.\n//\n// An optional callback surface so callers can wire OpenTelemetry, Prometheus,\n// or a log line **without this package depending on any of them**. No hook\n// installed costs one undefined check per request.\n//\n// Two rules from §19.2 are enforced here rather than left to documentation:\n//\n// * A hook cannot break the SDK. `TelemetryDispatcher.emit` swallows anything\n// a sink throws, so a broken hook cannot fail an authorization check.\n// * No secrets, ever. `TelemetryEvent` is a closed discriminated union with a\n// fixed field set and no index signature, so there is no way to put a token\n// into a payload bound for a metrics backend. The type system, not a review\n// comment, is what keeps them out.\n\n/** Why a request finished. */\nexport type Outcome = 'success' | 'failure';\n\n/** Whether this caller performed a §9 refresh or waited on another's. */\nexport type RefreshRole = 'leader' | 'follower';\n\n/** Emitted before an outbound call leaves the SDK. */\nexport interface RequestStartEvent {\n /** Discriminant. */\n type: 'requestStart';\n /** Canonical operation name, e.g. `checkAccess`. */\n operation: string;\n /** HTTP method. */\n method: string;\n /**\n * Path **template** — `/api/v1/authz/check`, never a URL with ids\n * substituted in. A metric label carrying a UUID is a cardinality bomb.\n */\n pathTemplate: string;\n /** 1 for the first attempt, incrementing per §16 retry. */\n attempt: number;\n}\n\n/** Emitted after a call completes, success or failure. */\nexport interface RequestEndEvent {\n /** Discriminant. */\n type: 'requestEnd';\n /** Canonical operation name. */\n operation: string;\n /** HTTP method. */\n method: string;\n /** Path template — see {@link RequestStartEvent.pathTemplate}. */\n pathTemplate: string;\n /** Attempt this event closes. */\n attempt: number;\n /** HTTP status, or `undefined` when the call never got a response. */\n status?: number;\n /** Wall-clock duration of this attempt, in milliseconds. */\n durationMs: number;\n /** Success or failure. */\n outcome: Outcome;\n}\n\n/**\n * Emitted before each §16 retry wait.\n *\n * §16.5 requires this: a retried-then-succeeded operation is otherwise\n * invisible — the caller sees a slow success and no signal that the server is\n * failing. That silence is the standing objection to automatic retry.\n */\nexport interface RetryEvent {\n /** Discriminant. */\n type: 'retry';\n /** Canonical operation name. */\n operation: string;\n /** The attempt that just failed. */\n attempt: number;\n /** The delay about to be taken, after jitter and any `Retry-After`. */\n delayMs: number;\n /** Redacted failure description. Never carries a token (§2 redaction rules). */\n reason: string;\n}\n\n/** Emitted around a §9 single-flight refresh. */\nexport interface RefreshEvent {\n /** Discriminant. */\n type: 'refresh';\n /** Whether this caller performed the refresh or waited on another's. */\n role: RefreshRole;\n /** How long the refresh (or the wait for one) took, in milliseconds. */\n durationMs: number;\n}\n\n/**\n * Emitted at construction, once per caller-supplied setting the SDK clamped\n * (§19.1, §19.2 rule 6).\n *\n * Two places in the contract require clamping rather than rejecting: §16.1's\n * attempt cap, base delay and delay cap, and §17.1 rule 2's memo TTL. Both\n * clamps are right — rejecting would break a caller whose configuration was\n * merely optimistic, and honoring would let one client become the herd §16\n * exists to prevent. Doing it *silently* is the part that is wrong.\n *\n * An operator who set a 60-second memo TTL believes they have one. They have\n * five seconds, and their staleness reasoning is off by a factor of twelve with\n * nothing anywhere to say so.\n *\n * Not emitted for a value already within its limit: an event that fires when\n * nothing happened trains its reader to ignore it.\n */\nexport interface ConfigClampedEvent {\n /** Discriminant. */\n type: 'configClamped';\n /** The setting's name, e.g. `decisionMemoTtlMs`. */\n setting: string;\n /** The value the caller asked for, rendered. */\n requested: string;\n /** The value actually in force, rendered. */\n effective: string;\n /** The §-reference for the limit, e.g. `§17.1 rule 2`. */\n contractReference: string;\n}\n\n/** Why an SSF poll left SETs unjudged: the JWKS (or discovery) fetch, or the replay store. */\nexport type SsfUnjudgedCategory = 'key_fetch' | 'replay_store';\n\n/**\n * Emitted when `SsfReceiver.poll` returns normally leaving at least one SET\n * unjudged (contract 1.60, §19.1's SHOULD; §34.2 P1) — one event per failure\n * category present in the batch.\n *\n * A poll that accepted some SETs cannot raise without losing them, so it\n * returns and lists the rest in `unjudged`; this event is what makes that\n * outage visible to an operator who never inspects the list. It carries a\n * count, never a `jti` or a SET.\n */\nexport interface SsfUnjudgedEvent {\n /** Discriminant. */\n type: 'ssfUnjudged';\n /** Canonical operation name: `ssf.poll`. */\n operation: string;\n /** How many SETs of the batch this category left unjudged. */\n count: number;\n /** The failure that left them unjudged. */\n category: SsfUnjudgedCategory;\n}\n\n/** A §19 telemetry event. Closed union — see the file header for why. */\nexport type TelemetryEvent =\n | RequestStartEvent\n | RequestEndEvent\n | RetryEvent\n | RefreshEvent\n | ConfigClampedEvent\n | SsfUnjudgedEvent;\n\n/**\n * A caller-supplied telemetry sink (§19).\n *\n * Invoked on the calling path, so it must not block: §19.2 rule 4 makes\n * buffering the caller's job so they can pick the policy. Every mature metrics\n * library already buffers.\n */\nexport type TelemetryHook = (event: TelemetryEvent) => void;\n\n/**\n * Internal dispatcher. `undefined` is the overwhelmingly common case and costs\n * one check.\n */\nexport class TelemetryDispatcher {\n constructor(private readonly hook?: TelemetryHook) {}\n\n /**\n * Emit an event, swallowing anything the caller's hook throws.\n *\n * §19.2 rule 2: telemetry is not permitted to fail an authorization check.\n */\n emit(event: TelemetryEvent): void {\n if (!this.hook) return;\n try {\n this.hook(event);\n } catch {\n // Deliberately swallowed. A hook that throws is the caller's bug, and\n // surfacing it here would turn a metrics problem into an authorization\n // failure.\n }\n }\n\n /** Whether a hook is installed. */\n get installed(): boolean {\n return this.hook !== undefined;\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","// AMQP transport security (CONTRACT.md §8b).\n//\n// HMAC signing (§8) gives authenticity and replay protection. It does not give\n// confidentiality: a signed `AuthzRequest` still names a subject, a resource\n// and an action in cleartext on the wire, and a signed reactor reply is still\n// an instruction to change a token. TLS gives confidentiality; HMAC gives\n// end-to-end authenticity across broker hops, which TLS cannot, because TLS\n// terminates at the broker and the broker then re-sends. §8b's framing is\n// exact: both are required, and neither substitutes for the other.\n//\n// This module is the one place in the SDK that turns a broker URL and some\n// optional PEM material into arguments for `amqplib.connect`. Both AMQP entry\n// points — `consume()` (§8) and `reactorServe()` (§22) — go through it, so\n// there is a single answer to \"what does this SDK accept as a broker URL\"\n// rather than one answer per call site.\n//\n// # Why this file exists at all\n//\n// It is a fix, not a feature. Both entry points previously called\n// `amqp.connect(url)` with no scheme check and no TLS options, while their own\n// doc comments stated that the URL \"must be `amqps://` (§8b) — there is no\n// verification-skip switch and no plaintext fallback\". Every word of that was\n// true of the intent and none of it was true of the code: a plaintext\n// `amqp://` URL connected without complaint, and a privately-issued broker\n// certificate — the common case for an in-cluster broker, and the whole reason\n// §8b rule 2 is a MUST — could not be trusted at all, because there was no way\n// to supply a CA bundle. Documented-but-unenforced is the worst of the three\n// states: it reads as a guarantee at review time and behaves as an invitation\n// at runtime.\n\nimport type { ConnectionOptions as TlsConnectionOptions } from 'node:tls';\nimport { NetworkError } from '../core/errors.js';\nimport { resolveClientIdentity } from '../core/config.js';\n\nconst PEM_CERT_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * TLS material for an `amqps://` broker connection (§8b).\n *\n * Every field is optional: with none set, an `amqps://` URL still connects and\n * still verifies, against Node's bundled root store. The fields exist for the\n * two cases that store cannot serve — a privately-issued broker certificate,\n * and mutual TLS toward the broker.\n *\n * # There is deliberately no verification-skip option\n *\n * Not as an omission to be filled in later. §8b rule 4 forbids surfacing one\n * under any name, and the reasoning is that such a switch is the single most\n * reliably misused option in TLS: it appears in a dev compose file, it works,\n * and it travels unchanged into production, where it turns TLS into an\n * expensive no-op against precisely the attacker TLS exists to stop.\n * {@link caCert} covers the legitimate reason people reach for it (rule 2)\n * without covering the rest.\n *\n * This paragraph names no concrete bypass flag, and that is not squeamishness:\n * CI greps `src/` for the literal disabling forms and fails the build on a hit.\n * A comment explaining why the SDK does not do the thing would trip the same\n * grep as code doing it — the check cannot tell prose from an assignment — so\n * the prose stays abstract and the check stays blunt. Both are better that way.\n *\n * `amqplib` would happily accept `rejectUnauthorized` in its socket options,\n * which is exactly why {@link buildAmqpConnectOptions} constructs that object\n * itself from these three fields rather than accepting a caller-supplied one.\n */\nexport interface AmqpTlsOptions {\n /**\n * PEM bundle of the CA(s) that issued the broker's certificate (§8b rule 2).\n *\n * Unset = verify against Node's bundled roots. Set this when the broker\n * certificate comes from a private CA — including one issued by AXIAM's own\n * organization CA, which is the recommended dogfooding path.\n *\n * Unlike the server's own `AXIAM__AMQP__TLS__CA_CERT_PATH`, this **replaces**\n * the trust set rather than adding to it: Node's `tls.connect` treats `ca` as\n * the complete root list. Supplying your broker's CA here therefore does\n * narrow trust to it, which is usually what someone setting this actually\n * wants.\n */\n readonly caCert?: string;\n /**\n * PEM client certificate chain, for mutual TLS toward the broker (§8b\n * rule 3).\n *\n * Must be supplied together with {@link clientKey}. Half a client identity is\n * never what anyone meant, and connecting anyway would silently drop the\n * mutual half of mutual TLS — so it is rejected before dialling.\n */\n readonly clientCert?: string;\n /** PEM private key matching {@link clientCert}. Secret material (§7). */\n readonly clientKey?: string;\n}\n\n/**\n * Reject any broker URL that is not `amqps://` (§8b rules 1 and 5).\n *\n * A plaintext URL is refused here rather than downgraded, and there is no\n * fallback path for it to take — rule 5 exists because a fallback that works\n * is a fallback that gets used, and the failure it produces is invisible\n * exactly when it matters.\n *\n * The `://` separator is load-bearing: matching on `amqps` alone would let a\n * hypothetical `amqpsomething://` through.\n *\n * @throws {NetworkError} when `url` is not an `amqps://` URL.\n */\nexport function assertAmqpsUrl(url: string, what = 'AMQP URL'): void {\n if (!url.trim().toLowerCase().startsWith('amqps://')) {\n throw new NetworkError(\n `${what} must use amqps:// (CONTRACT.md §8b rules 1 and 5) — got ` +\n `${JSON.stringify(url)}. Broker traffic carries authorization requests, ` +\n 'audit events and reactor replies across a trust boundary; HMAC signing ' +\n 'gives them authenticity and replay protection, not confidentiality. ' +\n 'There is no plaintext fallback and no verification-skip switch — supply ' +\n \"a private broker CA with `caCert` if the broker's certificate is not \" +\n 'publicly issued.',\n );\n }\n}\n\n/**\n * Validate `url` and build the socket options `amqplib.connect` should dial\n * with (§8b).\n *\n * `amqplib` forwards its second argument to `tls.connect` for an `amqps://`\n * URL, so the returned object is a `tls.ConnectionOptions` carrying at most\n * `ca`, `cert` and `key`. It never carries `rejectUnauthorized`, which leaves\n * Node's strict default (`true`) in force — see {@link AmqpTlsOptions}.\n *\n * The certificate/key pairing is validated by `resolveClientIdentity`, the same\n * §6.1 helper the REST and gRPC transports use, so mutual TLS is validated\n * identically on every transport this SDK speaks rather than once per protocol.\n *\n * @throws {NetworkError} when `url` is not `amqps://`.\n * @throws {Error} when the TLS material is internally inconsistent (a client\n * certificate without its key, or PEM that is not PEM).\n */\nexport function buildAmqpConnectOptions(\n url: string,\n tls: AmqpTlsOptions = {},\n what = 'AMQP URL',\n): TlsConnectionOptions | undefined {\n assertAmqpsUrl(url, what);\n\n if (tls.caCert !== undefined && !tls.caCert.includes(PEM_CERT_MARKER)) {\n throw new Error(\n `caCert must be a PEM-encoded certificate (expected to contain ` +\n `\"${PEM_CERT_MARKER}\") (CONTRACT.md §8b rule 2).`,\n );\n }\n\n // Reuses §6.1's all-or-nothing check and PEM validation rather than\n // re-implementing it: an SDK that validated a client identity two different\n // ways would eventually validate it two different amounts.\n const identity = resolveClientIdentity({\n clientCert: tls.clientCert,\n clientKey: tls.clientKey,\n });\n\n if (tls.caCert === undefined && identity === undefined) {\n // Nothing to configure. `undefined` lets amqplib use its own defaults,\n // which for an amqps:// URL means Node's bundled roots with verification\n // on — the correct behaviour for a publicly-issued broker certificate, and\n // the reason `caCert` is optional rather than required.\n return undefined;\n }\n\n return {\n ...(tls.caCert !== undefined ? { ca: tls.caCert } : {}),\n ...(identity !== undefined\n ? { cert: identity.cert, key: identity.key.expose() }\n : {}),\n };\n}\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';\nimport { buildAmqpConnectOptions, type AmqpTlsOptions } from './transport.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 * TLS material for the `amqps://` broker connection (CONTRACT.md §8b).\n *\n * Optional, and omitting it does not weaken anything: the URL must be\n * `amqps://` either way, and with no material supplied the broker is verified\n * against Node's bundled roots. Set {@link AmqpTlsOptions.caCert} when the\n * broker certificate comes from a private CA — the common case for an\n * in-cluster broker, and the reason §8b rule 2 is a MUST.\n */\n tls?: AmqpTlsOptions;\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 *\n * `amqpUrl` MUST be `amqps://` (CONTRACT.md §8b). It is checked before any\n * socket is opened, so a plaintext URL fails with a message naming the rule\n * rather than connecting and quietly putting signed-but-readable authorization\n * requests and audit events on the wire.\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 // §8b: validated BEFORE dialling. A bad URL or half a client identity is a\n // configuration fault, and finding out at connect time turns it into a\n // network error message that says nothing about what to fix.\n const socketOptions = buildAmqpConnectOptions(amqpUrl, options.tls, 'consume() amqpUrl');\n const connection = await amqp.connect(amqpUrl, socketOptions);\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","// The reactor event registry and its mutable-field allow-lists\n// (CONTRACT.md §22.5, §22.7, §22.8).\n//\n// Mirror, never import. This is the same data as the server's\n// `EVENT_REGISTRY` in `crates/axiam-core/src/models/reactor.rs`, restated here\n// so a reactor author can name an event, ask what it may mutate, and compute a\n// registration's default failure policy without a network call. The live copy\n// is served at `GET /api/v1/reactors/events` and is the one an admin UI SHOULD\n// read; this table is the offline equivalent.\n//\n// What is deliberately absent (§22.7 — normative MUST NOT): `authz.check`,\n// `authz.check_batch` and `token.introspect`. They are not hookable and this\n// SDK does not present them as such — they appear in no constant, no array and\n// no example here. A reactor round-trip is milliseconds; the check path's\n// budget is microseconds. An application that needs external input on an\n// authorization decision writes a deny grant, which the engine evaluates in the\n// hot path at hot-path cost.\n\n/**\n * What the server does when an interceptor produces no usable reply\n * (CONTRACT.md §22.8).\n *\n * \"No usable reply\" is one closed set and every member takes the same path:\n * timeout, transport failure, a budget exhausted before this reactor was\n * reached, the in-flight cap, and every §22.4 rejection — including a valid\n * signature carrying a forbidden patch field.\n */\nexport type FailurePolicy = 'fail_open' | 'fail_closed';\n\n/**\n * How a reactor participates in an event (CONTRACT.md §22.5, §22.9).\n *\n * `listen` is fire-and-forget observation: the server never waits and never\n * reads a reply, so a listener cannot affect any outcome — and\n * {@link reactorServe} publishes nothing at all in that mode.\n */\nexport type ReactorMode = 'intercept' | 'listen';\n\n/**\n * One hookable event: its name, what a reply may change, and what happens when\n * the reactor does not answer (CONTRACT.md §22.5).\n */\nexport interface ReactorEventSpec {\n /** Wire name, and the second half of the routing key (`<tenant_id>.<event>`). */\n readonly name: string;\n /** Whether an interceptor may register for this event at all. */\n readonly interceptable: boolean;\n /** Whether an interceptor's reply may carry a `patch`. */\n readonly mutable: boolean;\n /**\n * The **complete** allow-list. An entry ending in `.` is a namespace prefix\n * — see {@link patchFieldAllowed}.\n */\n readonly mutableFields: readonly string[];\n /** The `failure_policy` a registration gets when it names none. */\n readonly defaultFailurePolicy: FailurePolicy;\n /** One line, as the admin surface shows it. */\n readonly description: string;\n}\n\n/**\n * The five v1 event names.\n *\n * Handlers compare against these rather than string literals so a typo is a\n * type error rather than an event that silently never fires.\n */\nexport const REACTOR_EVENTS = {\n /** Before an access token is minted. Mutable: the `ext.` claim namespace. */\n TOKEN_PRE_ISSUE: 'token.pre_issue',\n /**\n * After credentials verify, before a session is issued. Veto or step-up.\n *\n * Fires on password authentication, on SAML ACS and on the OIDC callback\n * (§22.5, SEC-095). MFA completion and the WebAuthn `authenticate/finish`\n * ceremony are **not** separate firings — both continue a login that was\n * already gated at its first step.\n *\n * The federated paths have no step-up branch, so a `require_mfa` answer on\n * those is **refused** (the sign-in fails) rather than silently dropped: a\n * reactor that needs step-up there answers `deny` and drives enrolment out of\n * band.\n */\n LOGIN_POST_AUTH: 'login.post_auth',\n /** Before a user row is written. Mutable: `username`, `email`, `metadata.`. */\n USER_PRE_CREATE: 'user.pre_create',\n /** Before a user row is updated. Mutable: `username`, `email`, `metadata.`. */\n USER_PRE_UPDATE: 'user.pre_update',\n /** Before a role or permission is assigned. Veto only. */\n GRANT_PRE_ASSIGN: 'grant.pre_assign',\n} as const;\n\n/** The union of the five v1 registry event names. */\nexport type ReactorEventName = (typeof REACTOR_EVENTS)[keyof typeof REACTOR_EVENTS];\n\n/**\n * Every hookable event in v1 — five of them (CONTRACT.md §22.5).\n *\n * The order matches the server's `EVENT_REGISTRY`. Nothing on the authorization\n * hot path appears here, and nothing may be added to it locally: an event\n * outside the registry dispatches to nothing and resolves to `allow`, which is\n * what makes §22.7's exclusion structural rather than advisory.\n */\nexport const EVENT_REGISTRY: readonly ReactorEventSpec[] = [\n {\n name: REACTOR_EVENTS.TOKEN_PRE_ISSUE,\n interceptable: true,\n mutable: true,\n // Custom claims only. `iss`, `sub`, `aud`, `exp`, `iat`, `nbf`, `jti`,\n // `scope`, `scp`, `azp`, `act` and `client_id` are all unreachable because\n // none of them begins with `ext.` — a hook that can rewrite `sub` is a hook\n // that can mint a token for anyone.\n mutableFields: ['ext.'],\n defaultFailurePolicy: 'fail_open',\n description: 'Enrich or veto token issuance. May add claims under `ext.` only.',\n },\n {\n name: REACTOR_EVENTS.LOGIN_POST_AUTH,\n interceptable: true,\n mutable: false,\n mutableFields: [],\n defaultFailurePolicy: 'fail_closed',\n description:\n 'After credentials verify, before session issuance: veto or require step-up MFA.',\n },\n {\n name: REACTOR_EVENTS.USER_PRE_CREATE,\n interceptable: true,\n mutable: true,\n mutableFields: ['username', 'email', 'metadata.'],\n defaultFailurePolicy: 'fail_closed',\n description: \"Validate or normalize a new user's profile fields.\",\n },\n {\n name: REACTOR_EVENTS.USER_PRE_UPDATE,\n interceptable: true,\n mutable: true,\n mutableFields: ['username', 'email', 'metadata.'],\n defaultFailurePolicy: 'fail_closed',\n description: 'Validate or normalize a profile update.',\n },\n {\n name: REACTOR_EVENTS.GRANT_PRE_ASSIGN,\n interceptable: true,\n mutable: false,\n mutableFields: [],\n defaultFailurePolicy: 'fail_closed',\n description: 'Veto a role or permission assignment (four-eyes workflows). Veto-only.',\n },\n];\n\n/**\n * Look an event up by wire name. `undefined` for anything outside the registry\n * — including the three hot-path operations §22.7 excludes.\n */\nexport function eventSpec(name: string): ReactorEventSpec | undefined {\n return EVENT_REGISTRY.find((spec) => spec.name === name);\n}\n\n/**\n * Whether `field` may appear in a `patch` for `spec` (CONTRACT.md §22.5).\n *\n * An allow-list entry ending in `.` is a **namespace prefix**, and it matches a\n * field that starts with the entry and has **at least one character after the\n * dot**. So `ext.` admits `ext.department` and `ext.a.b.c`, and refuses `ext.`\n * itself (it names the namespace, not a claim), `ext` (not in the namespace),\n * `extra` / `external_id` (a prefix match on the *string* is not a match on the\n * namespace) and `evil.ext.department` (not a suffix match either).\n *\n * ## This is a lookup, not a filter\n *\n * It exists so a handler can check its own patch before returning it.\n * {@link reactorServe} does **not** call it to prune a patch: §22.4 rule 1 and\n * §22.10 rule 3 forbid filtering a handler's patch down to the allowed subset,\n * because one forbidden key rejects the *whole* patch server-side and dropping\n * it silently would leave the author believing a field was set when it was not.\n */\nexport function patchFieldAllowed(spec: ReactorEventSpec, field: string): boolean {\n if (!spec.mutable) return false;\n return spec.mutableFields.some((allowed) =>\n allowed.endsWith('.')\n ? field.length > allowed.length && field.startsWith(allowed)\n : field === allowed,\n );\n}\n\n/**\n * The `failure_policy` a registration gets when it names none: **the strictest\n * default among its events** (CONTRACT.md §22.8).\n *\n * A reactor registered for both `token.pre_issue` (open) and `login.post_auth`\n * (closed) can veto a login, so it inherits `fail_closed` — **in either array\n * order**. Reimplementing this as \"take the first event's default\" would let\n * the order of a JSON array decide whether an unreachable fraud check passes.\n *\n * An unknown event name contributes `fail_closed`: it will be refused at\n * registration anyway, and guessing `fail_open` for a name this SDK does not\n * recognise is the one guess that could weaken a decision. An empty list is\n * likewise `fail_closed` — a registration with no events is invalid, not\n * permissive.\n */\nexport function defaultFailurePolicyFor(eventNames: readonly string[]): FailurePolicy {\n if (eventNames.length === 0) return 'fail_closed';\n for (const name of eventNames) {\n const spec = eventSpec(name);\n if (!spec || spec.defaultFailurePolicy === 'fail_closed') return 'fail_closed';\n }\n return 'fail_open';\n}\n\n/** Default `timeout_ms` when a registration does not name one (§22.8). */\nexport const DEFAULT_REACTOR_TIMEOUT_MS = 500;\n\n/** Lowest accepted `timeout_ms` at registration (§22.8). `0` is refused. */\nexport const MIN_REACTOR_TIMEOUT_MS = 1;\n\n/**\n * Hard ceiling on a registration's `timeout_ms`, and on the whole chain's wall\n * clock (§22.8). A reactor that needs longer than five seconds to answer is not\n * an interceptor, it is an outage.\n */\nexport const MAX_REACTOR_TIMEOUT_MS = 5_000;\n\n/**\n * Per-tenant in-flight interception cap, enforced server-side with a\n * non-blocking acquire (§22.8). Stated here so a reactor author sizing a worker\n * pool knows the ceiling they are working under.\n */\nexport const DEFAULT_REACTOR_MAX_IN_FLIGHT = 64;\n","// The reactor wire protocol — the signed event and the signed reply\n// (CONTRACT.md §22.1–§22.4).\n//\n// Mirror, never import. These shapes reproduce the field order and serde\n// behaviour of the server's `ReactorEventMessage` / `ReactorReply`\n// (`crates/axiam-amqp/src/reactor/protocol.rs`) byte-for-byte using only Node\n// built-ins. `testdata/reactor_v2_reference_vectors.json` — generated by the\n// server's own sign path — is what pins them.\n//\n// ## The one canonicalization difference that will cost you a day\n//\n// §8's own two message types (`AuthzRequest`, `AuditEventMessage`) sign a body\n// with `hmac_signature` OMITTED. A reactor event and a reactor reply sign it\n// SERIALIZED AS `null`:\n//\n// {\"correlation_id\":\"…\",\"tenant_id\":\"…\", … ,\"hmac_signature\":null}\n// ^^^^ present\n//\n// Everything else about §8 v2 is unchanged: the HKDF-derived per-tenant subkey,\n// HMAC-SHA256 hex-encoded and compared in constant time, `key_version = 2` as a\n// hard floor, a ±300 s freshness window checked in BOTH directions, and a fresh\n// UUIDv4 `nonce` inside the signed bytes.\n//\n// ## The second thing that will cost you a day, and is TypeScript-specific\n//\n// `Date.prototype.toISOString()` ALWAYS emits three fractional digits\n// (`…T12:00:00.000Z`). The server's `issued_at` is a `chrono::DateTime<Utc>`,\n// which re-serializes with `SecondsFormat::AutoSi` — no fractional part at all\n// when the nanoseconds are zero. So a reply timestamped with a bare\n// `toISOString()` on a whole second is re-serialized by the server as\n// `…T12:00:00Z`, over different bytes than the reactor signed, and the\n// signature fails with no other symptom. {@link toChronoRfc3339} is the fix and\n// it is not optional.\n\nimport { createHash, randomUUID } from 'node:crypto';\nimport { signPayload, verifyPayload } from '../hmac.js';\nimport { eventSpec, type ReactorEventSpec } from './registry.js';\n\n/** Topic exchange every reactor event is published to (§22.1). */\nexport const REACTOR_EXCHANGE = 'axiam.reactor.events';\n\n/**\n * Envelope key version this SDK emits, and the floor it accepts (§22.2). A body\n * carrying less than this is refused before anything else about it is\n * considered.\n */\nexport const REACTOR_KEY_VERSION = 2;\n\n/**\n * Freshness window for `issued_at`, in milliseconds, in **both** directions\n * (§22.2). A future timestamp is not \"extra fresh\" — it is the shape of a\n * captured message held for later.\n */\nexport const REACTOR_FRESHNESS_SKEW_MS = 300_000;\n\n/**\n * The routing key an event is published with: `<tenant_id>.<event>` (§22.1).\n *\n * Stated so an SDK can assert against it; a reactor runtime never *binds* with\n * it. See {@link reactorQueueName}.\n */\nexport function reactorRoutingKey(tenantId: string, event: string): string {\n return `${tenantId}.${event}`;\n}\n\n/**\n * The durable per-reactor queue name:\n * `axiam.reactor.q.<tenant_id>.<reactor_id>` (§22.1).\n *\n * **The server declares this queue; a reactor only consumes from it.** This SDK\n * derives the name for the reactor it is configured as and for no other: a\n * reactor that can declare and bind is a reactor that can bind itself to\n * `*.token.pre_issue` and read another tenant's issuance events, and refusing to\n * hold that capability at all is cheaper than proving each actor does not misuse\n * it.\n */\nexport function reactorQueueName(tenantId: string, reactorId: string): string {\n return `axiam.reactor.q.${tenantId}.${reactorId}`;\n}\n\n/**\n * Render `date` the way the server's `chrono::DateTime<Utc>` serializes it:\n * RFC 3339, UTC, with **no** fractional part when the milliseconds are zero and\n * exactly three digits otherwise.\n *\n * This is not cosmetic. The server verifies a reply by re-serializing the body\n * it parsed, so a timestamp this SDK wrote as `…T12:00:00.000Z` comes back out\n * as `…T12:00:00Z` — different bytes, different MAC, and a `bad_signature`\n * rejection with nothing in the payload to explain it.\n */\nexport function toChronoRfc3339(date: Date): string {\n const iso = date.toISOString();\n return iso.endsWith('.000Z') ? `${iso.slice(0, -5)}Z` : iso;\n}\n\n/** `true` when `issuedAt` lies within `±skewMs` of `now` — both directions. */\nexport function isFresh(issuedAtMs: number, nowMs: number, skewMs: number): boolean {\n return Math.abs(nowMs - issuedAtMs) <= skewMs;\n}\n\n// ---------------------------------------------------------------------------\n// Event (server → reactor)\n// ---------------------------------------------------------------------------\n\n/**\n * One hook firing, delivered to a reactor (CONTRACT.md §22.3).\n *\n * Field order is load-bearing: it is the order the server serializes, and\n * therefore the order the canonical signed bytes carry.\n */\nexport interface ReactorEvent {\n /**\n * The tenant this firing belongs to. The signing subkey is derived from it,\n * so an event cannot be replayed into another tenant.\n */\n readonly tenant_id: string;\n /** A registry name (§22.5) — also the second half of the routing key. */\n readonly event: string;\n /**\n * The single-use handle for this dispatch. The runtime echoes it into the\n * reply **body**; copying it only into the AMQP property produces a reply the\n * server discards.\n */\n readonly correlation_id: string;\n /**\n * Event-specific body. Never carries a credential, a token, or a signing key\n * — a reactor is told *what is being decided*, not handed the means to act on\n * it elsewhere.\n *\n * On a chained event this object also carries `_reactor_patch`, the patch an\n * earlier reactor in the chain already returned (§22.3). Treat it as\n * **read-only context**: echoing it back inside your own `patch` is not how a\n * field is preserved — the server merges (§22.6).\n */\n readonly payload: Record<string, unknown>;\n /**\n * How long the server will actually wait for *this* dispatch, in\n * milliseconds. Inside the signed body, so it cannot be widened in transit.\n *\n * §22.3 sends it so an actor can shed load rather than answer into a closed\n * window: a late reply is discarded, and the CPU spent producing it was spent\n * for nothing.\n */\n readonly timeout_ms: number;\n /** §8 v2 envelope key version. Always `2` or higher. */\n readonly key_version: number;\n /** Fresh UUIDv4 per message, inside the signed bytes. */\n readonly nonce: string;\n /** Producer-side send time, RFC 3339, for the freshness gate. */\n readonly issued_at: string;\n /** HMAC-SHA256 over this body with the field serialized as `null`. */\n readonly hmac_signature: string | null;\n}\n\n/**\n * Why a delivered event was not usable, in the order §22.3 requires the checks\n * to run.\n */\nexport type EventRejection =\n /** The body is not a JSON object, or is missing a mandatory field. */\n | 'malformed'\n /**\n * `key_version` below the §8 v2 floor — refused **before** the signature is\n * even computed.\n */\n | 'key_version_too_old'\n /** Missing or wrong MAC. */\n | 'bad_signature'\n /** `issued_at` outside ±skew, in either direction. */\n | 'stale'\n /** This `nonce` was already seen inside the freshness window. */\n | 'replayed_nonce';\n\n/**\n * Why the server would not use a reply (CONTRACT.md §22.4).\n *\n * Every member resolves to the registration's `failure_policy` and every member\n * is audited: a rejected reply is **not** a softer failure than no reply at all.\n * This SDK exposes the taxonomy so a reactor author can assert against it and\n * read it in a log line, and refuses locally only what it can detect without\n * guessing (see {@link reactorServe}).\n */\nexport type ReplyRejection =\n | 'wrong_correlation'\n | 'tenant_mismatch'\n | 'event_mismatch'\n | 'key_version_too_old'\n | 'stale'\n | 'bad_signature'\n | 'require_mfa_not_supported'\n | 'not_mutable'\n | 'forbidden_patch_field'\n | 'malformed_mutation';\n\n/**\n * The canonical bytes of a delivered event: the body exactly as it arrived,\n * with `hmac_signature` **set to `null` in place** (§22.2).\n *\n * Setting the value rather than deleting the key is the whole difference from\n * §8's own two message types, and re-serializing the *parsed* body (rather than\n * a rebuilt struct) is what makes the payload's own key order and nesting\n * reproduce byte-for-byte — `JSON.parse` preserves insertion order for string\n * keys, and assigning to an existing key keeps its position.\n *\n * Returns `undefined` when the body carries no `hmac_signature` at all: an\n * unsigned event is not a weak event, it is not an event, and inserting the key\n * ourselves would put it in the wrong position anyway.\n */\nexport function canonicalEventBytes(body: Record<string, unknown>): Buffer | undefined {\n if (!('hmac_signature' in body)) return undefined;\n const canonical: Record<string, unknown> = { ...body, hmac_signature: null };\n return Buffer.from(JSON.stringify(canonical), 'utf8');\n}\n\n/** A successfully verified event, or the reason it was refused. */\nexport type VerifyEventResult =\n | { ok: true; event: ReactorEvent }\n | { ok: false; rejection: EventRejection };\n\n/**\n * Verify a delivered event and decode it, in the order §22.3 fixes:\n * **`key_version`, then the MAC, then freshness**. The fourth check, the nonce\n * seen-set, is the runtime's rather than this function's, because it is state\n * rather than a property of the message.\n *\n * A runtime that hands an unverified payload to user code has already lost: the\n * handler will act on it, and \"we checked afterwards\" is not a check.\n */\nexport function verifyEvent(\n body: Record<string, unknown>,\n signingKey: Buffer,\n nowMs: number = Date.now(),\n skewMs: number = REACTOR_FRESHNESS_SKEW_MS,\n): VerifyEventResult {\n // 1. key_version, before anything else about the body is considered.\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || !Number.isInteger(keyVersion)) {\n return { ok: false, rejection: 'malformed' };\n }\n if (keyVersion < REACTOR_KEY_VERSION) {\n return { ok: false, rejection: 'key_version_too_old' };\n }\n\n // 2. the MAC, over the body with hmac_signature serialized as null.\n const signature = body.hmac_signature;\n if (typeof signature !== 'string') {\n return { ok: false, rejection: 'bad_signature' };\n }\n const canonical = canonicalEventBytes(body);\n if (!canonical || !verifyPayload(signingKey, canonical, signature)) {\n return { ok: false, rejection: 'bad_signature' };\n }\n\n // Only now is the body's shape trusted enough to read.\n if (\n typeof body.tenant_id !== 'string' ||\n typeof body.event !== 'string' ||\n typeof body.correlation_id !== 'string' ||\n typeof body.nonce !== 'string' ||\n typeof body.issued_at !== 'string' ||\n typeof body.timeout_ms !== 'number' ||\n typeof body.payload !== 'object' ||\n body.payload === null ||\n Array.isArray(body.payload)\n ) {\n return { ok: false, rejection: 'malformed' };\n }\n\n // 3. freshness, in both directions.\n const issuedAtMs = Date.parse(body.issued_at);\n if (Number.isNaN(issuedAtMs) || !isFresh(issuedAtMs, nowMs, skewMs)) {\n return { ok: false, rejection: 'stale' };\n }\n\n return {\n ok: true,\n event: {\n tenant_id: body.tenant_id,\n event: body.event,\n correlation_id: body.correlation_id,\n payload: body.payload as Record<string, unknown>,\n timeout_ms: body.timeout_ms,\n key_version: keyVersion,\n nonce: body.nonce,\n issued_at: body.issued_at,\n hmac_signature: signature,\n },\n };\n}\n\n/**\n * The accumulated patch an earlier reactor in the chain returned, if this is a\n * chained dispatch (§22.3's `_reactor_patch`).\n *\n * Read-only context: it tells you what the state will be if the chain commits,\n * so you can decide against that rather than against the original. It is **not**\n * something to copy into your own patch.\n */\nexport function chainedPatch(event: ReactorEvent): unknown {\n return event.payload._reactor_patch;\n}\n\n/** The registry spec for an event's name, if this SDK knows it. */\nexport function specForEvent(event: ReactorEvent): ReactorEventSpec | undefined {\n return eventSpec(event.event);\n}\n\n// ---------------------------------------------------------------------------\n// Reply (reactor → server)\n// ---------------------------------------------------------------------------\n\n/** The closed set of decision values (§22.4). Lowercase on the wire. */\nexport type ReplyDecision = 'allow' | 'deny' | 'mutate';\n\n/**\n * A reactor's answer to one event (CONTRACT.md §22.4), as it appears on the\n * wire.\n *\n * The three conditionally-present fields are load-bearing. A reply that\n * serializes `\"require_mfa\": false` rather than omitting it produces different\n * canonical bytes and therefore a different MAC — the omission rule, not just\n * the values, is part of the wire format. {@link buildReactorReply} is what\n * enforces it; do not assemble one of these by hand.\n */\nexport interface ReactorReply {\n readonly correlation_id: string;\n readonly tenant_id: string;\n readonly event: string;\n readonly decision: ReplyDecision;\n /** Audited on a `deny`. **Omitted when absent.** */\n readonly reason?: string;\n /** Flat `string → string` map, sorted by key. **Omitted when absent.** */\n readonly patch?: Record<string, string>;\n /** `login.post_auth` only. **Omitted when `false`.** */\n readonly require_mfa?: true;\n readonly key_version: number;\n /**\n * A **fresh** UUIDv4 per reply. It is inside the signed bytes, so a unique one\n * is what keeps two replies from being byte-identical — which is what makes a\n * captured reply distinguishable from a fresh one. Emitting a constant nonce\n * removes the only uniqueness a reply body carries beyond its timestamp.\n */\n readonly nonce: string;\n readonly issued_at: string;\n readonly hmac_signature: string | null;\n}\n\n/** What {@link buildReactorReply} needs beyond the event it answers. */\nexport interface ReplyInput {\n readonly decision: ReplyDecision;\n readonly reason?: string;\n readonly patch?: Record<string, string>;\n readonly requireMfa?: boolean;\n /** Overridable for tests; defaults to a fresh UUIDv4 per reply. */\n readonly nonce?: string;\n /** Overridable for tests; defaults to now. */\n readonly issuedAt?: Date;\n}\n\n/**\n * Build an **unsigned** reply answering `event`, with `correlation_id`,\n * `tenant_id` and `event` copied from the event body (§22.1, §22.4), in the\n * server's field order and with every omission rule applied.\n *\n * The patch's keys are emitted in sorted order, because the server's `patch` is\n * a `BTreeMap` and the signed bytes are the sorted rendering.\n */\nexport function buildReactorReply(\n event: Pick<ReactorEvent, 'correlation_id' | 'tenant_id' | 'event'>,\n input: ReplyInput,\n): ReactorReply {\n // Assembled by assignment, in declaration order, because JSON.stringify\n // serializes string keys in insertion order and that order IS the wire format.\n const reply: Record<string, unknown> = {\n correlation_id: event.correlation_id,\n tenant_id: event.tenant_id,\n event: event.event,\n decision: input.decision,\n };\n // `reason` and `patch` are omitted when absent — not emitted as null.\n if (input.reason !== undefined) reply.reason = input.reason;\n if (input.patch !== undefined) reply.patch = sortedPatch(input.patch);\n // `require_mfa` is omitted when false. A reply carrying `false` explicitly\n // signs different bytes and its MAC will not verify.\n if (input.requireMfa === true) reply.require_mfa = true;\n reply.key_version = REACTOR_KEY_VERSION;\n reply.nonce = input.nonce ?? randomUUID();\n reply.issued_at = toChronoRfc3339(input.issuedAt ?? new Date());\n reply.hmac_signature = null;\n return reply as unknown as ReactorReply;\n}\n\n/** A patch object whose keys iterate in sorted order (the server's `BTreeMap`). */\nfunction sortedPatch(patch: Record<string, string>): Record<string, string> {\n const sorted: Record<string, string> = {};\n for (const key of Object.keys(patch).sort()) {\n sorted[key] = patch[key] as string;\n }\n return sorted;\n}\n\n/**\n * The exact bytes a reply is signed over: itself, in declaration order, with\n * `hmac_signature` set to `null`.\n *\n * Clearing the field here rather than asking the caller to remember is what\n * makes it impossible to sign over a body that already contains a signature.\n */\nexport function canonicalReplyBytes(reply: ReactorReply): Buffer {\n const unsigned: Record<string, unknown> = { ...reply, hmac_signature: null };\n return Buffer.from(JSON.stringify(unsigned), 'utf8');\n}\n\n/**\n * Sign a reply with the tenant's derived AMQP subkey, returning a new object\n * carrying the MAC. The input is not mutated.\n */\nexport function signReactorReply(reply: ReactorReply, signingKey: Buffer): ReactorReply {\n const signature = signPayload(signingKey, canonicalReplyBytes(reply));\n return { ...reply, hmac_signature: signature };\n}\n\n/**\n * Verify a reply's own signature — the check the server performs, exposed so an\n * SDK test (or a proxy) can run it locally.\n */\nexport function reactorReplySignatureValid(reply: ReactorReply, signingKey: Buffer): boolean {\n if (typeof reply.hmac_signature !== 'string') return false;\n return verifyPayload(signingKey, canonicalReplyBytes(reply), reply.hmac_signature);\n}\n\n/**\n * HKDF-SHA256 is **not** performed by this SDK: §8.1 assumes the per-tenant\n * subkey is provisioned out of band, and {@link reactorServe} takes that\n * already-derived key. This helper exists only so a caller can fingerprint the\n * key they were handed for an operational log without ever printing it.\n *\n * The digest is truncated to eight hex characters — enough to tell two keys\n * apart in a log line, far too little to attack.\n */\nexport function signingKeyFingerprint(signingKey: Buffer): string {\n return createHash('sha256').update(signingKey).digest('hex').slice(0, 8);\n}\n","// `reactorServe` — the SDK reactor runtime (CONTRACT.md §22.10).\n//\n// One helper. It connects (TLS per §8b and §6), consumes the SERVER-DECLARED\n// queue, and for each delivery: verifies §8 v2 (`key_version`, MAC, freshness,\n// nonce), decodes the event, dispatches to a user-supplied handler, then signs\n// and publishes the reply. It drains in-flight events on shutdown per §18.\n//\n// ## The four rules on the helper itself (§22.10)\n//\n// 1. It declares no topology. There is no `assertQueue`, `assertExchange` or\n// `bindQueue` anywhere in this module, and the channel seam it is written\n// against (`ReactorChannel`) exposes no such operation — so the rule is\n// structural rather than remembered. A reactor that can bind is a reactor\n// that can bind itself to `*.token.pre_issue`.\n// 2. It fails closed on its own errors. A handler that throws, a payload that\n// will not decode, a window that has already closed — every one of them\n// produces NO REPLY, letting the server's `failure_policy` decide.\n// Answering `allow` on behalf of a handler that crashed would override the\n// operator's `fail_closed` setting from inside the library.\n// 3. It does not filter a patch. A handler's patch is published exactly as\n// returned, forbidden keys and all (§22.4 rule 1).\n// 4. It honours `timeout_ms`. The handler runs under the event's own window,\n// and a reply whose window has closed is abandoned rather than published\n// late.\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../../core/index.js';\nimport { TelemetryDispatcher, type TelemetryHook } from '../../core/index.js';\nimport { InMemoryNonceStore, type NonceStore } from '../consumer.js';\nimport { buildAmqpConnectOptions, type AmqpTlsOptions } from '../transport.js';\nimport {\n REACTOR_FRESHNESS_SKEW_MS,\n buildReactorReply,\n reactorQueueName,\n signReactorReply,\n verifyEvent,\n type ReactorEvent,\n} from './protocol.js';\nimport { REACTOR_EVENTS, eventSpec, type ReactorMode } from './registry.js';\n\n/** Telemetry operation name for one reactor dispatch (§19.1). */\nconst TELEMETRY_OPERATION = 'reactorDispatch';\n\n// ---------------------------------------------------------------------------\n// The handler's answer\n// ---------------------------------------------------------------------------\n\n/**\n * What a handler decided about one event (CONTRACT.md §22.10).\n *\n * Three answers plus one absence. `allow`, `deny` and `mutate` are the three the\n * wire carries; `abstain` is the *absence* of a reply, which the server resolves\n * through the registration's `failure_policy` (§22.8) exactly as it resolves a\n * timeout.\n *\n * Build one with {@link allow}, {@link requireStepUp}, {@link deny} or\n * {@link mutate} rather than by hand.\n */\nexport type ReactorDecision =\n | {\n readonly kind: 'allow';\n /**\n * Proceed **only after step-up authentication**. `login.post_auth` only —\n * it is not a separate decision value, and sending it on any other event\n * is refused (§22.4 rule 3).\n */\n readonly requireMfa: boolean;\n }\n | {\n readonly kind: 'deny';\n /**\n * Audited reason. A deny with no reason still denies; the server\n * substitutes `\"denied by reactor\"` when it is absent.\n */\n readonly reason?: string;\n }\n | {\n readonly kind: 'mutate';\n /**\n * The fields to set — a flat `string → string` map. Published\n * **unfiltered**: one forbidden key rejects the whole patch server-side,\n * and pruning it here would leave you believing a field was set when it\n * was dropped (§22.4 rule 1). Check it yourself with `patchFieldAllowed`\n * if you want to know before you send.\n */\n readonly patch: Record<string, string>;\n }\n | {\n /**\n * Publish nothing at all.\n *\n * The right answer when the window has already closed (§22.3: shed load\n * rather than answer into a closed window) or when the handler cannot\n * decide. It is **not** a quiet `allow`: the server applies the\n * registration's `failure_policy`, which for every event except\n * `token.pre_issue` defaults to `fail_closed`.\n */\n readonly kind: 'abstain';\n };\n\n/** Proceed unchanged. */\nexport function allow(): ReactorDecision {\n return { kind: 'allow', requireMfa: false };\n}\n\n/** Proceed, but demand step-up authentication first. `login.post_auth` only. */\nexport function requireStepUp(): ReactorDecision {\n return { kind: 'allow', requireMfa: true };\n}\n\n/**\n * Refuse. Pass a reason for the audit trail; omitting it still denies, and the\n * audit record reads `\"denied by reactor\"`.\n */\nexport function deny(reason?: string): ReactorDecision {\n return reason === undefined ? { kind: 'deny' } : { kind: 'deny', reason };\n}\n\n/** Proceed, applying a patch. */\nexport function mutate(patch: Record<string, string>): ReactorDecision {\n return { kind: 'mutate', patch };\n}\n\n/** Publish nothing; let the registration's `failure_policy` decide. */\nexport function abstain(): ReactorDecision {\n return { kind: 'abstain' };\n}\n\n/**\n * A reactor handler: one function from a verified event to one of three answers\n * (CONTRACT.md §22.10).\n */\nexport type ReactorHandler = (event: ReactorEvent) => ReactorDecision | Promise<ReactorDecision>;\n\n// ---------------------------------------------------------------------------\n// The channel seam\n// ---------------------------------------------------------------------------\n\n/**\n * The operations one reactor delivery needs — **and no others**.\n *\n * There is deliberately no `assertQueue`, `assertExchange` or `bindQueue` here:\n * §22.1's \"actors consume; they never declare topology\" is enforced by the\n * seam's shape, so it cannot be violated by a later edit that forgets the rule.\n * `amqplib`'s `Channel` satisfies it structurally; tests provide a recording\n * fake that never touches a broker.\n */\nexport interface ReactorChannel {\n /** `channel.ack(msg)` — `allUpTo` intentionally omitted/false. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans. */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n /** Publish the signed reply to the `reply_to` queue, echoing the correlation id. */\n sendToQueue(\n queue: string,\n content: Buffer,\n options?: { correlationId?: string; contentType?: string },\n ): boolean;\n}\n\n/** Where this runtime writes its security events. */\nexport interface ReactorLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n// ---------------------------------------------------------------------------\n// Per-delivery dispatch\n// ---------------------------------------------------------------------------\n\n/** Everything one dispatch needs that does not come from the delivery. */\nexport interface ReactorDispatchContext {\n /** The tenant's HKDF-derived AMQP subkey. */\n readonly signingKey: Buffer;\n /** The tenant this reactor is registered in. */\n readonly tenantId: string;\n /** `intercept` (answers) or `listen` (observes, publishes nothing). */\n readonly mode: ReactorMode;\n /** `issued_at` acceptance window, in milliseconds. */\n readonly skewMs: number;\n /** Shared across every delivery on one consumer, or replay dedup does nothing. */\n readonly nonceStore: NonceStore;\n readonly logger?: ReactorLogger;\n readonly telemetry?: TelemetryDispatcher;\n}\n\n/**\n * Verify one delivery, dispatch it to `handler`, and publish the answer.\n *\n * Every path that cannot produce a **usable** reply publishes nothing at all,\n * which is what hands the decision to the registration's `failure_policy`\n * (§22.8) rather than to this library.\n *\n * Exported because it is the separately-testable unit backing\n * {@link reactorServe}'s per-message loop, mirroring the §8 consumer's\n * `verifyAndDispatch`.\n */\nexport async function dispatchReactorDelivery(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n handler: ReactorHandler,\n): Promise<void> {\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n reject(channel, msg, ctx, 'malformed', 'reactor delivery body failed JSON parse');\n return;\n }\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n reject(channel, msg, ctx, 'malformed', 'reactor delivery body is not a JSON object');\n return;\n }\n\n // §22.3, in order: key_version, MAC, freshness. Only then is anything in the\n // payload looked at.\n const verified = verifyEvent(body, ctx.signingKey, Date.now(), ctx.skewMs);\n if (!verified.ok) {\n reject(channel, msg, ctx, verified.rejection, 'reactor event failed §8 v2 verification');\n return;\n }\n const event = verified.event;\n\n // The fourth §22.3 check: the nonce seen-set.\n if (ctx.nonceStore.checkAndRecord(event.nonce, ctx.skewMs * 2)) {\n reject(channel, msg, ctx, 'replayed_nonce', 'reactor event nonce was already seen');\n return;\n }\n\n // A queue is per-tenant and the subkey is per-tenant, so this can only fire on\n // a misconfiguration — but a reactor answering for a tenant it was not\n // configured as is exactly the confusion §22.1 refuses to allow.\n if (event.tenant_id !== ctx.tenantId) {\n reject(\n channel,\n msg,\n ctx,\n 'malformed',\n 'reactor event names a different tenant than this reactor is configured for',\n );\n return;\n }\n\n const startedAt = Date.now();\n const deadline = startedAt + event.timeout_ms;\n const eventLabel = registryLabel(event.event);\n ctx.telemetry?.emit({\n type: 'requestStart',\n operation: TELEMETRY_OPERATION,\n method: 'AMQP',\n pathTemplate: eventLabel,\n attempt: 1,\n });\n\n // §22.10 rules 2 and 4 together: the handler runs inside the window the server\n // declared, and a throw is caught rather than propagated — both resolve to *no\n // reply*, never to a synthesized `allow`.\n let decision: ReactorDecision | undefined;\n try {\n decision = await withDeadline(handler(event), event.timeout_ms);\n } catch (err) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'reactor handler threw or outran timeout_ms; publishing no reply so the registration’s failure_policy decides',\n {\n event: event.event,\n correlationId: event.correlation_id,\n timeoutMs: event.timeout_ms,\n error: err instanceof Error ? err.message : String(err),\n },\n );\n }\n\n ctx.telemetry?.emit({\n type: 'requestEnd',\n operation: TELEMETRY_OPERATION,\n method: 'AMQP',\n pathTemplate: eventLabel,\n attempt: 1,\n durationMs: Date.now() - startedAt,\n outcome: decision === undefined ? 'failure' : 'success',\n });\n\n // A listener never publishes: the server does not wait for it and does not\n // read a reply, so anything it sent would be noise on a queue nobody is\n // draining (§22.5).\n if (ctx.mode === 'listen') {\n channel.ack(msg);\n return;\n }\n\n if (decision !== undefined) {\n publishAnswer(channel, msg, ctx, event, decision, deadline);\n }\n\n // The event verified and was consumed. Acking is what keeps `last_seen_at`\n // moving — a heartbeat derived from real work (§22.9) — and requeueing an\n // event whose correlation is already spent would only re-run a handler against\n // a window that has closed.\n channel.ack(msg);\n}\n\n/** Build, sign and publish the reply for `decision`, or publish nothing and say why. */\nfunction publishAnswer(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n event: ReactorEvent,\n decision: ReactorDecision,\n deadlineMs: number,\n): void {\n if (decision.kind === 'abstain') {\n return;\n }\n\n let requireMfa = false;\n let reason: string | undefined;\n let patch: Record<string, string> | undefined;\n let wire: 'allow' | 'deny' | 'mutate';\n\n if (decision.kind === 'allow') {\n wire = 'allow';\n requireMfa = decision.requireMfa;\n } else if (decision.kind === 'deny') {\n wire = 'deny';\n reason = decision.reason;\n } else {\n wire = 'mutate';\n patch = decision.patch;\n if (Object.keys(patch).length === 0) {\n // `mutate` with an empty patch is `malformed_mutation` server-side (§22.4\n // row 10). Refusing it here is not filtering — no field is being dropped,\n // the reply has no content to carry.\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'handler returned a mutation with an empty patch (malformed_mutation); publishing no reply',\n { event: event.event, correlationId: event.correlation_id },\n );\n return;\n }\n }\n\n // §22.4 row 7 / rule 3: `require_mfa` rides on `allow`, on `login.post_auth`,\n // and nowhere else. §22.13 allows an SDK to refuse this client-side; doing so\n // puts the mistake in the reactor author's log instead of only in the server's\n // audit trail.\n if (requireMfa && event.event !== REACTOR_EVENTS.LOGIN_POST_AUTH) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'require_mfa is only valid on login.post_auth (require_mfa_not_supported); publishing no reply',\n { event: event.event, correlationId: event.correlation_id },\n );\n return;\n }\n\n const reply = signReactorReply(\n buildReactorReply(event, { decision: wire, reason, patch, requireMfa }),\n ctx.signingKey,\n );\n\n // §22.3 / §22.10 rule 4: a late reply is discarded, and the CPU spent\n // producing it was spent for nothing. Do not spend the network on it too.\n if (Date.now() >= deadlineMs) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'the event’s window closed before the reply was ready; not publishing',\n {\n event: event.event,\n correlationId: event.correlation_id,\n timeoutMs: event.timeout_ms,\n },\n );\n return;\n }\n\n const replyTo = msg.properties.replyTo;\n if (typeof replyTo !== 'string' || replyTo.length === 0) {\n ctx.logger?.warn(\n 'axiam_sdk.reactor',\n 'delivery carried no reply_to property; nowhere to publish the reply',\n { correlationId: event.correlation_id },\n );\n return;\n }\n\n // The AMQP property is the RPC convention; what the server AUTHENTICATES is\n // the correlation_id inside the signed body, which `buildReactorReply` copied\n // from the event.\n const propertyCorrelation =\n typeof msg.properties.correlationId === 'string'\n ? msg.properties.correlationId\n : event.correlation_id;\n\n channel.sendToQueue(replyTo, Buffer.from(JSON.stringify(reply), 'utf8'), {\n correlationId: propertyCorrelation,\n contentType: 'application/json',\n });\n}\n\n/**\n * Nack without requeue and log the reason. The reason never carries the signing\n * key, and never the received or expected MAC.\n */\nfunction reject(\n channel: ReactorChannel,\n msg: ConsumeMessage,\n ctx: ReactorDispatchContext,\n rejection: string,\n message: string,\n): void {\n ctx.logger?.warn('axiam_sdk.security', `${message}; nacking without requeue`, {\n timestamp: new Date().toISOString(),\n rejection,\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n channel.nack(msg, false, false);\n}\n\n/**\n * Map a wire event name onto the registry's own string, so a telemetry label can\n * never be an attacker-chosen string or a cardinality bomb.\n */\nfunction registryLabel(name: string): string {\n return eventSpec(name)?.name ?? 'unknown_event';\n}\n\n/**\n * Settle `work`, or reject once `timeoutMs` has elapsed.\n *\n * The timer is always cleared — a pending `setTimeout` would keep a Node process\n * alive past the shutdown §18 promises is deterministic.\n */\nfunction withDeadline<T>(work: T | Promise<T>, timeoutMs: number): Promise<T> {\n return new Promise<T>((resolve, reject_) => {\n const timer = setTimeout(() => {\n reject_(new Error(`reactor handler exceeded timeout_ms=${timeoutMs}`));\n }, Math.max(timeoutMs, 0));\n Promise.resolve(work).then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject_(err instanceof Error ? err : new Error(String(err)));\n },\n );\n });\n}\n\n// ---------------------------------------------------------------------------\n// reactorServe\n// ---------------------------------------------------------------------------\n\n/** How to reach the broker and which reactor this process is (§22.1, §22.9). */\nexport interface ReactorConfig {\n /**\n * Broker URL. Must be `amqps://` (§8b rules 1 and 5) — there is no\n * verification-skip switch and no plaintext fallback, and this is now\n * *enforced* before the socket opens rather than merely stated here.\n */\n readonly amqpUrl: string;\n /**\n * TLS material for {@link amqpUrl} (§8b).\n *\n * Optional. With none supplied the broker is verified against Node's bundled\n * roots, which is correct for a publicly-issued broker certificate. Set\n * {@link AmqpTlsOptions.caCert} for a privately-issued one — the common case\n * for an in-cluster broker, and why §8b rule 2 is a MUST — and\n * `clientCert`/`clientKey` together for mutual TLS toward the broker\n * (rule 3).\n */\n readonly tls?: AmqpTlsOptions;\n /** The tenant this reactor is registered in. */\n readonly tenantId: string;\n /**\n * This reactor's registration id, from `POST /api/v1/reactors` (§22.9).\n *\n * It names the **one** queue this process may consume. Passing another\n * reactor's id is not a supported way to share a runtime: §22.1 forbids\n * deriving a queue name for a reactor other than the one you are.\n */\n readonly reactorId: string;\n /**\n * The tenant's HKDF-derived AMQP subkey (§8 v2, §22.2) — **not** the master\n * key. Obtain it from the AXIAM management API for this tenant; hard-coding\n * one is prohibited. Wrapped in `Sensitive` (§22.12) so it cannot be logged,\n * printed or serialized by accident.\n */\n readonly signingKey: Sensitive<Buffer>;\n /**\n * `intercept` (default) or `listen`.\n *\n * In `listen` mode the runtime publishes **nothing**: a listener cannot affect\n * any outcome, and §22.5 requires the handler be written idempotently because\n * a redelivery after a broker hiccup is normal.\n */\n readonly mode?: ReactorMode;\n /**\n * Override the ±300 s `issued_at` acceptance window. The same window, doubled,\n * bounds how long a `nonce` is remembered for replay detection.\n */\n readonly skewMs?: number;\n /** Nonce dedup store. One is created and shared across the consumer by default. */\n readonly nonceStore?: NonceStore;\n readonly logger?: ReactorLogger;\n /**\n * A §19 telemetry hook. One `requestStart`/`requestEnd` pair is emitted per\n * dispatch, with the registry event name as the path template — a bounded\n * label set, never a correlation id.\n */\n readonly telemetryHook?: TelemetryHook;\n /**\n * Deterministic shutdown (§18). Aborting it cancels the consumer, waits for\n * every in-flight dispatch to finish — handler, signature and publish — and\n * only then closes the channel and connection. Shutdown drains rather than\n * truncates.\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Run a reactor: consume the server-declared queue, answer every event\n * (CONTRACT.md §22.10).\n *\n * `handler` is called **only** with an event whose `key_version`, MAC, freshness\n * and nonce have all passed. It returns one of {@link ReactorDecision}'s three\n * answers, or {@link abstain} to publish nothing.\n *\n * Resolves when `signal` aborts (after the drain) or when the broker closes the\n * connection.\n *\n * @example\n * ```ts\n * import { Sensitive } from 'axiam-sdk/amqp';\n * import { REACTOR_EVENTS, allow, deny, mutate, reactorServe } from 'axiam-sdk/amqp';\n *\n * await reactorServe(\n * {\n * amqpUrl: 'amqps://reactor:secret@broker.example.com:5671',\n * tenantId: '11111111-1111-1111-1111-111111111111',\n * reactorId: '99999999-9999-9999-9999-999999999999',\n * signingKey: new Sensitive(subkey),\n * },\n * (event) => {\n * if (event.event === REACTOR_EVENTS.TOKEN_PRE_ISSUE) {\n * return mutate({ 'ext.cost_center': '42' });\n * }\n * if (event.event === REACTOR_EVENTS.LOGIN_POST_AUTH && fromEmbargoedRegion(event)) {\n * return deny('embargoed region');\n * }\n * return allow();\n * },\n * );\n * ```\n *\n * ## Security\n *\n * The `payload`, `patch`, `reason` and `decision` are tenant business data:\n * readable by design (a handler that cannot inspect the event cannot decide\n * anything) but **not** logged at info level by this runtime, and they should not\n * be logged at info level by yours either (§22.12). The signing key is\n * `Sensitive` and never appears in a log line or an error payload.\n */\nexport async function reactorServe(config: ReactorConfig, handler: ReactorHandler): Promise<void> {\n const queue = reactorQueueName(config.tenantId, config.reactorId);\n const skewMs = config.skewMs ?? REACTOR_FRESHNESS_SKEW_MS;\n const ctx: ReactorDispatchContext = {\n signingKey: config.signingKey.expose(),\n tenantId: config.tenantId,\n mode: config.mode ?? 'intercept',\n skewMs,\n // One store shared across every delivery on this consumer — a fresh store\n // per message would defeat replay dedup entirely.\n nonceStore: config.nonceStore ?? new InMemoryNonceStore(),\n logger: config.logger,\n telemetry: config.telemetryHook ? new TelemetryDispatcher(config.telemetryHook) : undefined,\n };\n\n // §8b: a reactor connects across a trust boundary, and its reply is an\n // instruction to allow, deny or rewrite a token. Validated before dialling —\n // a plaintext URL or half a client identity is a configuration fault, and\n // discovering it as a connect-time network error tells nobody what to fix.\n const socketOptions = buildAmqpConnectOptions(\n config.amqpUrl,\n config.tls,\n 'reactorServe() amqpUrl',\n );\n const connection = await amqp.connect(config.amqpUrl, socketOptions);\n const channel: Channel = await connection.createChannel();\n\n // NOTE: there is no assertQueue / assertExchange / bindQueue here, and there\n // must never be one. §22.1: the server declares the exchange, the queue and\n // the bindings; actors consume.\n const inFlight = new Set<Promise<void>>();\n let stopped = false;\n\n const { consumerTag } = await channel.consume(queue, (msg) => {\n if (!msg) return;\n // A delivery that arrives after the signal is nacked back rather than\n // half-processed: §18's drain covers what is already in flight, not what\n // the broker pushed afterwards.\n if (stopped) {\n channel.nack(msg, false, true);\n return;\n }\n const work = dispatchReactorDelivery(channel, msg, ctx, handler).finally(() => {\n inFlight.delete(work);\n });\n inFlight.add(work);\n });\n\n const closed = new Promise<void>((resolve) => {\n connection.on('close', () => resolve());\n });\n\n const aborted = config.signal\n ? new Promise<void>((resolve) => {\n const signal = config.signal as AbortSignal;\n if (signal.aborted) {\n resolve();\n return;\n }\n signal.addEventListener('abort', () => resolve(), { once: true });\n })\n : new Promise<void>(() => {\n /* never resolves; only the connection closing ends the run */\n });\n\n await Promise.race([closed, aborted]);\n stopped = true;\n\n // Drain (§18): stop taking new deliveries, then let every dispatch already\n // running finish — handler, signature, publish — before tearing down.\n try {\n await channel.cancel(consumerTag);\n } catch {\n // The channel may already be gone if the connection closed on us; the\n // drain below is what matters.\n }\n await Promise.allSettled([...inFlight]);\n try {\n await channel.close();\n await connection.close();\n } catch {\n // Idempotent teardown: closing an already-closed channel or connection is\n // the state the caller asked for, not an error to surface.\n }\n}\n","// Declarative reactor handler binding — CONTRACT.md §22.14.\n//\n// `reactorServe` takes ONE function from an event to one answer, which is the\n// right shape for the wire and the wrong shape for the code. A reactor\n// registered for three events opens with a `switch (event.event)`, and that\n// switch carries two defects.\n//\n// The first is cheap: a misspelled event name is a valid string literal, matches\n// no case, and is discovered as an event that never fires. The second is not. It\n// is the `default:` arm, which is almost always written `return allow()`. That\n// answers on behalf of code that never ran — the defect §22.10 rule 2 forbids\n// the RUNTIME from committing, relocated into user code where the rule does not\n// reach it. An operator who set `fail_closed` on a registration has it defeated\n// by a `default` arm in a file they never read.\n//\n// `reactorHandlers` is the declarative form. It is PURE SUGAR (§22.14 rule 1):\n// it produces exactly the `ReactorHandler` `reactorServe` already takes, opens\n// nothing, verifies nothing, signs nothing, and does not filter a patch. What it\n// adds is the two answers the switch got wrong — an unregistered event name is\n// refused when you BIND it, and an event with no handler ABSTAINS.\n\nimport { REACTOR_EVENTS, eventSpec, type ReactorEventName } from './registry.js';\nimport { abstain, type ReactorDecision, type ReactorHandler } from './runtime.js';\nimport type { ReactorEvent } from './protocol.js';\n\n/**\n * One handler per hook event.\n *\n * The key type is {@link ReactorEventName}, so a misspelled event is a\n * **compile-time** error in TypeScript — and `reactorHandlers` re-checks at\n * runtime for JavaScript callers, who get no such help. Duplicate keys within a\n * single object literal are a compile-time error too (TS1117), which is §22.14\n * rule 3 enforced by the language; passing two groups that both bind the same\n * event is the case the runtime check exists for.\n */\nexport type ReactorHandlerMap = Partial<Record<ReactorEventName, ReactorHandler>>;\n\n/**\n * The event names `reactorHandlers` accepts, sorted.\n *\n * Built from what IS hookable, deliberately: §22.13 requires the three hot-path\n * operations to be absent from every event constant this SDK exposes, so a list\n * naming them — even only to say they are refused — is the thing that would\n * break it (§22.14 rule 2).\n */\nexport function hookableEvents(): readonly string[] {\n return Object.values(REACTOR_EVENTS).slice().sort();\n}\n\n/**\n * Compose one handler per event into the single handler `reactorServe` takes\n * (CONTRACT.md §22.14).\n *\n * ```ts\n * await reactorServe(options, reactorHandlers({\n * [REACTOR_EVENTS.TOKEN_PRE_ISSUE]: enrichToken,\n * [REACTOR_EVENTS.LOGIN_POST_AUTH]: screenLogin,\n * }));\n * ```\n *\n * Several groups may be passed, so handlers can be split across modules and\n * merged here:\n *\n * ```ts\n * reactorHandlers(tokenHandlers, loginHandlers)\n * ```\n *\n * @param groups one or more event → handler maps.\n * @returns the `ReactorHandler` `reactorServe` accepts.\n * @throws TypeError if a key is outside the §22.5 registry — which is also how\n * §22.7's three hot-path operations are refused, since they are in no registry\n * row — if a value is not a function, if two groups bind the same event, or if\n * nothing is bound at all.\n */\nexport function reactorHandlers(...groups: readonly ReactorHandlerMap[]): ReactorHandler {\n const bound = new Map<string, ReactorHandler>();\n\n for (const group of groups) {\n for (const [event, handler] of Object.entries(group)) {\n if (eventSpec(event) === undefined) {\n throw new TypeError(\n `${event} is not a hookable reactor event; the registry is [${hookableEvents().join(', ')}]`,\n );\n }\n if (typeof handler !== 'function') {\n throw new TypeError(`the handler bound to ${event} is not a function`);\n }\n if (bound.has(event)) {\n throw new TypeError(`reactor event ${event} is already bound`);\n }\n bound.set(event, handler);\n }\n }\n\n if (bound.size === 0) {\n throw new TypeError('reactorHandlers received no bindings; bind at least one event');\n }\n\n return async (event: ReactorEvent): Promise<ReactorDecision> => {\n const handler = bound.get(event.event);\n if (handler === undefined) {\n // §22.14 rule 4. NOT allow(): publishing nothing lets the registration's\n // `failure_policy` resolve this exactly as it resolves a timeout (§22.8),\n // and this function does not know what the registration was for. The\n // operator's policy does.\n return abstain();\n }\n // Awaited without a try/catch on purpose (§22.14 rule 5): a handler's own\n // rejection must reach the runtime unchanged so it publishes nothing.\n // Catching it here would satisfy the letter of §22.10 rule 2 while\n // defeating it.\n return await handler(event);\n };\n}\n\n"]}