axiam-sdk 1.0.0-alpha2 → 1.0.0-alpha21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +219 -8
- package/dist/amqp/index.d.cts +1 -1
- package/dist/amqp/index.d.ts +1 -1
- package/dist/amqp/index.js +4 -0
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +4 -0
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-xwmCivHH.d.ts → authzCore-DtSN59if.d.ts} +19 -2
- package/dist/{authzCore-CV-Td-V1.d.cts → authzCore-DuRI1aJf.d.cts} +19 -2
- package/dist/client-B_FqmZ0i.d.cts +72 -0
- package/dist/client-Dn1fs5MH.d.ts +72 -0
- package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
- package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
- package/dist/grpc/index.d.cts +113 -6
- package/dist/grpc/index.d.ts +113 -6
- package/dist/grpc/index.js +435 -18
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +434 -19
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +209 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +204 -14
- package/dist/index.mjs.map +1 -1
- package/dist/jwks-BgojMGC5.d.cts +152 -0
- package/dist/jwks-BgojMGC5.d.ts +152 -0
- package/dist/middleware/index.d.cts +208 -8
- package/dist/middleware/index.d.ts +208 -8
- package/dist/middleware/index.js +1107 -1
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +1100 -3
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +2 -2
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +3 -0
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +3 -0
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +50 -94
- package/dist/node/index.d.ts +50 -94
- package/dist/node/index.js +1039 -15
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +1023 -16
- package/dist/node/index.mjs.map +1 -1
- package/dist/oidcState-BGxqWUun.d.cts +598 -0
- package/dist/oidcState-CkFuCjpM.d.ts +598 -0
- package/dist/rest/index.d.cts +107 -5
- package/dist/rest/index.d.ts +107 -5
- package/dist/rest/index.js +209 -13
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +204 -14
- package/dist/rest/index.mjs.map +1 -1
- package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
- package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
- package/dist/session-BWUWhhyB.d.cts +154 -0
- package/dist/session-BWUWhhyB.d.ts +154 -0
- package/package.json +2 -2
- package/dist/client-BPg9kfKV.d.ts +0 -150
- package/dist/client-CAeQw1a-.d.cts +0 -150
- package/dist/jwks-CX-nhD6A.d.cts +0 -29
- package/dist/jwks-CX-nhD6A.d.ts +0 -29
- package/dist/sensitive-CWBH_tHr.d.cts +0 -12
- package/dist/sensitive-CWBH_tHr.d.ts +0 -12
package/dist/amqp/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/sensitive.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/consumer.ts"],"names":[],"mappings":";;;;AAYO,IAAM,QAAA,GAAW,aAAA;AAExB,IAAM,mBAAA,mBAAsB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAE5D,IAAM,YAAN,MAAmB;AAAA,EACf,MAAA;AAAA,EAET,YAAY,KAAA,EAAU;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA,EAEA,QAAA,GAAmB;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,E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MAChF,QAAA,EAAU,IAAI,MAAA,CAAO,QAAA;AAAA,MACrB,UAAA,EAAY,IAAI,MAAA,CAAO,UAAA;AAAA,MACvB,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACvD,CAAA;AAED,IAAA,OAAA,CAAQ,IAAA,CAAK,GAAA,EAAK,KAAA,EAAO,KAAK,CAAA;AAC9B,IAAA;AAAA,EACF;AAEA,EAAA,OAAA,CAAQ,IAAI,GAAG,CAAA;AACjB;AAgBA,eAAsB,QACpB,OAAA,EACA,KAAA,EACA,YACA,OAAA,EACA,OAAA,GAA0B,EAAC,EACZ;AACf,EAAA,MAAM,UAAA,GAAa,MAAM,IAAA,CAAK,OAAA,CAAQ,OAAO,CAAA;AAC7C,EAAA,MAAM,OAAA,GAAmB,MAAM,UAAA,CAAW,aAAA,EAAc;AACxD,EAAA,MAAM,QAAQ,WAAA,CAAY,KAAA,EAAO,EAAE,OAAA,EAAS,MAAM,CAAA;AAKlD,EAAA,MAAM,aAAA,GAAgC;AAAA,IACpC,GAAG,OAAA;AAAA,IACH,UAAA,EAAY,OAAA,CAAQ,UAAA,IAAc,IAAI,kBAAA;AAAmB,GAC3D;AAEA,EAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,CAAC,GAAA,KAAQ;AACpC,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,KAAK,kBAAkB,OAAA,EAAS,GAAA,EAAK,WAAW,MAAA,EAAO,EAAG,SAAS,aAAa,CAAA;AAAA,EAClF,CAAC,CAAA;AACH","file":"index.mjs","sourcesContent":["// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\nexport class Sensitive<T> {\n readonly #value: T;\n\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n toString(): string {\n return REDACTED;\n }\n\n toJSON(): string {\n return REDACTED;\n }\n\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// AMQP HMAC-SHA256 sign/verify (CONTRACT.md §8, D-12).\n//\n// Mirror, never import. This module reproduces the server's algorithm in\n// crates/axiam-amqp/src/messages.rs:35-50 (and the Rust SDK's src/amqp/hmac.rs)\n// byte-for-byte using only Node's built-in `node:crypto` module, so the\n// SDK's HMAC output is wire-compatible with the AXIAM server for the same\n// key + canonical JSON payload bytes.\n//\n// Protocol (CONTRACT.md §8.2):\n// a. Extract hmac_signature from the message.\n// b. Set hmac_signature to null/absent in the body.\n// c. Serialize the remaining body to canonical JSON (declaration/insertion\n// order, no re-sorting — see messages.ts and Pitfall 5).\n// d. HMAC-SHA256(key, canonical_json_bytes), hex-encoded.\n// e. Constant-time compare against the received signature.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/**\n * Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.\n *\n * `payloadJson` MUST be the canonical JSON bytes of the message body with\n * `hmac_signature` already removed — otherwise the signature is computed\n * over a payload that includes a placeholder signature, making verification\n * impossible (matches the server's `sign_payload` doc comment).\n */\nexport function signPayload(key: Buffer, payloadJson: Buffer): string {\n return createHmac('sha256', key).update(payloadJson).digest('hex');\n}\n\n/**\n * Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.\n *\n * Returns `true` only if the signature matches, comparing in constant time\n * via `timingSafeEqual`. Never throws: malformed hex or a length mismatch\n * both return `false`.\n */\nexport function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean {\n const expected = createHmac('sha256', key).update(payloadJson).digest();\n let received: Buffer;\n try {\n received = Buffer.from(signatureHex, 'hex');\n } catch {\n return false;\n }\n // timingSafeEqual requires equal-length buffers; a length mismatch is\n // itself not secret information, so a fast-path length check first is\n // safe and matches Rust's hmac crate `verify_slice` behavior.\n if (received.length !== expected.length) return false;\n return timingSafeEqual(received, expected);\n}\n","// AMQP message DTOs mirroring the server's wire format (CONTRACT.md §8).\n//\n// Mirror, never import. These interfaces reproduce field declaration order\n// byte-for-byte from crates/axiam-amqp/src/messages.rs (and\n// the Rust SDK's src/amqp/messages.rs) so that `JSON.stringify` on a parsed\n// object (after deleting `hmac_signature`) produces canonical JSON\n// byte-identical to what the server signs/verifies against — see\n// Pitfall 5: no schema-validator reconstruction step before HMAC\n// verification, or the field order (and therefore the signed bytes) could\n// silently diverge.\n\n/**\n * Authorization check request received from `axiam.authz.request`.\n *\n * Field declaration order matches the server's `AuthzRequest`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * correlation_id, tenant_id, subject_id, action, resource_id, scope,\n * key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and\n * `issued_at` are always emitted (never omitted) so they fall inside the\n * HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay Protection\".\n */\nexport interface AuthzRequest {\n /** Caller-provided ID to correlate request with response. */\n correlation_id: string;\n tenant_id: string;\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /**\n * HMAC-SHA256 of the JSON-serialized message body (this field removed\n * before signing). Computed with the per-tenant AMQP signing key\n * (CONTRACT.md §8). The consumer MUST verify this before processing; a\n * missing signature is rejected in strict mode (the default).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to `axiam.authz.response`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n}\n\n/**\n * Audit event received from external services via `axiam.audit.events`.\n *\n * Field declaration order matches the server's `AuditEventMessage`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,\n * metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,\n * `nonce`, and `issued_at` are always emitted (never omitted) so they fall\n * inside the HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay\n * Protection\".\n */\nexport interface AuditEventMessage {\n tenant_id: string;\n actor_id: string;\n actor_type: string;\n action: string;\n resource_id?: string;\n outcome: string;\n ip_address?: string;\n metadata?: Record<string, unknown>;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */\n hmac_signature?: string;\n}\n\n/**\n * Notification event published to `axiam.notifications`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface NotificationEvent {\n event_type: string;\n tenant_id: string;\n actor_id: string;\n resource_id?: string;\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Message type names subject to HMAC verification per CONTRACT.md §8's\n * message-types table (`axiam.authz.request` -> AuthzRequest,\n * `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and\n * `NotificationEvent` are server-published and never carry\n * `hmac_signature`.\n */\nexport const HMAC_SIGNED_MESSAGE_TYPES = ['AuthzRequest', 'AuditEventMessage'] as const;\n\nexport type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];\n","// Closure-handler AMQP consumer (D-12, CONTRACT.md §8.3g/§8.4).\n//\n// The SDK owns the full ack/nack loop. Every delivery is HMAC-verified\n// (CONTRACT.md §8) BEFORE the caller-supplied handler is ever invoked. On\n// any verification failure (signature mismatch, missing signature in the\n// default strict mode, or a body that fails to parse as JSON) the delivery\n// is nacked WITHOUT requeue and a security event is emitted — the event\n// never contains the received/expected HMAC value or the signing key. Only\n// a verified delivery reaches the handler, and only then is it acked.\n//\n// NEW-4 (CONTRACT.md §8 \"v2 — Replay Protection\", hard cutover): once the\n// HMAC verifies, the delivery is ADDITIONALLY rejected (same nack-without-\n// requeue path) when `key_version < 2`, `issued_at` falls outside the\n// ±skew freshness window, or `nonce` has already been seen. Because this\n// module verifies by re-serializing the parsed body (minus\n// `hmac_signature`) in insertion order (Pitfall 5), `nonce`/`issued_at` are\n// already covered by the HMAC bytes with no canonicalization change — only\n// the three validation gates below are new.\n//\n// This is the TS port of the already-tested Rust `verify_and_dispatch`/\n// `consume` (the Rust SDK's src/amqp/consumer.rs).\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport { verifyPayload } from './hmac.js';\n\n/**\n * Default freshness skew for `issued_at` acceptance (NEW-4): a message is\n * accepted only when its `issued_at` lies within ±5 minutes of the\n * verifier's clock, matching the server's\n * `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`\n * (CONTRACT.md §8 v2).\n */\nexport const DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when\n * `nonce` has already been recorded and its dedup entry has not yet\n * expired (i.e. this delivery is a replay); otherwise it records the nonce\n * with the given TTL and returns `false`.\n */\nexport interface NonceStore {\n checkAndRecord(nonce: string, ttlMs: number): boolean;\n}\n\n/**\n * Default in-memory nonce dedup store (NEW-4). Naturally bounded: each\n * entry expires after `ttlMs` (the caller passes 2x the freshness skew, so\n * a nonce can never still be \"fresh\" once its dedup entry has lapsed) and\n * expired entries are pruned opportunistically on each check — no\n * background timer and no unbounded growth under sustained traffic.\n *\n * Share ONE instance across every delivery from the same consumer (as\n * `consume()` does by default) — a fresh store per call provides no\n * cross-message replay protection.\n */\nexport class InMemoryNonceStore implements NonceStore {\n private readonly seenUntilMs = new Map<string, number>();\n\n checkAndRecord(nonce: string, ttlMs: number): boolean {\n const now = Date.now();\n this.prune(now);\n const expiry = this.seenUntilMs.get(nonce);\n if (expiry !== undefined && expiry > now) {\n return true;\n }\n this.seenUntilMs.set(nonce, now + ttlMs);\n return false;\n }\n\n private prune(now: number): void {\n for (const [nonce, expiry] of this.seenUntilMs) {\n if (expiry <= now) this.seenUntilMs.delete(nonce);\n }\n }\n}\n\ntype ReplayRejectReason = 'key_version' | 'issued_at' | 'nonce';\n\n/**\n * NEW-4 validation gates, checked only AFTER the HMAC has already verified.\n * Returns the failing gate's name, or `undefined` when all three pass.\n * `ttlMs` for the nonce store is 2x `skewMs` — the freshness window plus a\n * margin so a nonce cannot be replayed the instant its dedup entry expires\n * while `issued_at` might still (barely) be judged fresh by a differently-\n * skewed verifier.\n */\nfunction checkReplayProtection(\n body: Record<string, unknown>,\n skewMs: number,\n nonceStore: NonceStore,\n): ReplayRejectReason | undefined {\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || keyVersion < 2) {\n return 'key_version';\n }\n\n const issuedAtRaw = body.issued_at;\n if (typeof issuedAtRaw !== 'string') {\n return 'issued_at';\n }\n const issuedAtMs = Date.parse(issuedAtRaw);\n if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {\n return 'issued_at';\n }\n\n const nonce = body.nonce;\n if (typeof nonce !== 'string' || nonce.length === 0) {\n return 'nonce';\n }\n if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {\n return 'nonce';\n }\n\n return undefined;\n}\n\n/**\n * Minimal seam over the channel operations this module needs\n * (ack/nack/consume). `amqplib`'s `Channel` implements this directly;\n * tests provide a recording fake that never touches a live broker, so the\n * security-sensitive nack-without-requeue behavior can be asserted without\n * a running RabbitMQ instance.\n */\nexport interface ConsumeChannel {\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void | Promise<void>,\n ): Promise<unknown>;\n /** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\nexport interface ConsumeLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface ConsumeOptions {\n logger?: ConsumeLogger;\n /**\n * Strict mode (default true, CONTRACT.md §8.3): a message with no\n * `hmac_signature` is treated as a verification failure (nack-no-requeue),\n * not a pass-through. Lenient mode (false) is a temporary rolling-\n * deployment measure only — strict MUST remain the default.\n */\n strict?: boolean;\n /**\n * Freshness skew window for `issued_at` validation (NEW-4), in\n * milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),\n * matching the server default (CONTRACT.md §8 v2).\n */\n skewMs?: number;\n /**\n * Nonce replay-dedup store (NEW-4). Defaults to a fresh\n * `InMemoryNonceStore` per call when omitted — `consume()` creates and\n * shares ONE store across every delivery on that connection by default;\n * callers invoking `verifyAndDispatch` directly across multiple messages\n * must pass the same store explicitly for dedup to take effect.\n */\n nonceStore?: NonceStore;\n}\n\n/**\n * Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,\n * only on success, invoke `handler` with the parsed body (hmac_signature\n * removed) before acking. On any failure the delivery is nacked without\n * requeue and a security event is emitted that never contains the HMAC\n * value or the signing key.\n *\n * Exported (not just used internally) so it is the same separately-testable\n * unit backing `consume`'s per-message loop, mirroring the Rust SDK's\n * `verify_and_dispatch`.\n */\nexport async function verifyAndDispatch(\n channel: ConsumeChannel,\n msg: ConsumeMessage,\n signingKey: Buffer,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const { logger, strict = true } = options;\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n logger?.warn('axiam_sdk.security', 'AMQP message body failed JSON parse; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n const sig = typeof body.hmac_signature === 'string' ? body.hmac_signature : undefined;\n delete body.hmac_signature;\n const canonical = Buffer.from(JSON.stringify(body), 'utf8');\n\n // Strict mode (default, CONTRACT.md §8.3): a missing signature is treated\n // as a verification failure, not a pass-through. A present signature is\n // always verified regardless of strict/lenient mode; lenient mode only\n // changes the outcome for a MISSING signature (temporary rolling-\n // deployment measure — strict MUST remain the default).\n let verified: boolean;\n if (sig !== undefined) {\n verified = verifyPayload(signingKey, canonical, sig);\n } else {\n verified = !strict;\n }\n\n if (!verified) {\n // Security event (§8.4): timestamp, exchange, routing key, and tenant\n // context (if present in the body) — NEVER the signature value or the\n // signing key.\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn('axiam_sdk.security', 'AMQP HMAC verification failed; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n // NEW-4 (CONTRACT.md §8 v2, hard cutover): only reached once the HMAC has\n // verified. `body` was re-serialized in insertion order to compute\n // `canonical` above, so `nonce`/`issued_at` are already inside the bytes\n // that were just verified — these are the three ADDITIONAL validation\n // gates (key_version, freshness, replay), not re-verification.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);\n if (replayRejectReason) {\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn(\n 'axiam_sdk.security',\n `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,\n {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n },\n );\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n try {\n await handler(body);\n } catch (err) {\n // Do not requeue a handler-crashing message into a hot loop.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n error: err instanceof Error ? err.message : String(err),\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n channel.ack(msg);\n}\n\n/**\n * Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and\n * consume from it — verifying each delivery's HMAC-SHA256 signature\n * (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an\n * unverified message; verification failures are nacked without requeue and\n * logged as a security event.\n *\n * `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK\n * does not fetch it from the server (no such endpoint exists; CONTRACT.md\n * §8.1 assumes out-of-band provisioning).\n *\n * This function owns the full ack/nack loop; `handler` MUST NOT itself call\n * ack/nack (there is no delivery handle exposed to it).\n */\nexport async function consume(\n amqpUrl: string,\n queue: string,\n signingKey: Sensitive<Buffer>,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const connection = await amqp.connect(amqpUrl);\n const channel: Channel = await connection.createChannel();\n await channel.assertQueue(queue, { durable: true });\n\n // NEW-4: one nonce store shared across every delivery on this consumer —\n // a fresh store per message (the per-call default in `verifyAndDispatch`)\n // would defeat replay dedup entirely.\n const sharedOptions: ConsumeOptions = {\n ...options,\n nonceStore: options.nonceStore ?? new InMemoryNonceStore(),\n };\n\n await channel.consume(queue, (msg) => {\n if (!msg) return;\n void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/sensitive.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/consumer.ts"],"names":[],"mappings":";;;;AAYO,IAAM,QAAA,GAAW,aAAA;AAExB,IAAM,mBAAA,mBAAsB,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAA;AAyB5D,IAAM,YAAN,MAAmB;AAAA,EACf,MAAA;AAAA;AAAA,EAGT,YAAY,KAAA,EAAU;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA;AAAA,EAGA,QAAA,GAAmB;AACjB,IAA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AQ,IAAA,CAAK,sBAAsB,6CAAA,EAA+C;AAAA,MAChF,QAAA,EAAU,IAAI,MAAA,CAAO,QAAA;AAAA,MACrB,UAAA,EAAY,IAAI,MAAA,CAAO,UAAA;AAAA,MACvB,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACvD,CAAA;AAED,IAAA,OAAA,CAAQ,IAAA,CAAK,GAAA,EAAK,KAAA,EAAO,KAAK,CAAA;AAC9B,IAAA;AAAA,EACF;AAEA,EAAA,OAAA,CAAQ,IAAI,GAAG,CAAA;AACjB;AAgBA,eAAsB,QACpB,OAAA,EACA,KAAA,EACA,YACA,OAAA,EACA,OAAA,GAA0B,EAAC,EACZ;AACf,EAAA,MAAM,UAAA,GAAa,MAAM,IAAA,CAAK,OAAA,CAAQ,OAAO,CAAA;AAC7C,EAAA,MAAM,OAAA,GAAmB,MAAM,UAAA,CAAW,aAAA,EAAc;AACxD,EAAA,MAAM,QAAQ,WAAA,CAAY,KAAA,EAAO,EAAE,OAAA,EAAS,MAAM,CAAA;AAKlD,EAAA,MAAM,aAAA,GAAgC;AAAA,IACpC,GAAG,OAAA;AAAA,IACH,UAAA,EAAY,OAAA,CAAQ,UAAA,IAAc,IAAI,kBAAA;AAAmB,GAC3D;AAEA,EAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,CAAC,GAAA,KAAQ;AACpC,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,KAAK,kBAAkB,OAAA,EAAS,GAAA,EAAK,WAAW,MAAA,EAAO,EAAG,SAAS,aAAa,CAAA;AAAA,EAClF,CAAC,CAAA;AACH","file":"index.mjs","sourcesContent":["// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// AMQP HMAC-SHA256 sign/verify (CONTRACT.md §8, D-12).\n//\n// Mirror, never import. This module reproduces the server's algorithm in\n// crates/axiam-amqp/src/messages.rs:35-50 (and the Rust SDK's src/amqp/hmac.rs)\n// byte-for-byte using only Node's built-in `node:crypto` module, so the\n// SDK's HMAC output is wire-compatible with the AXIAM server for the same\n// key + canonical JSON payload bytes.\n//\n// Protocol (CONTRACT.md §8.2):\n// a. Extract hmac_signature from the message.\n// b. Set hmac_signature to null/absent in the body.\n// c. Serialize the remaining body to canonical JSON (declaration/insertion\n// order, no re-sorting — see messages.ts and Pitfall 5).\n// d. HMAC-SHA256(key, canonical_json_bytes), hex-encoded.\n// e. Constant-time compare against the received signature.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/**\n * Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.\n *\n * `payloadJson` MUST be the canonical JSON bytes of the message body with\n * `hmac_signature` already removed — otherwise the signature is computed\n * over a payload that includes a placeholder signature, making verification\n * impossible (matches the server's `sign_payload` doc comment).\n */\nexport function signPayload(key: Buffer, payloadJson: Buffer): string {\n return createHmac('sha256', key).update(payloadJson).digest('hex');\n}\n\n/**\n * Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.\n *\n * Returns `true` only if the signature matches, comparing in constant time\n * via `timingSafeEqual`. Never throws: malformed hex or a length mismatch\n * both return `false`.\n */\nexport function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean {\n const expected = createHmac('sha256', key).update(payloadJson).digest();\n let received: Buffer;\n try {\n received = Buffer.from(signatureHex, 'hex');\n } catch {\n return false;\n }\n // timingSafeEqual requires equal-length buffers; a length mismatch is\n // itself not secret information, so a fast-path length check first is\n // safe and matches Rust's hmac crate `verify_slice` behavior.\n if (received.length !== expected.length) return false;\n return timingSafeEqual(received, expected);\n}\n","// AMQP message DTOs mirroring the server's wire format (CONTRACT.md §8).\n//\n// Mirror, never import. These interfaces reproduce field declaration order\n// byte-for-byte from crates/axiam-amqp/src/messages.rs (and\n// the Rust SDK's src/amqp/messages.rs) so that `JSON.stringify` on a parsed\n// object (after deleting `hmac_signature`) produces canonical JSON\n// byte-identical to what the server signs/verifies against — see\n// Pitfall 5: no schema-validator reconstruction step before HMAC\n// verification, or the field order (and therefore the signed bytes) could\n// silently diverge.\n\n/**\n * Authorization check request received from `axiam.authz.request`.\n *\n * Field declaration order matches the server's `AuthzRequest`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * correlation_id, tenant_id, subject_id, action, resource_id, scope,\n * key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and\n * `issued_at` are always emitted (never omitted) so they fall inside the\n * HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay Protection\".\n */\nexport interface AuthzRequest {\n /** Caller-provided ID to correlate request with response. */\n correlation_id: string;\n tenant_id: string;\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /**\n * HMAC-SHA256 of the JSON-serialized message body (this field removed\n * before signing). Computed with the per-tenant AMQP signing key\n * (CONTRACT.md §8). The consumer MUST verify this before processing; a\n * missing signature is rejected in strict mode (the default).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to `axiam.authz.response`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n}\n\n/**\n * Audit event received from external services via `axiam.audit.events`.\n *\n * Field declaration order matches the server's `AuditEventMessage`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,\n * metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,\n * `nonce`, and `issued_at` are always emitted (never omitted) so they fall\n * inside the HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay\n * Protection\".\n */\nexport interface AuditEventMessage {\n tenant_id: string;\n actor_id: string;\n actor_type: string;\n action: string;\n resource_id?: string;\n outcome: string;\n ip_address?: string;\n metadata?: Record<string, unknown>;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */\n hmac_signature?: string;\n}\n\n/**\n * Notification event published to `axiam.notifications`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface NotificationEvent {\n event_type: string;\n tenant_id: string;\n actor_id: string;\n resource_id?: string;\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Message type names subject to HMAC verification per CONTRACT.md §8's\n * message-types table (`axiam.authz.request` -> AuthzRequest,\n * `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and\n * `NotificationEvent` are server-published and never carry\n * `hmac_signature`.\n */\nexport const HMAC_SIGNED_MESSAGE_TYPES = ['AuthzRequest', 'AuditEventMessage'] as const;\n\nexport type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];\n","// Closure-handler AMQP consumer (D-12, CONTRACT.md §8.3g/§8.4).\n//\n// The SDK owns the full ack/nack loop. Every delivery is HMAC-verified\n// (CONTRACT.md §8) BEFORE the caller-supplied handler is ever invoked. On\n// any verification failure (signature mismatch, missing signature in the\n// default strict mode, or a body that fails to parse as JSON) the delivery\n// is nacked WITHOUT requeue and a security event is emitted — the event\n// never contains the received/expected HMAC value or the signing key. Only\n// a verified delivery reaches the handler, and only then is it acked.\n//\n// NEW-4 (CONTRACT.md §8 \"v2 — Replay Protection\", hard cutover): once the\n// HMAC verifies, the delivery is ADDITIONALLY rejected (same nack-without-\n// requeue path) when `key_version < 2`, `issued_at` falls outside the\n// ±skew freshness window, or `nonce` has already been seen. Because this\n// module verifies by re-serializing the parsed body (minus\n// `hmac_signature`) in insertion order (Pitfall 5), `nonce`/`issued_at` are\n// already covered by the HMAC bytes with no canonicalization change — only\n// the three validation gates below are new.\n//\n// This is the TS port of the already-tested Rust `verify_and_dispatch`/\n// `consume` (the Rust SDK's src/amqp/consumer.rs).\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport { verifyPayload } from './hmac.js';\n\n/**\n * Default freshness skew for `issued_at` acceptance (NEW-4): a message is\n * accepted only when its `issued_at` lies within ±5 minutes of the\n * verifier's clock, matching the server's\n * `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`\n * (CONTRACT.md §8 v2).\n */\nexport const DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when\n * `nonce` has already been recorded and its dedup entry has not yet\n * expired (i.e. this delivery is a replay); otherwise it records the nonce\n * with the given TTL and returns `false`.\n */\nexport interface NonceStore {\n checkAndRecord(nonce: string, ttlMs: number): boolean;\n}\n\n/**\n * Default in-memory nonce dedup store (NEW-4). Naturally bounded: each\n * entry expires after `ttlMs` (the caller passes 2x the freshness skew, so\n * a nonce can never still be \"fresh\" once its dedup entry has lapsed) and\n * expired entries are pruned opportunistically on each check — no\n * background timer and no unbounded growth under sustained traffic.\n *\n * Share ONE instance across every delivery from the same consumer (as\n * `consume()` does by default) — a fresh store per call provides no\n * cross-message replay protection.\n */\nexport class InMemoryNonceStore implements NonceStore {\n private readonly seenUntilMs = new Map<string, number>();\n\n checkAndRecord(nonce: string, ttlMs: number): boolean {\n const now = Date.now();\n this.prune(now);\n const expiry = this.seenUntilMs.get(nonce);\n if (expiry !== undefined && expiry > now) {\n return true;\n }\n this.seenUntilMs.set(nonce, now + ttlMs);\n return false;\n }\n\n private prune(now: number): void {\n for (const [nonce, expiry] of this.seenUntilMs) {\n if (expiry <= now) this.seenUntilMs.delete(nonce);\n }\n }\n}\n\ntype ReplayRejectReason = 'key_version' | 'issued_at' | 'nonce';\n\n/**\n * NEW-4 validation gates, checked only AFTER the HMAC has already verified.\n * Returns the failing gate's name, or `undefined` when all three pass.\n * `ttlMs` for the nonce store is 2x `skewMs` — the freshness window plus a\n * margin so a nonce cannot be replayed the instant its dedup entry expires\n * while `issued_at` might still (barely) be judged fresh by a differently-\n * skewed verifier.\n */\nfunction checkReplayProtection(\n body: Record<string, unknown>,\n skewMs: number,\n nonceStore: NonceStore,\n): ReplayRejectReason | undefined {\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || keyVersion < 2) {\n return 'key_version';\n }\n\n const issuedAtRaw = body.issued_at;\n if (typeof issuedAtRaw !== 'string') {\n return 'issued_at';\n }\n const issuedAtMs = Date.parse(issuedAtRaw);\n if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {\n return 'issued_at';\n }\n\n const nonce = body.nonce;\n if (typeof nonce !== 'string' || nonce.length === 0) {\n return 'nonce';\n }\n if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {\n return 'nonce';\n }\n\n return undefined;\n}\n\n/**\n * Minimal seam over the channel operations this module needs\n * (ack/nack/consume). `amqplib`'s `Channel` implements this directly;\n * tests provide a recording fake that never touches a live broker, so the\n * security-sensitive nack-without-requeue behavior can be asserted without\n * a running RabbitMQ instance.\n */\nexport interface ConsumeChannel {\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void | Promise<void>,\n ): Promise<unknown>;\n /** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\nexport interface ConsumeLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface ConsumeOptions {\n logger?: ConsumeLogger;\n /**\n * Strict mode (default true, CONTRACT.md §8.3): a message with no\n * `hmac_signature` is treated as a verification failure (nack-no-requeue),\n * not a pass-through. Lenient mode (false) is a temporary rolling-\n * deployment measure only — strict MUST remain the default.\n */\n strict?: boolean;\n /**\n * Freshness skew window for `issued_at` validation (NEW-4), in\n * milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),\n * matching the server default (CONTRACT.md §8 v2).\n */\n skewMs?: number;\n /**\n * Nonce replay-dedup store (NEW-4). Defaults to a fresh\n * `InMemoryNonceStore` per call when omitted — `consume()` creates and\n * shares ONE store across every delivery on that connection by default;\n * callers invoking `verifyAndDispatch` directly across multiple messages\n * must pass the same store explicitly for dedup to take effect.\n */\n nonceStore?: NonceStore;\n}\n\n/**\n * Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,\n * only on success, invoke `handler` with the parsed body (hmac_signature\n * removed) before acking. On any failure the delivery is nacked without\n * requeue and a security event is emitted that never contains the HMAC\n * value or the signing key.\n *\n * Exported (not just used internally) so it is the same separately-testable\n * unit backing `consume`'s per-message loop, mirroring the Rust SDK's\n * `verify_and_dispatch`.\n */\nexport async function verifyAndDispatch(\n channel: ConsumeChannel,\n msg: ConsumeMessage,\n signingKey: Buffer,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const { logger, strict = true } = options;\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n logger?.warn('axiam_sdk.security', 'AMQP message body failed JSON parse; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n const sig = typeof body.hmac_signature === 'string' ? body.hmac_signature : undefined;\n delete body.hmac_signature;\n const canonical = Buffer.from(JSON.stringify(body), 'utf8');\n\n // Strict mode (default, CONTRACT.md §8.3): a missing signature is treated\n // as a verification failure, not a pass-through. A present signature is\n // always verified regardless of strict/lenient mode; lenient mode only\n // changes the outcome for a MISSING signature (temporary rolling-\n // deployment measure — strict MUST remain the default).\n let verified: boolean;\n if (sig !== undefined) {\n verified = verifyPayload(signingKey, canonical, sig);\n } else {\n verified = !strict;\n }\n\n if (!verified) {\n // Security event (§8.4): timestamp, exchange, routing key, and tenant\n // context (if present in the body) — NEVER the signature value or the\n // signing key.\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn('axiam_sdk.security', 'AMQP HMAC verification failed; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n // NEW-4 (CONTRACT.md §8 v2, hard cutover): only reached once the HMAC has\n // verified. `body` was re-serialized in insertion order to compute\n // `canonical` above, so `nonce`/`issued_at` are already inside the bytes\n // that were just verified — these are the three ADDITIONAL validation\n // gates (key_version, freshness, replay), not re-verification.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);\n if (replayRejectReason) {\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn(\n 'axiam_sdk.security',\n `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,\n {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n },\n );\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n try {\n await handler(body);\n } catch (err) {\n // Do not requeue a handler-crashing message into a hot loop.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n error: err instanceof Error ? err.message : String(err),\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n channel.ack(msg);\n}\n\n/**\n * Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and\n * consume from it — verifying each delivery's HMAC-SHA256 signature\n * (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an\n * unverified message; verification failures are nacked without requeue and\n * logged as a security event.\n *\n * `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK\n * does not fetch it from the server (no such endpoint exists; CONTRACT.md\n * §8.1 assumes out-of-band provisioning).\n *\n * This function owns the full ack/nack loop; `handler` MUST NOT itself call\n * ack/nack (there is no delivery handle exposed to it).\n */\nexport async function consume(\n amqpUrl: string,\n queue: string,\n signingKey: Sensitive<Buffer>,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const connection = await amqp.connect(amqpUrl);\n const channel: Channel = await connection.createChannel();\n await channel.assertQueue(queue, { durable: true });\n\n // NEW-4: one nonce store shared across every delivery on this consumer —\n // a fresh store per message (the per-call default in `verifyAndDispatch`)\n // would defeat replay dedup entirely.\n const sharedOptions: ConsumeOptions = {\n ...options,\n nonceStore: options.nonceStore ?? new InMemoryNonceStore(),\n };\n\n await channel.consume(queue, (msg) => {\n if (!msg) return;\n void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.js';
|
|
2
|
-
import { V as Verifier } from './jwks-
|
|
2
|
+
import { V as Verifier } from './jwks-BgojMGC5.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Minimal session shape the middleware needs: a JWKS verifier (D-11) and the
|
|
@@ -9,13 +9,18 @@ import { V as Verifier } from './jwks-CX-nhD6A.js';
|
|
|
9
9
|
* DIFFERENT tenant in the same org.
|
|
10
10
|
*/
|
|
11
11
|
interface VerifiableSession {
|
|
12
|
+
/** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */
|
|
12
13
|
jwksVerifier: Verifier;
|
|
14
|
+
/** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */
|
|
13
15
|
tenantHeaderValue: string;
|
|
14
16
|
}
|
|
15
17
|
/** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */
|
|
16
18
|
interface AxiamIdentity {
|
|
19
|
+
/** The authenticated end user's id (the token's `sub` claim). */
|
|
17
20
|
userId: string;
|
|
21
|
+
/** The tenant the verified token was minted for (the token's `tenant_id` claim). */
|
|
18
22
|
tenantId: string;
|
|
23
|
+
/** Roles derived from the token's space-separated `scope` claim (§10). */
|
|
19
24
|
roles: string[];
|
|
20
25
|
}
|
|
21
26
|
/**
|
|
@@ -37,6 +42,7 @@ declare function authenticateRequest(session: VerifiableSession, token: string):
|
|
|
37
42
|
* itself, so this module pulls in no axios/grpc dependency.
|
|
38
43
|
*/
|
|
39
44
|
interface AuthzChecker {
|
|
45
|
+
/** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */
|
|
40
46
|
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
41
47
|
}
|
|
42
48
|
/**
|
|
@@ -48,11 +54,14 @@ interface AuthzChecker {
|
|
|
48
54
|
* not per-request, when it is absent.
|
|
49
55
|
*/
|
|
50
56
|
interface AuthzVerifiableSession extends VerifiableSession {
|
|
57
|
+
/** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */
|
|
51
58
|
authzClient?: AuthzChecker;
|
|
52
59
|
}
|
|
53
60
|
/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */
|
|
54
61
|
interface ResourceParamRef {
|
|
62
|
+
/** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */
|
|
55
63
|
readonly kind: 'param';
|
|
64
|
+
/** The path/route parameter name the resource id is read from. */
|
|
56
65
|
readonly name: string;
|
|
57
66
|
}
|
|
58
67
|
/**
|
|
@@ -92,6 +101,7 @@ interface RequireAccessOptions {
|
|
|
92
101
|
}
|
|
93
102
|
/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */
|
|
94
103
|
interface AuthzLogger {
|
|
104
|
+
/** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */
|
|
95
105
|
debug(event: string, message: string, context?: Record<string, unknown>): void;
|
|
96
106
|
}
|
|
97
107
|
/**
|
|
@@ -103,17 +113,24 @@ interface AuthzLogger {
|
|
|
103
113
|
declare function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker;
|
|
104
114
|
/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */
|
|
105
115
|
interface ErrorBody {
|
|
116
|
+
/** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */
|
|
106
117
|
error: string;
|
|
118
|
+
/** Human-readable explanation; never contains token material. */
|
|
107
119
|
message: string;
|
|
108
120
|
}
|
|
109
121
|
/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */
|
|
110
122
|
type CheckOutcome = {
|
|
123
|
+
/** The check passed — the caller proceeds to the handler. */
|
|
111
124
|
kind: 'allowed';
|
|
112
125
|
} | {
|
|
126
|
+
/** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */
|
|
113
127
|
kind: 'denied';
|
|
128
|
+
/** Denial message surfaced in the 403 body. */
|
|
114
129
|
message: string;
|
|
115
130
|
} | {
|
|
131
|
+
/** The authz transport failed — fail-closed → HTTP 503, never an allow. */
|
|
116
132
|
kind: 'unavailable';
|
|
133
|
+
/** Failure message surfaced in the 503 body. */
|
|
117
134
|
message: string;
|
|
118
135
|
};
|
|
119
136
|
/**
|
|
@@ -131,4 +148,4 @@ declare function evaluateAccess(checker: AuthzChecker, action: string, resourceI
|
|
|
131
148
|
/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */
|
|
132
149
|
declare function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean;
|
|
133
150
|
|
|
134
|
-
export { type
|
|
151
|
+
export { type AuthzVerifiableSession as A, type CheckOutcome as C, type ErrorBody as E, type RequireAccessOptions as R, type VerifiableSession as V, type AuthzLogger as a, type AxiamIdentity as b, type ResourceSpec as c, type AuthzChecker as d, type ResourceParamRef as e, ResourceResolutionError as f, type ResourceResolver as g, assertAuthzClient as h, authenticateRequest as i, evaluateAccess as j, fromParam as k, hasAnyRole as l, resolveResourceId as r };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.cjs';
|
|
2
|
-
import { V as Verifier } from './jwks-
|
|
2
|
+
import { V as Verifier } from './jwks-BgojMGC5.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Minimal session shape the middleware needs: a JWKS verifier (D-11) and the
|
|
@@ -9,13 +9,18 @@ import { V as Verifier } from './jwks-CX-nhD6A.cjs';
|
|
|
9
9
|
* DIFFERENT tenant in the same org.
|
|
10
10
|
*/
|
|
11
11
|
interface VerifiableSession {
|
|
12
|
+
/** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */
|
|
12
13
|
jwksVerifier: Verifier;
|
|
14
|
+
/** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */
|
|
13
15
|
tenantHeaderValue: string;
|
|
14
16
|
}
|
|
15
17
|
/** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */
|
|
16
18
|
interface AxiamIdentity {
|
|
19
|
+
/** The authenticated end user's id (the token's `sub` claim). */
|
|
17
20
|
userId: string;
|
|
21
|
+
/** The tenant the verified token was minted for (the token's `tenant_id` claim). */
|
|
18
22
|
tenantId: string;
|
|
23
|
+
/** Roles derived from the token's space-separated `scope` claim (§10). */
|
|
19
24
|
roles: string[];
|
|
20
25
|
}
|
|
21
26
|
/**
|
|
@@ -37,6 +42,7 @@ declare function authenticateRequest(session: VerifiableSession, token: string):
|
|
|
37
42
|
* itself, so this module pulls in no axios/grpc dependency.
|
|
38
43
|
*/
|
|
39
44
|
interface AuthzChecker {
|
|
45
|
+
/** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */
|
|
40
46
|
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
41
47
|
}
|
|
42
48
|
/**
|
|
@@ -48,11 +54,14 @@ interface AuthzChecker {
|
|
|
48
54
|
* not per-request, when it is absent.
|
|
49
55
|
*/
|
|
50
56
|
interface AuthzVerifiableSession extends VerifiableSession {
|
|
57
|
+
/** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */
|
|
51
58
|
authzClient?: AuthzChecker;
|
|
52
59
|
}
|
|
53
60
|
/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */
|
|
54
61
|
interface ResourceParamRef {
|
|
62
|
+
/** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */
|
|
55
63
|
readonly kind: 'param';
|
|
64
|
+
/** The path/route parameter name the resource id is read from. */
|
|
56
65
|
readonly name: string;
|
|
57
66
|
}
|
|
58
67
|
/**
|
|
@@ -92,6 +101,7 @@ interface RequireAccessOptions {
|
|
|
92
101
|
}
|
|
93
102
|
/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */
|
|
94
103
|
interface AuthzLogger {
|
|
104
|
+
/** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */
|
|
95
105
|
debug(event: string, message: string, context?: Record<string, unknown>): void;
|
|
96
106
|
}
|
|
97
107
|
/**
|
|
@@ -103,17 +113,24 @@ interface AuthzLogger {
|
|
|
103
113
|
declare function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker;
|
|
104
114
|
/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */
|
|
105
115
|
interface ErrorBody {
|
|
116
|
+
/** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */
|
|
106
117
|
error: string;
|
|
118
|
+
/** Human-readable explanation; never contains token material. */
|
|
107
119
|
message: string;
|
|
108
120
|
}
|
|
109
121
|
/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */
|
|
110
122
|
type CheckOutcome = {
|
|
123
|
+
/** The check passed — the caller proceeds to the handler. */
|
|
111
124
|
kind: 'allowed';
|
|
112
125
|
} | {
|
|
126
|
+
/** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */
|
|
113
127
|
kind: 'denied';
|
|
128
|
+
/** Denial message surfaced in the 403 body. */
|
|
114
129
|
message: string;
|
|
115
130
|
} | {
|
|
131
|
+
/** The authz transport failed — fail-closed → HTTP 503, never an allow. */
|
|
116
132
|
kind: 'unavailable';
|
|
133
|
+
/** Failure message surfaced in the 503 body. */
|
|
117
134
|
message: string;
|
|
118
135
|
};
|
|
119
136
|
/**
|
|
@@ -131,4 +148,4 @@ declare function evaluateAccess(checker: AuthzChecker, action: string, resourceI
|
|
|
131
148
|
/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */
|
|
132
149
|
declare function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean;
|
|
133
150
|
|
|
134
|
-
export { type
|
|
151
|
+
export { type AuthzVerifiableSession as A, type CheckOutcome as C, type ErrorBody as E, type RequireAccessOptions as R, type VerifiableSession as V, type AuthzLogger as a, type AxiamIdentity as b, type ResourceSpec as c, type AuthzChecker as d, type ResourceParamRef as e, ResourceResolutionError as f, type ResourceResolver as g, assertAuthzClient as h, authenticateRequest as i, evaluateAccess as j, fromParam as k, hasAnyRole as l, resolveResourceId as r };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { S as SharedSession, A as AxiamClientOptions } from './session-BWUWhhyB.cjs';
|
|
2
|
+
import { L as LoginResult, A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The main entry point for the AXIAM TypeScript/JavaScript SDK — an
|
|
6
|
+
* isomorphic (browser + Node) REST client for authentication and
|
|
7
|
+
* authorization against an AXIAM server.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* `AxiamClient` implements the SDK's cross-language behavioral contract
|
|
11
|
+
* (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/
|
|
12
|
+
* `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the
|
|
13
|
+
* three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic
|
|
14
|
+
* CSRF forwarding (§3), the required tenant context (§5), and a per-instance
|
|
15
|
+
* single-flight refresh guard that de-duplicates concurrent token refreshes
|
|
16
|
+
* (§9).
|
|
17
|
+
*
|
|
18
|
+
* A `tenantSlug` or `tenantId` is mandatory at construction — there is no
|
|
19
|
+
* default tenant, and AXIAM is a multi-tenant system where every
|
|
20
|
+
* authenticated call is scoped by the `X-Tenant-ID` header this client
|
|
21
|
+
* injects on every request (§5). Session tokens never appear as a return
|
|
22
|
+
* value or public property anywhere on this class: they arrive exclusively
|
|
23
|
+
* via `httpOnly` cookies set by the server.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
|
|
28
|
+
*
|
|
29
|
+
* const result = await client.login('user@example.com', 'hunter2');
|
|
30
|
+
* if (result.status === 'mfa_required') {
|
|
31
|
+
* await client.verifyMfa(result.mfaToken, '123456');
|
|
32
|
+
* }
|
|
33
|
+
*
|
|
34
|
+
* const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });
|
|
35
|
+
* if (!decision.allowed) {
|
|
36
|
+
* throw new Error(decision.reason ?? 'access denied');
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
declare class AxiamClient {
|
|
41
|
+
/** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */
|
|
42
|
+
readonly session: SharedSession;
|
|
43
|
+
/**
|
|
44
|
+
* @param options client configuration (§5/§6).
|
|
45
|
+
* @param session optional pre-built session to adopt instead of the default
|
|
46
|
+
* browser `SharedSession`. This is the injection point for the Node
|
|
47
|
+
* persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie
|
|
48
|
+
* jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`
|
|
49
|
+
* from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it
|
|
50
|
+
* is adopted here, so httpOnly login/refresh cookies persist. When omitted
|
|
51
|
+
* the browser `SharedSession` is built by default — the Node modules are
|
|
52
|
+
* NEVER statically imported from this browser-safe module, so a `/rest`
|
|
53
|
+
* browser bundle keeps pulling zero Node dependencies (SC#1).
|
|
54
|
+
*/
|
|
55
|
+
constructor(options: AxiamClientOptions, session?: SharedSession);
|
|
56
|
+
/** `POST /api/v1/auth/login` (§1, D-18). */
|
|
57
|
+
login(email: string, password: string): Promise<LoginResult>;
|
|
58
|
+
/** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */
|
|
59
|
+
verifyMfa(mfaToken: string, code: string): Promise<LoginResult>;
|
|
60
|
+
/** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */
|
|
61
|
+
refresh(): Promise<void>;
|
|
62
|
+
/** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */
|
|
63
|
+
logout(): Promise<void>;
|
|
64
|
+
/** `POST /api/v1/authz/check` (§1, FND-04). */
|
|
65
|
+
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
66
|
+
/** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */
|
|
67
|
+
can(action: string, resourceId: string, scope?: string): Promise<boolean>;
|
|
68
|
+
/** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */
|
|
69
|
+
batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { AxiamClient as A };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { S as SharedSession, A as AxiamClientOptions } from './session-BWUWhhyB.js';
|
|
2
|
+
import { L as LoginResult, A as AccessCheck, a as AccessDecision } from './types-BVkMoqLU.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The main entry point for the AXIAM TypeScript/JavaScript SDK — an
|
|
6
|
+
* isomorphic (browser + Node) REST client for authentication and
|
|
7
|
+
* authorization against an AXIAM server.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* `AxiamClient` implements the SDK's cross-language behavioral contract
|
|
11
|
+
* (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/
|
|
12
|
+
* `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the
|
|
13
|
+
* three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic
|
|
14
|
+
* CSRF forwarding (§3), the required tenant context (§5), and a per-instance
|
|
15
|
+
* single-flight refresh guard that de-duplicates concurrent token refreshes
|
|
16
|
+
* (§9).
|
|
17
|
+
*
|
|
18
|
+
* A `tenantSlug` or `tenantId` is mandatory at construction — there is no
|
|
19
|
+
* default tenant, and AXIAM is a multi-tenant system where every
|
|
20
|
+
* authenticated call is scoped by the `X-Tenant-ID` header this client
|
|
21
|
+
* injects on every request (§5). Session tokens never appear as a return
|
|
22
|
+
* value or public property anywhere on this class: they arrive exclusively
|
|
23
|
+
* via `httpOnly` cookies set by the server.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
|
|
28
|
+
*
|
|
29
|
+
* const result = await client.login('user@example.com', 'hunter2');
|
|
30
|
+
* if (result.status === 'mfa_required') {
|
|
31
|
+
* await client.verifyMfa(result.mfaToken, '123456');
|
|
32
|
+
* }
|
|
33
|
+
*
|
|
34
|
+
* const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });
|
|
35
|
+
* if (!decision.allowed) {
|
|
36
|
+
* throw new Error(decision.reason ?? 'access denied');
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
declare class AxiamClient {
|
|
41
|
+
/** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */
|
|
42
|
+
readonly session: SharedSession;
|
|
43
|
+
/**
|
|
44
|
+
* @param options client configuration (§5/§6).
|
|
45
|
+
* @param session optional pre-built session to adopt instead of the default
|
|
46
|
+
* browser `SharedSession`. This is the injection point for the Node
|
|
47
|
+
* persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie
|
|
48
|
+
* jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`
|
|
49
|
+
* from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it
|
|
50
|
+
* is adopted here, so httpOnly login/refresh cookies persist. When omitted
|
|
51
|
+
* the browser `SharedSession` is built by default — the Node modules are
|
|
52
|
+
* NEVER statically imported from this browser-safe module, so a `/rest`
|
|
53
|
+
* browser bundle keeps pulling zero Node dependencies (SC#1).
|
|
54
|
+
*/
|
|
55
|
+
constructor(options: AxiamClientOptions, session?: SharedSession);
|
|
56
|
+
/** `POST /api/v1/auth/login` (§1, D-18). */
|
|
57
|
+
login(email: string, password: string): Promise<LoginResult>;
|
|
58
|
+
/** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */
|
|
59
|
+
verifyMfa(mfaToken: string, code: string): Promise<LoginResult>;
|
|
60
|
+
/** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */
|
|
61
|
+
refresh(): Promise<void>;
|
|
62
|
+
/** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */
|
|
63
|
+
logout(): Promise<void>;
|
|
64
|
+
/** `POST /api/v1/authz/check` (§1, FND-04). */
|
|
65
|
+
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
66
|
+
/** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */
|
|
67
|
+
can(action: string, resourceId: string, scope?: string): Promise<boolean>;
|
|
68
|
+
/** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */
|
|
69
|
+
batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { AxiamClient as A };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { CookieJar } from 'tough-cookie';
|
|
2
|
+
import { S as SharedSession, A as AxiamClientOptions } from './session-BWUWhhyB.cjs';
|
|
3
|
+
import { A as AxiamClient } from './client-B_FqmZ0i.cjs';
|
|
4
|
+
import { S as Sensitive } from './sensitive-BC_s7Rrd.cjs';
|
|
5
|
+
import { V as Verifier } from './jwks-BgojMGC5.cjs';
|
|
6
|
+
import { AxiosInstance } from 'axios';
|
|
7
|
+
|
|
8
|
+
/** Tracks the access/refresh token pair for a Node session, kept in sync with the cookie jar after each REST call/refresh. */
|
|
9
|
+
declare class TokenManager {
|
|
10
|
+
#private;
|
|
11
|
+
constructor(jar: CookieJar, baseUrl: string, tenantId?: string);
|
|
12
|
+
/**
|
|
13
|
+
* Synchronous, best-effort read of the last-known access token. Returns
|
|
14
|
+
* `null` if no token has been cached yet (no request/refresh has
|
|
15
|
+
* completed since construction, or `syncFromJar()` was never called).
|
|
16
|
+
*/
|
|
17
|
+
cachedAccessToken(): Sensitive<string> | null;
|
|
18
|
+
/**
|
|
19
|
+
* Async read of the current `axiam_refresh` cookie value from the jar,
|
|
20
|
+
* wrapped in Sensitive<T>. Queried against the refresh endpoint's URL
|
|
21
|
+
* since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible
|
|
22
|
+
* at the bare base URL).
|
|
23
|
+
*/
|
|
24
|
+
refreshTokenValue(): Promise<Sensitive<string> | null>;
|
|
25
|
+
/**
|
|
26
|
+
* Refresh the in-memory cached access token from the jar. Call this after
|
|
27
|
+
* every REST request/refresh so the synchronous gRPC-interceptor fast-path
|
|
28
|
+
* (`cachedAccessToken()`) stays current (Pitfall 3).
|
|
29
|
+
*/
|
|
30
|
+
syncFromJar(): Promise<void>;
|
|
31
|
+
/** The resolved tenant identifier (slug or UUID form), if known. */
|
|
32
|
+
tenantId(): string | undefined;
|
|
33
|
+
/** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */
|
|
34
|
+
setTenantId(tenantId: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Best-effort decode of the `tenant_id`/`org_id` claims out of the cached
|
|
37
|
+
* access token, WITHOUT signature verification. Used only to populate the
|
|
38
|
+
* `refresh` request body (`RefreshRequest` requires both UUIDs) — never as a
|
|
39
|
+
* trust decision: the actual credential is the httpOnly `axiam_access` cookie
|
|
40
|
+
* the server verifies, and the server re-derives the authoritative `org_id`
|
|
41
|
+
* from the tenant on refresh (see crates/axiam-api-rest handlers/auth.rs),
|
|
42
|
+
* so echoing these values back carries no security weight. A malformed or
|
|
43
|
+
* absent token yields an empty result (the caller then keeps whatever UUIDs
|
|
44
|
+
* were resolved from construction options).
|
|
45
|
+
*/
|
|
46
|
+
claimsFromCachedToken(): {
|
|
47
|
+
tenantId?: string;
|
|
48
|
+
orgId?: string;
|
|
49
|
+
};
|
|
50
|
+
/** Clear all cached token state (used by logout()). */
|
|
51
|
+
clear(): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Node-only {@link SharedSession} adding a {@link TokenManager} and a JWKS {@link Verifier} for local (offline) access-token verification. */
|
|
55
|
+
declare class NodeSession extends SharedSession {
|
|
56
|
+
#private;
|
|
57
|
+
/** Manages the access/refresh token pair backing this session. */
|
|
58
|
+
readonly tokenManager: TokenManager;
|
|
59
|
+
/** Local JWKS verifier for validating access tokens without a server round-trip. */
|
|
60
|
+
readonly jwksVerifier: Verifier;
|
|
61
|
+
constructor(options: AxiamClientOptions, base: SharedSession, tokenManager: TokenManager, jwksVerifier: Verifier, jar: CookieJar);
|
|
62
|
+
/**
|
|
63
|
+
* Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this
|
|
64
|
+
* session's per-instance `refreshGuard` (inherited from SharedSession) by
|
|
65
|
+
* both REST's reactive interceptor (rest/interceptors.ts) and gRPC's
|
|
66
|
+
* callWithRefresh — since `refreshGuard` is scoped to THIS session
|
|
67
|
+
* instance (CR-02, D-13), both transports share exactly one in-flight
|
|
68
|
+
* refresh for this session regardless of which one triggers it, while
|
|
69
|
+
* remaining fully independent from any other session's guard.
|
|
70
|
+
*/
|
|
71
|
+
doRefresh: () => Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a
|
|
74
|
+
* successful login()/verifyMfa(). Refreshes the cached access token (so
|
|
75
|
+
* the gRPC interceptor's synchronous fast-path is current immediately
|
|
76
|
+
* after login) and reads the `axiam_csrf` cookie out of the jar into
|
|
77
|
+
* `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.
|
|
78
|
+
*/
|
|
79
|
+
onAuthenticated: () => Promise<void>;
|
|
80
|
+
}
|
|
81
|
+
/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */
|
|
82
|
+
declare function createNodeSession(options: AxiamClientOptions): NodeSession;
|
|
83
|
+
/**
|
|
84
|
+
* Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node
|
|
85
|
+
* counterpart to `new AxiamClient(options)` (which builds the browser
|
|
86
|
+
* `SharedSession` with no cookie jar): it constructs a `NodeSession`
|
|
87
|
+
* (tough-cookie jar + CSRF/refresh token sync) and adopts it via the
|
|
88
|
+
* `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens
|
|
89
|
+
* from login/refresh persist and every post-login REST call authenticates
|
|
90
|
+
* correctly under Node.
|
|
91
|
+
*
|
|
92
|
+
* Lives in this Node-only module (reachable via the `axiam-sdk/node` and
|
|
93
|
+
* `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`
|
|
94
|
+
* entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).
|
|
95
|
+
* The returned client shares the single session with any `AuthzGrpcClient`
|
|
96
|
+
* built from the same `NodeSession`.
|
|
97
|
+
*/
|
|
98
|
+
declare function createNodeClient(options: AxiamClientOptions): AxiamClient;
|
|
99
|
+
|
|
100
|
+
/** The `axiam_access` cookie name (httpOnly, path `/`). */
|
|
101
|
+
declare const ACCESS_COOKIE = "axiam_access";
|
|
102
|
+
/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */
|
|
103
|
+
declare const REFRESH_COOKIE = "axiam_refresh";
|
|
104
|
+
/** The `axiam_csrf` cookie name (JS-readable, path `/`). */
|
|
105
|
+
declare const CSRF_COOKIE = "axiam_csrf";
|
|
106
|
+
/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */
|
|
107
|
+
declare function createJar(): CookieJar;
|
|
108
|
+
/**
|
|
109
|
+
* Wrap an axios instance with `axios-cookiejar-support` so the jar persists
|
|
110
|
+
* `Set-Cookie` responses across requests and replays them on subsequent
|
|
111
|
+
* requests to the same origin/path (§4). Mutates and returns the same
|
|
112
|
+
* instance (matches `axios-cookiejar-support`'s documented in-place wrap).
|
|
113
|
+
*/
|
|
114
|
+
declare function wrapAxios(instance: AxiosInstance, jar: CookieJar): AxiosInstance;
|
|
115
|
+
/**
|
|
116
|
+
* Read a single cookie's value out of the jar by name, for the given URL.
|
|
117
|
+
* This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body
|
|
118
|
+
* fallback exists on the wire).
|
|
119
|
+
*/
|
|
120
|
+
declare function extractCookieValue(jar: CookieJar, url: string, name: string): Promise<string | undefined>;
|
|
121
|
+
|
|
122
|
+
export { ACCESS_COOKIE as A, CSRF_COOKIE as C, NodeSession as N, REFRESH_COOKIE as R, TokenManager as T, createNodeClient as a, createNodeSession as b, createJar as c, extractCookieValue as e, wrapAxios as w };
|