axiam-sdk 1.3.1 → 1.4.0
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.
- package/README.md +130 -14
- package/dist/amqp/index.d.cts +384 -17
- package/dist/amqp/index.d.ts +384 -17
- package/dist/amqp/index.js +639 -66
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +631 -67
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
- package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
- package/dist/browser/index.d.cts +1 -1
- package/dist/browser/index.d.ts +1 -1
- package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
- package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
- package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
- package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
- package/dist/grpc/index.d.cts +5 -5
- package/dist/grpc/index.d.ts +5 -5
- package/dist/grpc/index.js +249 -18
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +249 -18
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +29 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
- package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
- package/dist/middleware/index.d.cts +220 -43
- package/dist/middleware/index.d.ts +220 -43
- package/dist/middleware/index.js +587 -149
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +579 -150
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +18 -4
- package/dist/nestjs/index.d.ts +18 -4
- package/dist/nestjs/index.js +20 -1
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +19 -2
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +5 -5
- package/dist/node/index.d.ts +5 -5
- package/dist/node/index.js +351 -66
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +348 -67
- package/dist/node/index.mjs.map +1 -1
- package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
- package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +29 -3
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +29 -3
- package/dist/rest/index.mjs.map +1 -1
- package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
- package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
- package/package.json +9 -9
package/dist/amqp/index.mjs.map
CHANGED
|
@@ -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":["amqp"],"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;AAwHO,I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"index.mjs","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"]}
|
|
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/authzResponse.ts","../../src/amqp/authzRequester.ts","../../src/amqp/reactor/registry.ts","../../src/amqp/reactor/protocol.ts","../../src/amqp/reactor/runtime.ts","../../src/amqp/reactor/handlers.ts"],"names":["TRAILING_SIGNATURE","createHmac","timingSafeEqual","reject","amqp","randomUUID"],"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;AAwHO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,KAAA;AAAA,EAET,WAAA,CAAY,SAAiB,KAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,EACpD;AACF,CAAA;;;ACzJO,IAAM,QAAA,GAAW,aAAA;AAExB,IAAM,mBAAA,mBAAsB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAyB5D,IAAM,YAAN,MAAmB;AAAA,EACf,MAAA;AAAA;AAAA,EAGT,YAAY,KAAA,EAAU;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA;AAAA,EAGA,QAAA,GAAmB;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA;AAAA,EAGA,MAAA,GAAiB;AACf,IAAA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AK,CAAA,kBAAA,CAAoB,CAAA;AAAA,MACvE;AACA,MAAA,IAAI,KAAA,CAAM,GAAA,CAAI,KAAK,CAAA,EAAG;AACpB,QAAA,MAAM,IAAI,SAAA,CAAU,CAAA,cAAA,EAAiB,KAAK,CAAA,iBAAA,CAAmB,CAAA;AAAA,MAC/D;AACA,MAAA,KAAA,CAAM,GAAA,CAAI,OAAO,OAAO,CAAA;AAAA,IAC1B;AAAA,EACF;AAEA,EAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AACpB,IAAA,MAAM,IAAI,UAAU,+DAA+D,CAAA;AAAA,EACrF;AAEA,EAAA,OAAO,OAAO,KAAA,KAAkD;AAC9D,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,GAAA,CAAI,KAAA,CAAM,KAAK,CAAA;AACrC,IAAA,IAAI,YAAY,MAAA,EAAW;AAKzB,MAAA,OAAO,OAAA,EAAQ;AAAA,IACjB;AAKA,IAAA,OAAO,MAAM,QAAQ,KAAK,CAAA;AAAA,EAC5B,CAAA;AACF","file":"index.mjs","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\n/**\n * Decode `bytes` as UTF-8, throwing on an invalid sequence. A leading byte-order\n * mark is kept (`ignoreBOM`), so the decoded text and the raw bytes always\n * agree; a BOM then makes the body fail to parse as JSON instead of being\n * silently dropped from one view of the message only.\n */\nexport function decodeUtf8Strict(bytes: Uint8Array): string {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\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\nimport type { AuthzResponseVerifier } from './authzResponse.js';\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 always rejected (no lenient mode).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to the request's `reply_to` queue, else\n * `axiam.authz.response`.\n *\n * Server-signed from contract 1.68 (CONTRACT.md §8, \"Signed authorization\n * responses\"): it carries `tenant_id`, `nonce` and `hmac_signature`, bound to\n * the request it answers. Through 1.67 it carried none of them, so all three\n * are optional here. Never verify one by re-serializing this object — verify\n * the received bytes with {@link AuthzResponseVerifier}.\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n /** `allowed`, `no_grant`, `denied_by_rule`, `tenant_suspended`, or a code this SDK does not know (verbatim). */\n reason_code?: string;\n /** The `tenant_id` of the request this answers (contract 1.68). */\n tenant_id?: string;\n /** The `nonce` of the request this answers, echoed (contract 1.68). */\n nonce?: string;\n /** HMAC-SHA256 over the received bytes minus this trailing member, under the tenant subkey (contract 1.68). */\n hmac_signature?: 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) — the messages a producer\n * signs. `AuthzResponse` is server-signed from contract 1.68 but verified over\n * its received bytes by {@link AuthzResponseVerifier}, not by this path;\n * `NotificationEvent` carries no `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. The\n// consumer is typed (D-9): it is configured with the ONE signed type it\n// consumes and accepts that type's layout only. On any refusal (a body that is\n// not one well-formed JSON object starting with `{` — a byte-order mark is\n// refused, never stripped — a missing signature (no lenient mode, §8 rule 3), a\n// layout that is not the configured type's, a signature mismatch, a verified\n// body that does not decode, or a failed v2 gate) the delivery is nacked\n// WITHOUT requeue and ONE event is logged (D-8): timestamp, exchange, routing\n// key, the consumer's own tenant and a closed reason — never a signature, a\n// nonce, a key or any member of the body. Only a verified delivery reaches the\n// 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 over the received bytes (the body minus its trailing\n// `hmac_signature` member; axiam#882), `nonce`/`issued_at` are already\n// covered by the HMAC bytes with no canonicalization change — only the three\n// 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 { decodeUtf8Strict, 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\n/** The two signed event types an event consumer can be configured for (CONTRACT.md §8 step 2c, D-9). */\nexport type EventType = 'AuthzRequest' | 'AuditEventMessage';\n\n/** The closed vocabulary of the discard event's `reason` (CONTRACT.md §8 rule 4, D-8). */\nexport type EventDiscardReason = 'malformed' | 'unsigned' | 'signature' | 'key_version' | 'stale' | 'replay';\n\nconst UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\nconst RFC3339 = /^\\d{4}-\\d{2}-\\d{2}[Tt]\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/;\n\ntype MemberKind = 'uuid' | 'string' | 'json' | 'u8' | 'timestamp';\n\n/**\n * Step 2f decode: the verified canonical bytes decode into the configured\n * type, member by member, as the server's struct does (`Uuid`, `String`,\n * `u8`, `DateTime<Utc>`, `serde_json::Value`).\n */\nfunction decodesAs(kinds: Readonly<Record<string, MemberKind>>, body: Record<string, unknown>): boolean {\n for (const [name, value] of Object.entries(body)) {\n switch (kinds[name]) {\n case 'uuid':\n if (typeof value !== 'string' || !UUID.test(value)) return false;\n break;\n case 'string':\n if (typeof value !== 'string') return false;\n break;\n case 'u8':\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 255) return false;\n break;\n case 'timestamp':\n if (typeof value !== 'string' || !RFC3339.test(value) || Number.isNaN(Date.parse(value))) return false;\n break;\n case 'json':\n if (value === null) return false; // an omitted member, never `null` (§8 wire form)\n break;\n default:\n return false;\n }\n }\n return true;\n}\n\n/** The members of each type, in declaration order (CONTRACT.md §8 \"Exact signed field order\"); a name ending in `?` is optional. */\ninterface EventSpec {\n readonly layout: readonly string[];\n readonly kinds: Readonly<Record<string, MemberKind>>;\n}\nconst EVENT_SPECS: Readonly<Record<EventType, EventSpec>> = {\n AuthzRequest: {\n layout: ['correlation_id', 'tenant_id', 'subject_id', 'action', 'resource_id', 'scope?', 'key_version', 'nonce', 'issued_at'],\n kinds: {\n correlation_id: 'uuid',\n tenant_id: 'uuid',\n subject_id: 'uuid',\n action: 'string',\n resource_id: 'uuid',\n scope: 'string',\n key_version: 'u8',\n nonce: 'uuid',\n issued_at: 'timestamp',\n },\n },\n AuditEventMessage: {\n layout: [\n 'tenant_id',\n 'actor_id',\n 'actor_type',\n 'action',\n 'resource_id?',\n 'outcome',\n 'ip_address?',\n 'metadata?',\n 'key_version',\n 'nonce',\n 'issued_at',\n ],\n kinds: {\n tenant_id: 'uuid',\n actor_id: 'uuid',\n actor_type: 'string',\n action: 'string',\n resource_id: 'uuid',\n outcome: 'string',\n ip_address: 'string',\n metadata: 'json',\n key_version: 'u8',\n nonce: 'uuid',\n issued_at: 'timestamp',\n },\n },\n};\n\n/**\n * Gates (6)–(8), checked only AFTER the HMAC verified and the body decoded.\n * Returns the failing gate's reason, or `undefined` when all three pass; the\n * nonce is recorded last, so a body refused at (6) or (7) leaves none behind.\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): 'key_version' | 'stale' | 'replay' | undefined {\n if ((body.key_version as number) < 2) return 'key_version';\n if (Math.abs(Date.now() - Date.parse(body.issued_at as string)) > skewMs) return 'stale';\n if (nonceStore.checkAndRecord(body.nonce as string, skewMs * 2)) return 'replay';\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 /**\n * The consumer's OWN tenant: the tenant whose signing subkey `signingKey`\n * is (CONTRACT.md §8 rule 1). Every discard event names it as `tenantId`;\n * a `tenant_id` read from a message body is never logged (D-8).\n */\n tenantId: string;\n /**\n * The ONE signed type this consumer consumes (CONTRACT.md §8 step 2c, D-9).\n * A body with the layout of any other signed type — the other event type, an\n * `AuthzResponse`, a reactor message — is refused as `malformed` before the\n * HMAC is computed. An application consuming both types runs two consumers.\n */\n eventType: EventType;\n logger?: ConsumeLogger;\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/** `,\"hmac_signature\":\"<64 hex>\"}` at the very end of the body, nothing after it (CONTRACT.md §8 step 2b). */\nconst TRAILING_SIGNATURE = /,\"hmac_signature\":\"([0-9a-fA-F]{64})\"\\}$/;\n\n/** Whether `names` (top-level member names, in wire order) fit `layout` exactly. */\nfunction matchesSignedLayout(names: readonly string[], layout: readonly string[]): boolean {\n let i = 0;\n for (const declared of layout) {\n const optional = declared.endsWith('?');\n const name = optional ? declared.slice(0, -1) : declared;\n if (i < names.length && names[i] === name) i += 1;\n else if (!optional) return false;\n }\n return i === names.length;\n}\n\n/**\n * A configuration fault, found before any delivery is read: the consumer needs\n * its own tenant (D-8) and the one type it consumes (D-9).\n */\nfunction assertConsumeConfig(options: ConsumeOptions, where: string): void {\n if (typeof options?.tenantId !== 'string' || options.tenantId === '') {\n throw new TypeError(`${where}: options.tenantId (the consumer's own tenant) is required`);\n }\n if (!Object.prototype.hasOwnProperty.call(EVENT_SPECS, options.eventType)) {\n throw new TypeError(`${where}: options.eventType must be 'AuthzRequest' or 'AuditEventMessage'`);\n }\n}\n\n/**\n * Whether any JSON object in `text` (already known to be well-formed JSON)\n * repeats a key. Keys are compared after unescaping, so `\"a\"` and `\"\\u0061\"`\n * are the same key.\n */\nfunction hasDuplicateKey(text: string): boolean {\n const stack: Array<Set<string> | null> = [];\n let i = 0;\n const n = text.length;\n while (i < n) {\n const c = text[i];\n if (c === '\"') {\n let j = i + 1;\n while (j < n && text[j] !== '\"') {\n j += text[j] === '\\\\' ? 2 : 1;\n }\n const raw = text.slice(i, j + 1);\n i = j + 1;\n const top = stack[stack.length - 1];\n if (top !== undefined && top !== null) {\n let k = i;\n while (k < n && /\\s/.test(text[k])) k += 1;\n if (text[k] === ':') {\n const key = JSON.parse(raw) as string;\n if (top.has(key)) return true;\n top.add(key);\n }\n }\n continue;\n }\n if (c === '{') stack.push(new Set());\n else if (c === '[') stack.push(null);\n else if (c === '}' || c === ']') stack.pop();\n i += 1;\n }\n return false;\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 assertConsumeConfig(options, 'verifyAndDispatch()');\n const { logger } = options;\n const spec = EVENT_SPECS[options.eventType];\n\n // CONTRACT.md §8 step 2 / axiam#882: verify over the RECEIVED bytes — the body\n // with its trailing `,\"hmac_signature\":\"<hex>\"}` member removed — never over a\n // re-serialization, which disagrees with serde_json on floats (`1.0`),\n // integer-like keys (reordered) and large integers. The handler is given the\n // value decoded from those same verified bytes, so what is verified and what\n // is delivered cannot differ.\n //\n // Every discard is ONE call of `refuse` (D-8): nack first (a logger that\n // throws must not leave the delivery unacked), then exactly the five members\n // of the event — the tenant is this consumer's own, never read from the body.\n const refuse = (reason: EventDiscardReason): void => {\n try {\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n } catch {\n // channel already closed: nothing more can be done for this delivery\n }\n try {\n logger?.warn('axiam_sdk.security', `AMQP event discarded (${reason})`, {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n tenantId: options.tenantId,\n reason,\n });\n } catch {\n // an integrator logger's failure is not the delivery's problem\n }\n };\n\n // (1) one JSON object whose FIRST BYTE is its opening `{` (a byte-order mark,\n // whitespace or any other prefix is refused, never stripped; D-10), nothing\n // after its `}`. Invalid UTF-8 is refused rather than decoded to U+FFFD, which\n // would make the handler's value differ from the bytes.\n let text: string;\n try {\n text = decodeUtf8Strict(msg.content);\n } catch {\n refuse('malformed');\n return;\n }\n let whole: unknown;\n try {\n whole = JSON.parse(text);\n } catch {\n whole = undefined;\n }\n if (\n typeof whole !== 'object' ||\n whole === null ||\n Array.isArray(whole) ||\n !text.startsWith('{') ||\n !text.endsWith('}')\n ) {\n refuse('malformed');\n return;\n }\n\n // (2) no top-level `hmac_signature` member: unsigned, whatever else is wrong\n // (§8 rule 3: there is no lenient mode).\n if (!Object.prototype.hasOwnProperty.call(whole, 'hmac_signature')) {\n refuse('unsigned');\n return;\n }\n\n // (3) everything else steps 2a-2c refuse: a repeated member at any depth, a\n // signature that is not the trailing 64-hex member (null, non-string, not\n // last), and a layout that is not the configured type's.\n if (hasDuplicateKey(text)) {\n refuse('malformed');\n return;\n }\n const trailing = TRAILING_SIGNATURE.exec(msg.content.toString('latin1'));\n const sig = (whole as Record<string, unknown>).hmac_signature;\n if (trailing === null || sig !== trailing[1]) {\n refuse('malformed');\n return;\n }\n // latin1 maps one byte to one unit and the member is ASCII, so the match\n // index is a byte index.\n const canonical = Buffer.concat([msg.content.subarray(0, trailing.index), Buffer.from('}', 'ascii')]);\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(decodeUtf8Strict(canonical)) as Record<string, unknown>;\n } catch {\n refuse('malformed');\n return;\n }\n // Step 2c, typed (D-9): the configured type's layout ONLY, before the HMAC\n // and before anything is decoded.\n if (!matchesSignedLayout(Object.keys(body), spec.layout)) {\n refuse('malformed');\n return;\n }\n\n // (4) HMAC over the canonical bytes, compared in constant time.\n if (!verifyPayload(signingKey, canonical, trailing[1])) {\n refuse('signature');\n return;\n }\n\n // (5) the verified bytes decode into the configured type. `key_version` is a `u8`: only an\n // integer literal decodes (`2.0` and `2e0` parse to 2 in JavaScript but not in serde), and the\n // last three members are fixed, so its raw token is read from the end of the canonical bytes.\n const keyVersionToken = /,\"key_version\":([^,]*),\"nonce\":\"[^\"]*\",\"issued_at\":\"[^\"]*\"\\}$/.exec(\n canonical.toString('utf8'),\n );\n if (keyVersionToken === null || !/^\\d+$/.test(keyVersionToken[1]) || !decodesAs(spec.kinds, body)) {\n refuse('malformed');\n return;\n }\n\n // (6)-(8) NEW-4 (CONTRACT.md §8 v2, hard cutover): key_version, freshness,\n // replay — three ADDITIONAL gates over bytes already verified; the nonce is\n // recorded only when all of them pass.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const gate = checkReplayProtection(body, skewMs, nonceStore);\n if (gate !== undefined) {\n refuse(gate);\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 try {\n channel.nack(msg, false, false);\n } catch {\n // channel already closed\n }\n try {\n // The error's NAME only: its message is application text and may hold body content.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n tenantId: options.tenantId,\n error: err instanceof Error ? err.name : 'non-Error',\n });\n } catch {\n // an integrator logger's failure is not the delivery's problem\n }\n return;\n }\n\n try {\n channel.ack(msg);\n } catch {\n // The message was verified and processed; a closed channel is not a discard.\n }\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 assertConsumeConfig(options, 'consume()');\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 verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions).catch(() => {\n // Never an unhandled rejection (it would take the process down and the\n // unacked delivery would come back): nack without requeue first, then\n // log without body content; neither step may throw out of here.\n try {\n channel.nack(msg, false, false);\n } catch {\n // channel already closed\n }\n try {\n sharedOptions.logger?.warn('axiam_sdk.security', 'AMQP event discarded (malformed)', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n tenantId: sharedOptions.tenantId,\n reason: 'malformed' satisfies EventDiscardReason,\n });\n } catch {\n // an integrator logger's failure is not the delivery's problem\n }\n });\n });\n}\n","// Signed AMQP authorization responses (CONTRACT.md §8, \"Signed authorization\n// responses\", contract 1.68; SA-15, N2, D-9).\n//\n// From 1.68 the server signs every `AuthzResponse` with the requester's own\n// tenant subkey and binds it to the request it answers (`tenant_id`, `nonce`,\n// `correlation_id`). This module is the requester half: it verifies a received\n// response and matches it to a request the caller still has outstanding.\n//\n// The one rule that differs from every other §8 message: the canonical bytes\n// are the RECEIVED bytes with the trailing `,\"hmac_signature\":\"<64 hex>\"`\n// member removed — never a re-serialization of the parsed members. `reason`\n// echoes the requested action, which the requester chooses, and JSON encoders\n// disagree on escaping, so a re-serialization fails to verify the genuine\n// answer (contract vector 4). And the response handed back is parsed from\n// those same verified bytes, so what is verified and what is delivered cannot\n// differ (the Go SDK's C2).\n//\n// `AuthzRequester` (authzRequester.ts) is built on this class. An application\n// that publishes its own requests registers each with `expect()` and hands\n// every delivery from its private reply queue to `verify()` (or `settle()`,\n// which also acks/nacks).\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport type { ConsumeLogger } from './consumer.js';\nimport { decodeUtf8Strict } from './hmac.js';\n\n/** The members of a request that its response must echo (§8 rule 3). */\nexport interface OutstandingAuthzRequest {\n /** The request's `correlation_id`. */\n correlation_id: string;\n /** The request's `nonce`, which a 1.68 response echoes. */\n nonce: string;\n /** The request's `tenant_id`; MUST be the verifier's own tenant. */\n tenant_id: string;\n}\n\n/** A response that passed §8 rules 1–3, parsed from the bytes that were verified. */\nexport interface VerifiedAuthzResponse {\n /** Echo of the request's `correlation_id`. */\n correlation_id: string;\n /** The decision. */\n allowed: boolean;\n /** Human-readable reason, when the server gave one. */\n reason?: string;\n /** Machine-readable reason (`allowed`, `no_grant`, `denied_by_rule`, `tenant_suspended`, or a code this SDK does not know, verbatim). */\n reason_code?: string;\n /** The tenant the response answers for; equals the verifier's tenant. */\n tenant_id: string;\n /** Echo of the request's `nonce`. */\n nonce: string;\n}\n\n/** Why a response was discarded. Never carries a signature value. */\nexport type AuthzResponseRejection =\n /**\n * Not JSON, or missing / ill-typed `correlation_id`, `allowed`, `tenant_id`,\n * `nonce`, or an `hmac_signature` member that does not end the body or is\n * not 64 hex digits (rule 1).\n */\n | 'malformed'\n /** No `hmac_signature` member at all: no AXIAM server sends one to a reply queue (CONTRACT.md §8, contract 1.69). */\n | 'unsigned'\n /** The HMAC does not verify under this tenant's subkey (rule 2). */\n | 'signature'\n /** `tenant_id` is not this verifier's tenant (rule 3). */\n | 'tenant'\n /** No outstanding request has this `correlation_id` and `nonce` (rule 3). */\n | 'unknown_request';\n\n/** The outcome of {@link AuthzResponseVerifier.verify}. */\nexport type AuthzResponseVerdict =\n | {\n /** The response passed every rule; its request has been retired. */\n accepted: true;\n /** The verified response. */\n response: VerifiedAuthzResponse;\n }\n | {\n /** The response was discarded: never an allow, and its request stays outstanding. */\n accepted: false;\n /** Which rule failed. */\n reason: AuthzResponseRejection;\n };\n\n/** Configuration for an {@link AuthzResponseVerifier}. */\nexport interface AuthzResponseVerifierOptions {\n /**\n * The requester's own tenant subkey — the HKDF-derived per-tenant AMQP key\n * for `tenantId` and the `key_version` the requests were signed with\n * (currently `2`), never the master key (§8.1: provisioned out of band).\n */\n subkey: Sensitive<Buffer>;\n /** The requester's own tenant; every accepted response names it. */\n tenantId: string;\n /**\n * The requester's private reply queue (the `amq.gen-…` name it declared and\n * sent as `reply_to`). The discard event's routing key when\n * {@link AuthzResponseVerifier.verify} is called without a delivery: the\n * transport cannot report one, and every answer the requester can receive\n * arrives on this queue (§8 consumer obligation 4).\n */\n replyQueue?: string;\n /** Receives security events. Never receives a signature value or the key. */\n logger?: ConsumeLogger;\n}\n\n/**\n * Where a response was read from, for the security event a discarded response\n * logs (CONTRACT.md §8 rule 4 and consumer obligation 4: timestamp, exchange,\n * routing key, tenant, reason). {@link AuthzResponseVerifier.settle} takes\n * it from the delivery's `msg.fields`.\n */\nexport interface AuthzResponseDelivery {\n /** The exchange the response was published to (`''` for the default exchange). */\n exchange: string;\n /** The routing key it was published with (the reply queue's name on the default exchange). */\n routingKey: string;\n}\n\n/** The ack/nack subset of an amqplib `Channel` that {@link AuthzResponseVerifier.settle} needs. */\nexport interface SettleChannel {\n /** `channel.ack(msg)`. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)`. */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\n/** `,\"hmac_signature\":\"<64 hex>\"}` at the very end of the body, nothing after it. */\nconst TRAILING_SIGNATURE = /,\"hmac_signature\":\"([0-9a-fA-F]{64})\"\\}$/;\n\nconst isString = (value: unknown): value is string => typeof value === 'string';\n\n/**\n * Verifies signed `AuthzResponse` messages for one tenant and matches them to\n * the caller's outstanding requests (CONTRACT.md §8 rules 1–4, contract 1.68).\n *\n * @example\n * ```ts\n * const verifier = new AuthzResponseVerifier({ subkey, tenantId });\n * // when publishing a request (with an exclusive reply_to queue):\n * verifier.expect({ correlation_id, nonce, tenant_id: tenantId });\n * // for every delivery on that queue:\n * const verdict = verifier.settle(channel, msg);\n * if (verdict.accepted) resolvePending(verdict.response);\n * ```\n */\nexport class AuthzResponseVerifier {\n readonly #subkey: Sensitive<Buffer>;\n readonly #tenantId: string;\n readonly #tenantConfigured: string;\n readonly #replyQueue: string | undefined;\n readonly #logger: ConsumeLogger | undefined;\n /** correlation_id → nonce of each outstanding request. */\n readonly #outstanding = new Map<string, string>();\n\n /** @param options the tenant, its subkey, and the reply queue's name. */\n constructor(options: AuthzResponseVerifierOptions) {\n this.#subkey = options.subkey;\n this.#tenantConfigured = options.tenantId;\n this.#tenantId = options.tenantId.toLowerCase();\n this.#replyQueue = options.replyQueue;\n this.#logger = options.logger;\n }\n\n /**\n * Register a published request whose answer is awaited. Its `tenant_id`\n * must be this verifier's tenant.\n *\n * @throws RangeError when the request names another tenant.\n */\n expect(request: OutstandingAuthzRequest): void {\n if (request.tenant_id.toLowerCase() !== this.#tenantId) {\n throw new RangeError('AuthzResponseVerifier.expect: the request names another tenant');\n }\n this.#outstanding.set(request.correlation_id, request.nonce);\n }\n\n /** Stop waiting for `correlationId` (for example on the caller's own timeout). */\n forget(correlationId: string): void {\n this.#outstanding.delete(correlationId);\n }\n\n /** Number of requests still awaiting an answer. */\n get pending(): number {\n return this.#outstanding.size;\n }\n\n /**\n * Verify one received response body (CONTRACT.md §8 rules 1–4). On\n * acceptance the matching request is retired, so a second response for it\n * is dropped. On any failure nothing is retired — the genuine answer may\n * still arrive — and a security event is logged without either signature.\n *\n * @param delivery where the body was read from; the security event names\n * its exchange and routing key (§8 rule 4). {@link settle} passes it.\n * Without it the event reports `''` and `options.replyQueue` (`''` when\n * that is not set either).\n */\n verify(body: Buffer, delivery?: AuthzResponseDelivery): AuthzResponseVerdict {\n // Normative order (CONTRACT.md §8 consumer obligation 4): (1) not one JSON\n // object -> malformed; (2) no hmac_signature member -> unsigned, whatever\n // else is missing; (3) a bad signature member, or a missing / ill-typed\n // allowed, tenant_id, nonce or correlation_id -> malformed, BEFORE the\n // HMAC; (4) the HMAC fails -> signature; then tenant and unknown_request.\n let whole: unknown;\n let text: string;\n try {\n text = decodeUtf8Strict(body);\n whole = JSON.parse(text);\n } catch {\n return this.#refuse('malformed', delivery);\n }\n // The first byte must be the opening `{`: a byte-order mark or whitespace\n // before it is refused, never skipped (contract 1.69 step 2a, D-10).\n if (typeof whole !== 'object' || whole === null || Array.isArray(whole) || !text.startsWith('{')) {\n return this.#refuse('malformed', delivery);\n }\n if (!Object.prototype.hasOwnProperty.call(whole, 'hmac_signature')) {\n return this.#refuse('unsigned', delivery);\n }\n // Byte offsets: latin1 maps each byte to one UTF-16 unit, and the\n // signature member is pure ASCII, so the match index is a byte index.\n const match = TRAILING_SIGNATURE.exec(body.toString('latin1'));\n if (!match) {\n return this.#refuse('malformed', delivery);\n }\n\n // The canonical bytes are the received bytes with the trailing member\n // removed: everything before it, then the closing brace.\n const canonical = Buffer.concat([body.subarray(0, match.index), Buffer.from('}', 'ascii')]);\n let parsed: unknown;\n try {\n parsed = JSON.parse(decodeUtf8Strict(canonical));\n } catch {\n return this.#refuse('malformed', delivery);\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return this.#refuse('malformed', delivery);\n }\n const r = parsed as Record<string, unknown>;\n if (\n !isString(r.correlation_id) ||\n typeof r.allowed !== 'boolean' ||\n !isString(r.tenant_id) ||\n !isString(r.nonce) ||\n Object.prototype.hasOwnProperty.call(r, 'hmac_signature')\n ) {\n return this.#refuse('malformed', delivery);\n }\n\n const expected = createHmac('sha256', this.#subkey.expose()).update(canonical).digest();\n const received = Buffer.from(match[1], 'hex');\n if (received.length !== expected.length || !timingSafeEqual(received, expected)) {\n return this.#refuse('signature', delivery);\n }\n // Optional members are checked once the signature has verified (obligation 4 step 3 names only the four required ones).\n if ((r.reason !== undefined && !isString(r.reason)) || (r.reason_code !== undefined && !isString(r.reason_code))) {\n return this.#refuse('malformed', delivery);\n }\n\n // Rule 3 — the binding.\n if (r.tenant_id.toLowerCase() !== this.#tenantId) {\n return this.#refuse('tenant', delivery);\n }\n const nonce = this.#outstanding.get(r.correlation_id);\n if (nonce === undefined || nonce !== r.nonce) {\n return this.#refuse('unknown_request', delivery);\n }\n\n this.#outstanding.delete(r.correlation_id);\n return {\n accepted: true,\n response: {\n correlation_id: r.correlation_id,\n allowed: r.allowed,\n ...(r.reason !== undefined ? { reason: r.reason as string } : {}),\n ...(r.reason_code !== undefined ? { reason_code: r.reason_code as string } : {}),\n tenant_id: r.tenant_id,\n nonce: r.nonce,\n },\n };\n }\n\n /**\n * {@link verify} a delivery read from a queue, then ack it when accepted\n * and nack it **without requeue** when discarded (§8 rule 4).\n */\n settle(channel: SettleChannel, msg: ConsumeMessage): AuthzResponseVerdict {\n const verdict = this.verify(msg.content, {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n try {\n if (verdict.accepted) {\n channel.ack(msg);\n } else {\n channel.nack(msg, false, false);\n }\n } catch {\n // the channel closed under the delivery: nothing escapes the delivery loop (contract 1.69, D-10)\n }\n return verdict;\n }\n\n #refuse(reason: AuthzResponseRejection, delivery: AuthzResponseDelivery | undefined): AuthzResponseVerdict {\n try {\n this.#logger?.warn(\n 'axiam_sdk.security',\n `AMQP authorization response discarded (${reason})`,\n this.#eventContext(reason, delivery),\n );\n } catch {\n // an integrator logger's failure is not the delivery's problem (contract 1.69, D-10)\n }\n return { accepted: false, reason };\n }\n\n /**\n * The §8 discard event (consumer obligation 4): exactly timestamp, exchange,\n * routing key, the requester's OWN tenant and the reason code. Nothing read\n * from the body, no signature value, no nonce.\n */\n #eventContext(reason: AuthzResponseRejection, delivery: AuthzResponseDelivery | undefined): Record<string, unknown> {\n // Always five members (A.2); `''` when neither the delivery nor the\n // verifier's `replyQueue` says where the body was read from.\n const routingKey = delivery !== undefined ? delivery.routingKey : (this.#replyQueue ?? '');\n return {\n timestamp: new Date().toISOString(),\n exchange: delivery !== undefined ? delivery.exchange : '',\n routingKey,\n tenantId: this.#tenantConfigured,\n reason,\n };\n }\n}\n","// The AMQP authorization requester (CONTRACT.md §8, \"Signed authorization\n// responses\", contract 1.68; N2, D-9).\n//\n// Publishes a signed `AuthzRequest` on `axiam.authz.request` (default\n// exchange) with `reply_to` naming a PRIVATE queue — exclusive, auto-delete,\n// broker-named (`amq.gen-…`) — and accepts an answer only when\n// `AuthzResponseVerifier` verifies it as the server's signed response to THAT\n// request: tenant subkey, own `tenant_id`, and the request's `correlation_id`\n// and `nonce`. A forged or mismatched response is nacked without requeue and\n// the caller keeps waiting for the genuine answer, until the timeout.\n//\n// The same rule as the verifier: verify the received bytes and deliver the\n// same bytes. Mirrors the Go SDK's `amqp/authz_requester.go`.\n\nimport { createHmac, randomUUID } from 'node:crypto';\nimport amqp from 'amqplib';\nimport type { ConsumeMessage } from 'amqplib';\nimport { NetworkError, type Sensitive } from '../core/index.js';\nimport { AuthzResponseVerifier, type AuthzResponseVerifierOptions } from './authzResponse.js';\nimport type { ConsumeLogger } from './consumer.js';\nimport { buildAmqpConnectOptions, type AmqpTlsOptions } from './transport.js';\n\n/** The queue the server consumes `AuthzRequest` from (CONTRACT.md §8). */\nexport const AUTHZ_REQUEST_QUEUE = 'axiam.authz.request';\n\n/** The signing-key version requests are sent under; the response carries none (§8). */\nconst AUTHZ_KEY_VERSION = 2;\n\n/** Default bound on one {@link AuthzRequester.check}, in milliseconds. */\nexport const DEFAULT_AUTHZ_TIMEOUT_MS = 10_000;\n\n/** Prefix of the server's own queues; the server does not honour such a `reply_to` (§8 rule 5). */\nconst SERVER_QUEUE_PREFIX = 'axiam.';\n\n/** A lone (unpaired) UTF-16 surrogate, which serde_json cannot represent. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/** The largest delay `setTimeout` honours; Node runs anything larger (or `NaN`, `≤ 0`) after 1 ms. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\n/**\n * Refuse a `timeoutMs` that `setTimeout` would silently turn into \"time out\n * at once\" (non-finite, not positive, or above 2³¹−1 ms), so the\n * misconfiguration is visible at construction instead of failing every check.\n */\nfunction assertTimeout(timeoutMs: number | undefined): void {\n if (timeoutMs === undefined) return;\n if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) {\n throw new RangeError(`axiam: authz requester timeoutMs must be a finite number in (0, ${MAX_TIMEOUT_MS}]`);\n }\n}\n\n/** Thrown by {@link AuthzRequester.check} once the requester is closed or its reply queue went away. */\nexport class AuthzRequesterClosedError extends Error {\n constructor() {\n super('axiam: authz requester is closed');\n this.name = 'AuthzRequesterClosedError';\n }\n}\n\n/** A verified answer to one `AuthzRequest`. */\nexport interface AuthzDecision {\n /** The decision; `true` only for a response that verified. */\n allowed: boolean;\n /** The server's human-readable reason, when it gave one. */\n reason?: string;\n /** `allowed`, `no_grant`, `denied_by_rule`, `tenant_suspended`, or a code this SDK does not know (verbatim). */\n reasonCode?: string;\n}\n\n/** One authorization question (CONTRACT.md §8 `AuthzRequest`). */\nexport interface AuthzCheckInput {\n /** The subject (user or service account) UUID. */\n subjectId: string;\n /** The action, e.g. `documents:read`. */\n action: string;\n /** The resource UUID. */\n resourceId: string;\n /** Optional sub-resource scope. */\n scope?: string;\n /** Aborts the wait (the request stays published; its answer is then dropped). */\n signal?: AbortSignal;\n}\n\n/**\n * The subset of an amqplib `Channel` the requester uses. A real `Channel`\n * satisfies it; tests supply a fake.\n */\nexport interface AuthzRequesterChannel {\n /** `channel.assertQueue('', { exclusive: true, autoDelete: true, durable: false })` — a broker-named private queue. */\n assertQueue(\n queue: string,\n options: { exclusive: boolean; autoDelete: boolean; durable: boolean },\n ): Promise<{ queue: string }>;\n /** `channel.consume(queue, onMessage, { noAck: false, exclusive: true })`. */\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void,\n options: { noAck: boolean; exclusive: boolean },\n ): Promise<{ consumerTag: string }>;\n /** `channel.sendToQueue(queue, content, options)` — a publish on the default exchange. */\n sendToQueue(\n queue: string,\n content: Buffer,\n options: { correlationId: string; replyTo: string; contentType: string },\n ): boolean;\n /** `channel.ack(msg)`. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)`. */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n /** `channel.cancel(consumerTag)`; optional. */\n cancel?(consumerTag: string): Promise<unknown>;\n}\n\n/** Configuration for {@link createAuthzRequester}. */\nexport interface AuthzRequesterOptions {\n /** The requester's OWN tenant (UUID); the only tenant an answer is accepted for. */\n tenantId: string;\n /** The tenant's HKDF-derived AMQP subkey for `key_version` 2 (§8.1, provisioned out of band) — never the master key. */\n subkey: Sensitive<Buffer>;\n /**\n * Bound on each {@link AuthzRequester.check}, in milliseconds. Defaults to\n * {@link DEFAULT_AUTHZ_TIMEOUT_MS}. A value that is not finite, not\n * positive, or above 2³¹−1 is refused with a `RangeError` when the\n * requester is created.\n */\n timeoutMs?: number;\n /** Security-event logger. Never receives a signature value or the key. */\n logger?: ConsumeLogger;\n /** Clock for `issued_at`; injectable for tests. */\n now?: () => Date;\n}\n\n/** The fields of a request, for {@link buildAuthzRequest}. */\nexport interface AuthzRequestFields {\n /** Request correlation id (UUID). */\n correlationId: string;\n /** The requester's tenant (UUID). */\n tenantId: string;\n /** Subject UUID. */\n subjectId: string;\n /** Action. */\n action: string;\n /** Resource UUID. */\n resourceId: string;\n /** Optional scope. */\n scope?: string;\n /** Fresh per-request nonce (UUID). */\n nonce: string;\n /** Send time. */\n issuedAt: Date;\n}\n\nfunction normalizeUuid(value: string, what: string): string {\n if (!UUID_RE.test(value)) {\n throw new TypeError(`axiam: ${what} is not a UUID`);\n }\n return value.toLowerCase();\n}\n\n/**\n * Serialize and sign an `AuthzRequest` exactly as the server verifies it\n * (CONTRACT.md §8 v2): compact JSON in the fixed field order\n * `correlation_id, tenant_id, subject_id, action, resource_id, scope?,\n * key_version, nonce, issued_at`, then `,\"hmac_signature\":\"<hex>\"` appended as\n * the trailing member. `JSON.stringify` escapes strings as serde_json does\n * (`\"`, `\\`, the short escapes, other controls as lower-case `\\u00XX`; all\n * else raw), so the bytes match — except for a lone surrogate, which serde\n * cannot represent and is refused.\n *\n * @throws TypeError on a non-UUID id or an action/scope that is not well-formed UTF-16.\n */\nexport function buildAuthzRequest(subkey: Buffer, fields: AuthzRequestFields): Buffer {\n for (const s of [fields.action, ...(fields.scope !== undefined ? [fields.scope] : [])]) {\n if (typeof s !== 'string' || LONE_SURROGATE.test(s)) {\n throw new TypeError('axiam: action and scope must be well-formed strings');\n }\n }\n const body: Record<string, unknown> = {\n correlation_id: normalizeUuid(fields.correlationId, 'correlation_id'),\n tenant_id: normalizeUuid(fields.tenantId, 'tenant_id'),\n subject_id: normalizeUuid(fields.subjectId, 'subject_id'),\n action: fields.action,\n resource_id: normalizeUuid(fields.resourceId, 'resource_id'),\n };\n if (fields.scope !== undefined) body.scope = fields.scope;\n body.key_version = AUTHZ_KEY_VERSION;\n body.nonce = normalizeUuid(fields.nonce, 'nonce');\n // RFC 3339, second precision, UTC — the server's own format.\n body.issued_at = fields.issuedAt.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n const canonical = JSON.stringify(body);\n const signature = createHmac('sha256', subkey).update(Buffer.from(canonical, 'utf8')).digest('hex');\n return Buffer.from(`${canonical.slice(0, -1)},\"hmac_signature\":\"${signature}\"}`, 'utf8');\n}\n\ninterface Pending {\n resolve(decision: AuthzDecision): void;\n reject(err: Error): void;\n}\n\n/**\n * Publishes `AuthzRequest` messages and verifies their answers. Many checks\n * may be outstanding at once. Build it with {@link createAuthzRequester} or\n * {@link connectAuthzRequester}.\n *\n * The AMQP authorization requester requires an AXIAM server of 1.68 or later\n * (contract 1.68). Such a server signs every authorization response with the\n * tenant's AMQP subkey and answers on the requester's private `reply_to`\n * queue. A server older than 1.68 ignores `reply_to` and answers, unsigned,\n * only on the shared `axiam.authz.response` queue, which this requester never\n * reads: against it every check times out. There is no option to accept\n * unsigned responses (CONTRACT.md §8, contract 1.69): no AXIAM server sends\n * one to a reply queue, so an unsigned response can only have been published\n * by someone else, and it is discarded and logged. During a rolling upgrade\n * from a pre-1.68 server, use REST or gRPC authorization until every replica\n * runs 1.68 or later.\n */\nexport class AuthzRequester {\n readonly #channel: AuthzRequesterChannel;\n readonly #options: AuthzRequesterOptions;\n readonly #tenantId: string;\n readonly #replyTo: string;\n readonly #verifier: AuthzResponseVerifier;\n readonly #pending = new Map<string, Pending>();\n #consumerTag: string | undefined;\n #closed = false;\n #onClose: (() => Promise<void>) | undefined;\n\n /** @internal Use {@link createAuthzRequester}. */\n constructor(channel: AuthzRequesterChannel, options: AuthzRequesterOptions, tenantId: string, replyTo: string) {\n this.#channel = channel;\n this.#options = options;\n this.#tenantId = tenantId;\n this.#replyTo = replyTo;\n this.#verifier = new AuthzResponseVerifier({\n subkey: options.subkey,\n tenantId,\n replyQueue: replyTo,\n ...(options.logger !== undefined ? { logger: options.logger } : {}),\n });\n }\n\n /** The private reply queue every request names in `reply_to`. */\n get replyTo(): string {\n return this.#replyTo;\n }\n\n /** Number of checks still awaiting an answer. */\n get pending(): number {\n return this.#pending.size;\n }\n\n /** @internal Start consuming the reply queue. */\n async start(onClose?: () => Promise<void>): Promise<void> {\n this.#onClose = onClose;\n const { consumerTag } = await this.#channel.consume(this.#replyTo, (msg) => this.#handle(msg), {\n noAck: false,\n exclusive: true,\n });\n this.#consumerTag = consumerTag;\n }\n\n /**\n * Ask whether `subjectId` may perform `action` on `resourceId` and wait for\n * the verified answer. A response that fails verification or binding is\n * discarded and the check keeps waiting for the genuine one: a failed\n * verification is never an allow and never completes the request.\n *\n * @throws AuthzRequesterClosedError once {@link close} was called or the reply queue went away.\n * @throws NetworkError on a publish failure or when no verified answer arrives in time.\n */\n async check(input: AuthzCheckInput): Promise<AuthzDecision> {\n if (this.#closed) {\n throw new AuthzRequesterClosedError();\n }\n const correlationId = randomUUID(); // CSPRNG: unpredictable\n const nonce = randomUUID();\n const body = buildAuthzRequest(this.#options.subkey.expose(), {\n correlationId,\n tenantId: this.#tenantId,\n subjectId: input.subjectId,\n action: input.action,\n resourceId: input.resourceId,\n ...(input.scope !== undefined ? { scope: input.scope } : {}),\n nonce,\n issuedAt: (this.#options.now ?? (() => new Date()))(),\n });\n\n return new Promise<AuthzDecision>((resolve, reject) => {\n const timeoutMs = this.#options.timeoutMs ?? DEFAULT_AUTHZ_TIMEOUT_MS;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => finish(() => reject(new NetworkError('axiam: authz check aborted')));\n const finish = (settle: () => void) => {\n if (timer !== undefined) clearTimeout(timer);\n input.signal?.removeEventListener('abort', onAbort);\n this.#pending.delete(correlationId);\n this.#verifier.forget(correlationId);\n settle();\n };\n\n this.#pending.set(correlationId, {\n resolve: (d) => finish(() => resolve(d)),\n reject: (e) => finish(() => reject(e)),\n });\n this.#verifier.expect({ correlation_id: correlationId, nonce, tenant_id: this.#tenantId });\n\n timer = setTimeout(\n () => finish(() => reject(new NetworkError('axiam: no verified authz answer before the timeout'))),\n timeoutMs,\n );\n if (input.signal) {\n if (input.signal.aborted) {\n onAbort();\n return;\n }\n input.signal.addEventListener('abort', onAbort, { once: true });\n }\n\n try {\n this.#channel.sendToQueue(AUTHZ_REQUEST_QUEUE, body, {\n correlationId,\n replyTo: this.#replyTo,\n contentType: 'application/json',\n });\n } catch (err) {\n finish(() => reject(new NetworkError('axiam: failed to publish authz request', err)));\n }\n });\n }\n\n /**\n * Stop accepting answers: every outstanding and later check rejects with\n * {@link AuthzRequesterClosedError}. The reply queue is exclusive and\n * auto-delete, so the broker removes it with its consumer. Idempotent.\n */\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n for (const p of [...this.#pending.values()]) {\n p.reject(new AuthzRequesterClosedError());\n }\n if (this.#consumerTag !== undefined && this.#channel.cancel) {\n try {\n await this.#channel.cancel(this.#consumerTag);\n } catch {\n // The channel may already be gone; nothing left to release.\n }\n }\n await this.#onClose?.();\n }\n\n #handle(msg: ConsumeMessage | null): void {\n if (msg === null) {\n // The broker cancelled the consumer: the reply queue is gone.\n void this.close();\n return;\n }\n // No body escapes the delivery loop (CONTRACT.md §8, contract 1.69, D-10): whatever\n // the bytes, nothing thrown here may reach the channel's dispatcher.\n try {\n // Acks an accepted answer, nacks (no requeue) and logs anything else; on\n // acceptance the verifier has already retired the request.\n if (this.#closed) {\n // After Close an answer is not decoded or dispatched: nacked without\n // requeue, no discard event (CONTRACT.md §8 consumer obligation 4).\n this.#channel.nack(msg, false, false);\n return;\n }\n const verdict = this.#verifier.settle(this.#channel, msg);\n if (!verdict.accepted) {\n return;\n }\n const pending = this.#pending.get(verdict.response.correlation_id);\n pending?.resolve({\n allowed: verdict.response.allowed,\n ...(verdict.response.reason !== undefined ? { reason: verdict.response.reason } : {}),\n ...(verdict.response.reason_code !== undefined ? { reasonCode: verdict.response.reason_code } : {}),\n });\n } catch {\n // a closed channel or a failing resolver is not the delivery's problem\n }\n }\n}\n\n/**\n * Open a private reply queue on `channel` and return a requester for\n * `options.tenantId` (CONTRACT.md §8, contract 1.68).\n *\n * The reply queue is declared with an EMPTY name (the broker names it\n * `amq.gen-…`), `exclusive`, `autoDelete` and non-durable, and consumed\n * exclusively with manual acknowledgement. A returned name that is empty or\n * starts with `axiam.` is refused: the server would answer such a request on\n * the shared `axiam.authz.response` queue (§8 rule 5).\n *\n * The caller owns `channel` and its connection, and therefore their error\n * handling: attach `'error'` listeners to both (an amqplib connection or\n * channel that emits `'error'` with no listener throws an uncaught exception\n * and ends the process), and call {@link AuthzRequester.close} when either\n * closes, so outstanding checks are released at once instead of waiting for\n * their timeout. {@link connectAuthzRequester} does both itself.\n *\n * @throws TypeError on a non-UUID tenant or an empty subkey; RangeError on an\n * invalid `timeoutMs`; Error on a non-private reply queue.\n */\nexport async function createAuthzRequester(\n channel: AuthzRequesterChannel,\n options: AuthzRequesterOptions,\n): Promise<AuthzRequester> {\n return createOn(channel, options);\n}\n\nasync function createOn(\n channel: AuthzRequesterChannel,\n options: AuthzRequesterOptions,\n onClose?: () => Promise<void>,\n): Promise<AuthzRequester> {\n const tenantId = normalizeUuid(options.tenantId, 'authz requester tenant_id');\n if (options.subkey.expose().length === 0) {\n throw new TypeError('axiam: authz requester needs the tenant subkey');\n }\n assertTimeout(options.timeoutMs);\n const { queue } = await channel.assertQueue('', { exclusive: true, autoDelete: true, durable: false });\n if (typeof queue !== 'string' || queue.length === 0 || queue.startsWith(SERVER_QUEUE_PREFIX)) {\n throw new Error(`axiam: authz reply queue ${JSON.stringify(queue)} is not a private queue`);\n }\n const requester = new AuthzRequester(channel, options, tenantId, queue);\n await requester.start(onClose);\n return requester;\n}\n\n/**\n * Connect to the broker at `amqpUrl` (MUST be `amqps://`, CONTRACT.md §8b) and\n * return a requester on its own channel; {@link AuthzRequester.close} also\n * closes that connection.\n *\n * The connection and channel are private to the requester, so it handles\n * their events itself: an `'error'` on either (a socket error, a missed\n * heartbeat, a channel-level exception) is logged through `options.logger`\n * — the error's message only, never the URL's credentials or a key (a\n * socket error's message can name the broker host and port) — instead of\n * escaping as an uncaught exception, and a `'close'` of either closes the requester:\n * every outstanding check rejects at once with\n * {@link AuthzRequesterClosedError}, and so does every later one. Reconnect\n * by building a new requester.\n */\nexport async function connectAuthzRequester(\n amqpUrl: string,\n options: AuthzRequesterOptions & { tls?: AmqpTlsOptions },\n): Promise<AuthzRequester> {\n const socketOptions = buildAmqpConnectOptions(amqpUrl, options.tls, 'connectAuthzRequester() amqpUrl');\n const connection = await amqp.connect(amqpUrl, socketOptions);\n // Listen from the start: an 'error' with no listener throws out of\n // amqplib's socket handler and takes the whole process down.\n let requester: AuthzRequester | undefined;\n let gone = false;\n const onError = (source: 'connection' | 'channel') => (err: unknown) => {\n options.logger?.warn('axiam_sdk.amqp', `AMQP authz requester ${source} error`, {\n timestamp: new Date().toISOString(),\n reason: err instanceof Error ? err.message : 'unknown',\n });\n };\n const onGone = () => {\n gone = true;\n void requester?.close();\n };\n connection.on('error', onError('connection'));\n connection.on('close', onGone);\n try {\n const channel = await connection.createChannel();\n channel.on('error', onError('channel'));\n channel.on('close', onGone);\n requester = await createOn(channel as unknown as AuthzRequesterChannel, options, async () => {\n try {\n await connection.close();\n } catch {\n // already closed\n }\n });\n if (gone) {\n // Closed while the reply queue was being set up.\n await requester.close();\n }\n return requester;\n } catch (err) {\n await connection.close().catch(() => undefined);\n throw err;\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"]}
|