axiam-sdk 1.0.0-alpha
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/LICENSE +201 -0
- package/README.md +231 -0
- package/dist/amqp/index.d.cts +246 -0
- package/dist/amqp/index.d.ts +246 -0
- package/dist/amqp/index.js +179 -0
- package/dist/amqp/index.js.map +1 -0
- package/dist/amqp/index.mjs +166 -0
- package/dist/amqp/index.mjs.map +1 -0
- package/dist/client-B2SB-C7c.d.cts +207 -0
- package/dist/client-B2SB-C7c.d.ts +207 -0
- package/dist/grpc/index.d.cts +106 -0
- package/dist/grpc/index.d.ts +106 -0
- package/dist/grpc/index.js +908 -0
- package/dist/grpc/index.js.map +1 -0
- package/dist/grpc/index.mjs +868 -0
- package/dist/grpc/index.mjs.map +1 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +561 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +552 -0
- package/dist/index.mjs.map +1 -0
- package/dist/jwks-CX-nhD6A.d.cts +29 -0
- package/dist/jwks-CX-nhD6A.d.ts +29 -0
- package/dist/middleware/index.d.cts +153 -0
- package/dist/middleware/index.d.ts +153 -0
- package/dist/middleware/index.js +232 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/index.mjs +220 -0
- package/dist/middleware/index.mjs.map +1 -0
- package/dist/node/index.d.cts +103 -0
- package/dist/node/index.d.ts +103 -0
- package/dist/node/index.js +717 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/index.mjs +700 -0
- package/dist/node/index.mjs.map +1 -0
- package/dist/rest/index.d.cts +27 -0
- package/dist/rest/index.d.ts +27 -0
- package/dist/rest/index.js +561 -0
- package/dist/rest/index.js.map +1 -0
- package/dist/rest/index.mjs +552 -0
- package/dist/rest/index.mjs.map +1 -0
- package/dist/sensitive-CWBH_tHr.d.cts +12 -0
- package/dist/sensitive-CWBH_tHr.d.ts +12 -0
- package/package.json +145 -0
|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c,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"]}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { AxiosInstance } from 'axios';
|
|
2
|
+
|
|
3
|
+
/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */
|
|
4
|
+
type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for {@link AxiamClient}, passed as its constructor's first
|
|
8
|
+
* argument.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is
|
|
12
|
+
* multi-tenant and has no default tenant, so construction throws when both
|
|
13
|
+
* are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch
|
|
14
|
+
* (CONTRACT.md §6); there is no option to disable certificate verification.
|
|
15
|
+
*/
|
|
16
|
+
interface AxiamClientOptions {
|
|
17
|
+
/** Base URL of the AXIAM server, e.g. "https://iam.example.com". */
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
/** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */
|
|
20
|
+
tenantSlug?: string;
|
|
21
|
+
/** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */
|
|
22
|
+
tenantId?: string;
|
|
23
|
+
/** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */
|
|
24
|
+
customCa?: string;
|
|
25
|
+
/** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */
|
|
26
|
+
connectTimeoutMs?: number;
|
|
27
|
+
/** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */
|
|
28
|
+
requestTimeoutMs?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The outcome of an access check, shared by the REST (`AxiamClient.checkAccess`
|
|
33
|
+
* / `.batchCheck`) and gRPC (`AuthzGrpcClient.checkAccess` / `.batchCheck`)
|
|
34
|
+
* transports (CONTRACT.md §1). `reason` is present (and non-empty) only when
|
|
35
|
+
* `allowed` is `false`.
|
|
36
|
+
*/
|
|
37
|
+
interface AccessDecision {
|
|
38
|
+
/** Whether the checked action on the checked resource is permitted. */
|
|
39
|
+
allowed: boolean;
|
|
40
|
+
/** Present (and non-empty) only when `allowed` is `false`; a human-readable reason the check was denied. */
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The single session object every AXIAM transport (REST here, gRPC/AMQP in
|
|
46
|
+
* 17-03/17-04, middleware in 17-05) attaches to. Constructed once per
|
|
47
|
+
* `AxiamClient` instance.
|
|
48
|
+
*/
|
|
49
|
+
declare class SharedSession {
|
|
50
|
+
/** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */
|
|
51
|
+
readonly axios: AxiosInstance;
|
|
52
|
+
/** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */
|
|
53
|
+
readonly baseUrl: string;
|
|
54
|
+
/** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
|
|
55
|
+
readonly tenantHeaderValue: string;
|
|
56
|
+
/** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
|
|
57
|
+
csrfToken: string | undefined;
|
|
58
|
+
/** Set true once a successful login/verifyMfa has completed. */
|
|
59
|
+
authenticated: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Per-instance single-flight refresh guard (CR-02, D-13). Shared across
|
|
62
|
+
* this session's REST and gRPC transports (rest/interceptors.ts,
|
|
63
|
+
* grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but
|
|
64
|
+
* NEVER shared with a different SharedSession/NodeSession instance.
|
|
65
|
+
*
|
|
66
|
+
* @internal SDK-internal transport wiring, not intended to be invoked
|
|
67
|
+
* directly by SDK consumers — refreshes are driven automatically by the
|
|
68
|
+
* response interceptor (rest) or `callWithRefresh` (grpc).
|
|
69
|
+
*/
|
|
70
|
+
readonly refreshGuard: RefreshGuard;
|
|
71
|
+
constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string);
|
|
72
|
+
/**
|
|
73
|
+
* Optional session-level hook invoked by rest/auth.ts after a successful
|
|
74
|
+
* login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser
|
|
75
|
+
* persona) does not implement it — the browser reads document.cookie
|
|
76
|
+
* directly on every request and has no jar to sync from. NodeSession
|
|
77
|
+
* overrides this to populate `csrfToken` from its cookie jar and refresh
|
|
78
|
+
* the cached access token.
|
|
79
|
+
*/
|
|
80
|
+
onAuthenticated?(): Promise<void>;
|
|
81
|
+
/**
|
|
82
|
+
* Host-isolation guard (3A, defense in depth): returns `true` when `url`
|
|
83
|
+
* targets a host other than this session's base origin — an absolute
|
|
84
|
+
* third-party URL, or a redirect that axios/the browser resolved off-origin.
|
|
85
|
+
* The tenant identifier and CSRF token must never be attached to such a
|
|
86
|
+
* request. A relative/host-less `url` (the normal case, merged against
|
|
87
|
+
* `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's
|
|
88
|
+
* `_prepare_request` guard. Malformed input fails closed (treated as
|
|
89
|
+
* foreign).
|
|
90
|
+
*/
|
|
91
|
+
isForeignHost(url: string | undefined): boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The authenticated user's identity, as returned by `login()`/`verifyMfa()` on success. */
|
|
95
|
+
interface AxiamUserInfo {
|
|
96
|
+
/** The user's unique identifier (UUID). */
|
|
97
|
+
id: string;
|
|
98
|
+
/** The user's login username. */
|
|
99
|
+
username: string;
|
|
100
|
+
/** The user's email address. */
|
|
101
|
+
email: string;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The outcome of AxiamClient.login()/verifyMfa() (D-18).
|
|
105
|
+
*
|
|
106
|
+
* No raw session-token field exists here or anywhere else in the public
|
|
107
|
+
* REST API surface — AXIAM delivers tokens exclusively via `Set-Cookie`
|
|
108
|
+
* (T-17-07).
|
|
109
|
+
*/
|
|
110
|
+
type LoginResult = {
|
|
111
|
+
/** Discriminant: MFA is required to complete the login. */
|
|
112
|
+
status: 'mfa_required';
|
|
113
|
+
/** Opaque challenge token to pass to `verifyMfa(mfaToken, code)`. */
|
|
114
|
+
mfaToken: string;
|
|
115
|
+
/** The MFA methods the user has enrolled and may complete the challenge with. */
|
|
116
|
+
availableMethods: string[];
|
|
117
|
+
} | {
|
|
118
|
+
/** Discriminant: login completed and a session was established. */
|
|
119
|
+
status: 'authenticated';
|
|
120
|
+
/** The authenticated user's identity. */
|
|
121
|
+
user: AxiamUserInfo;
|
|
122
|
+
/** Opaque session identifier for this authenticated session. */
|
|
123
|
+
sessionId: string;
|
|
124
|
+
/** Access token lifetime in seconds from the time of this response. */
|
|
125
|
+
expiresIn: number;
|
|
126
|
+
};
|
|
127
|
+
/** A single access check request, as passed to `checkAccess()`/`can()`/`batchCheck()`. */
|
|
128
|
+
interface AccessCheck {
|
|
129
|
+
/** The action being performed (e.g. `"read"`, `"write"`, `"delete"`). */
|
|
130
|
+
action: string;
|
|
131
|
+
/** The identifier of the resource the action targets. */
|
|
132
|
+
resourceId: string;
|
|
133
|
+
/** Optional sub-resource scope for finer-grained checks. */
|
|
134
|
+
scope?: string;
|
|
135
|
+
/** Optional subject (user/service account) identifier to check on behalf of; defaults to the caller's own identity when omitted. */
|
|
136
|
+
subjectId?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The main entry point for the AXIAM TypeScript/JavaScript SDK — an
|
|
141
|
+
* isomorphic (browser + Node) REST client for authentication and
|
|
142
|
+
* authorization against an AXIAM server.
|
|
143
|
+
*
|
|
144
|
+
* @remarks
|
|
145
|
+
* `AxiamClient` implements the SDK's cross-language behavioral contract
|
|
146
|
+
* (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/
|
|
147
|
+
* `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the
|
|
148
|
+
* three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic
|
|
149
|
+
* CSRF forwarding (§3), the required tenant context (§5), and a per-instance
|
|
150
|
+
* single-flight refresh guard that de-duplicates concurrent token refreshes
|
|
151
|
+
* (§9).
|
|
152
|
+
*
|
|
153
|
+
* A `tenantSlug` or `tenantId` is mandatory at construction — there is no
|
|
154
|
+
* default tenant, and AXIAM is a multi-tenant system where every
|
|
155
|
+
* authenticated call is scoped by the `X-Tenant-ID` header this client
|
|
156
|
+
* injects on every request (§5). Session tokens never appear as a return
|
|
157
|
+
* value or public property anywhere on this class: they arrive exclusively
|
|
158
|
+
* via `httpOnly` cookies set by the server.
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```ts
|
|
162
|
+
* const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
|
|
163
|
+
*
|
|
164
|
+
* const result = await client.login('user@example.com', 'hunter2');
|
|
165
|
+
* if (result.status === 'mfa_required') {
|
|
166
|
+
* await client.verifyMfa(result.mfaToken, '123456');
|
|
167
|
+
* }
|
|
168
|
+
*
|
|
169
|
+
* const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });
|
|
170
|
+
* if (!decision.allowed) {
|
|
171
|
+
* throw new Error(decision.reason ?? 'access denied');
|
|
172
|
+
* }
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
declare class AxiamClient {
|
|
176
|
+
/** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */
|
|
177
|
+
readonly session: SharedSession;
|
|
178
|
+
/**
|
|
179
|
+
* @param options client configuration (§5/§6).
|
|
180
|
+
* @param session optional pre-built session to adopt instead of the default
|
|
181
|
+
* browser `SharedSession`. This is the injection point for the Node
|
|
182
|
+
* persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie
|
|
183
|
+
* jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`
|
|
184
|
+
* from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it
|
|
185
|
+
* is adopted here, so httpOnly login/refresh cookies persist. When omitted
|
|
186
|
+
* the browser `SharedSession` is built by default — the Node modules are
|
|
187
|
+
* NEVER statically imported from this browser-safe module, so a `/rest`
|
|
188
|
+
* browser bundle keeps pulling zero Node dependencies (SC#1).
|
|
189
|
+
*/
|
|
190
|
+
constructor(options: AxiamClientOptions, session?: SharedSession);
|
|
191
|
+
/** `POST /api/v1/auth/login` (§1, D-18). */
|
|
192
|
+
login(email: string, password: string): Promise<LoginResult>;
|
|
193
|
+
/** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */
|
|
194
|
+
verifyMfa(mfaToken: string, code: string): Promise<LoginResult>;
|
|
195
|
+
/** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */
|
|
196
|
+
refresh(): Promise<void>;
|
|
197
|
+
/** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */
|
|
198
|
+
logout(): Promise<void>;
|
|
199
|
+
/** `POST /api/v1/authz/check` (§1, FND-04). */
|
|
200
|
+
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
201
|
+
/** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */
|
|
202
|
+
can(action: string, resourceId: string, scope?: string): Promise<boolean>;
|
|
203
|
+
/** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */
|
|
204
|
+
batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export { type AccessDecision as A, type LoginResult as L, SharedSession as S, type AxiamClientOptions as a, AxiamClient as b, type AccessCheck as c, type AxiamUserInfo as d };
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { AxiosInstance } from 'axios';
|
|
2
|
+
|
|
3
|
+
/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */
|
|
4
|
+
type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for {@link AxiamClient}, passed as its constructor's first
|
|
8
|
+
* argument.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is
|
|
12
|
+
* multi-tenant and has no default tenant, so construction throws when both
|
|
13
|
+
* are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch
|
|
14
|
+
* (CONTRACT.md §6); there is no option to disable certificate verification.
|
|
15
|
+
*/
|
|
16
|
+
interface AxiamClientOptions {
|
|
17
|
+
/** Base URL of the AXIAM server, e.g. "https://iam.example.com". */
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
/** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */
|
|
20
|
+
tenantSlug?: string;
|
|
21
|
+
/** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */
|
|
22
|
+
tenantId?: string;
|
|
23
|
+
/** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */
|
|
24
|
+
customCa?: string;
|
|
25
|
+
/** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */
|
|
26
|
+
connectTimeoutMs?: number;
|
|
27
|
+
/** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */
|
|
28
|
+
requestTimeoutMs?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The outcome of an access check, shared by the REST (`AxiamClient.checkAccess`
|
|
33
|
+
* / `.batchCheck`) and gRPC (`AuthzGrpcClient.checkAccess` / `.batchCheck`)
|
|
34
|
+
* transports (CONTRACT.md §1). `reason` is present (and non-empty) only when
|
|
35
|
+
* `allowed` is `false`.
|
|
36
|
+
*/
|
|
37
|
+
interface AccessDecision {
|
|
38
|
+
/** Whether the checked action on the checked resource is permitted. */
|
|
39
|
+
allowed: boolean;
|
|
40
|
+
/** Present (and non-empty) only when `allowed` is `false`; a human-readable reason the check was denied. */
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The single session object every AXIAM transport (REST here, gRPC/AMQP in
|
|
46
|
+
* 17-03/17-04, middleware in 17-05) attaches to. Constructed once per
|
|
47
|
+
* `AxiamClient` instance.
|
|
48
|
+
*/
|
|
49
|
+
declare class SharedSession {
|
|
50
|
+
/** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */
|
|
51
|
+
readonly axios: AxiosInstance;
|
|
52
|
+
/** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */
|
|
53
|
+
readonly baseUrl: string;
|
|
54
|
+
/** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
|
|
55
|
+
readonly tenantHeaderValue: string;
|
|
56
|
+
/** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
|
|
57
|
+
csrfToken: string | undefined;
|
|
58
|
+
/** Set true once a successful login/verifyMfa has completed. */
|
|
59
|
+
authenticated: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Per-instance single-flight refresh guard (CR-02, D-13). Shared across
|
|
62
|
+
* this session's REST and gRPC transports (rest/interceptors.ts,
|
|
63
|
+
* grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but
|
|
64
|
+
* NEVER shared with a different SharedSession/NodeSession instance.
|
|
65
|
+
*
|
|
66
|
+
* @internal SDK-internal transport wiring, not intended to be invoked
|
|
67
|
+
* directly by SDK consumers — refreshes are driven automatically by the
|
|
68
|
+
* response interceptor (rest) or `callWithRefresh` (grpc).
|
|
69
|
+
*/
|
|
70
|
+
readonly refreshGuard: RefreshGuard;
|
|
71
|
+
constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string);
|
|
72
|
+
/**
|
|
73
|
+
* Optional session-level hook invoked by rest/auth.ts after a successful
|
|
74
|
+
* login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser
|
|
75
|
+
* persona) does not implement it — the browser reads document.cookie
|
|
76
|
+
* directly on every request and has no jar to sync from. NodeSession
|
|
77
|
+
* overrides this to populate `csrfToken` from its cookie jar and refresh
|
|
78
|
+
* the cached access token.
|
|
79
|
+
*/
|
|
80
|
+
onAuthenticated?(): Promise<void>;
|
|
81
|
+
/**
|
|
82
|
+
* Host-isolation guard (3A, defense in depth): returns `true` when `url`
|
|
83
|
+
* targets a host other than this session's base origin — an absolute
|
|
84
|
+
* third-party URL, or a redirect that axios/the browser resolved off-origin.
|
|
85
|
+
* The tenant identifier and CSRF token must never be attached to such a
|
|
86
|
+
* request. A relative/host-less `url` (the normal case, merged against
|
|
87
|
+
* `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's
|
|
88
|
+
* `_prepare_request` guard. Malformed input fails closed (treated as
|
|
89
|
+
* foreign).
|
|
90
|
+
*/
|
|
91
|
+
isForeignHost(url: string | undefined): boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The authenticated user's identity, as returned by `login()`/`verifyMfa()` on success. */
|
|
95
|
+
interface AxiamUserInfo {
|
|
96
|
+
/** The user's unique identifier (UUID). */
|
|
97
|
+
id: string;
|
|
98
|
+
/** The user's login username. */
|
|
99
|
+
username: string;
|
|
100
|
+
/** The user's email address. */
|
|
101
|
+
email: string;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The outcome of AxiamClient.login()/verifyMfa() (D-18).
|
|
105
|
+
*
|
|
106
|
+
* No raw session-token field exists here or anywhere else in the public
|
|
107
|
+
* REST API surface — AXIAM delivers tokens exclusively via `Set-Cookie`
|
|
108
|
+
* (T-17-07).
|
|
109
|
+
*/
|
|
110
|
+
type LoginResult = {
|
|
111
|
+
/** Discriminant: MFA is required to complete the login. */
|
|
112
|
+
status: 'mfa_required';
|
|
113
|
+
/** Opaque challenge token to pass to `verifyMfa(mfaToken, code)`. */
|
|
114
|
+
mfaToken: string;
|
|
115
|
+
/** The MFA methods the user has enrolled and may complete the challenge with. */
|
|
116
|
+
availableMethods: string[];
|
|
117
|
+
} | {
|
|
118
|
+
/** Discriminant: login completed and a session was established. */
|
|
119
|
+
status: 'authenticated';
|
|
120
|
+
/** The authenticated user's identity. */
|
|
121
|
+
user: AxiamUserInfo;
|
|
122
|
+
/** Opaque session identifier for this authenticated session. */
|
|
123
|
+
sessionId: string;
|
|
124
|
+
/** Access token lifetime in seconds from the time of this response. */
|
|
125
|
+
expiresIn: number;
|
|
126
|
+
};
|
|
127
|
+
/** A single access check request, as passed to `checkAccess()`/`can()`/`batchCheck()`. */
|
|
128
|
+
interface AccessCheck {
|
|
129
|
+
/** The action being performed (e.g. `"read"`, `"write"`, `"delete"`). */
|
|
130
|
+
action: string;
|
|
131
|
+
/** The identifier of the resource the action targets. */
|
|
132
|
+
resourceId: string;
|
|
133
|
+
/** Optional sub-resource scope for finer-grained checks. */
|
|
134
|
+
scope?: string;
|
|
135
|
+
/** Optional subject (user/service account) identifier to check on behalf of; defaults to the caller's own identity when omitted. */
|
|
136
|
+
subjectId?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The main entry point for the AXIAM TypeScript/JavaScript SDK — an
|
|
141
|
+
* isomorphic (browser + Node) REST client for authentication and
|
|
142
|
+
* authorization against an AXIAM server.
|
|
143
|
+
*
|
|
144
|
+
* @remarks
|
|
145
|
+
* `AxiamClient` implements the SDK's cross-language behavioral contract
|
|
146
|
+
* (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/
|
|
147
|
+
* `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the
|
|
148
|
+
* three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic
|
|
149
|
+
* CSRF forwarding (§3), the required tenant context (§5), and a per-instance
|
|
150
|
+
* single-flight refresh guard that de-duplicates concurrent token refreshes
|
|
151
|
+
* (§9).
|
|
152
|
+
*
|
|
153
|
+
* A `tenantSlug` or `tenantId` is mandatory at construction — there is no
|
|
154
|
+
* default tenant, and AXIAM is a multi-tenant system where every
|
|
155
|
+
* authenticated call is scoped by the `X-Tenant-ID` header this client
|
|
156
|
+
* injects on every request (§5). Session tokens never appear as a return
|
|
157
|
+
* value or public property anywhere on this class: they arrive exclusively
|
|
158
|
+
* via `httpOnly` cookies set by the server.
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```ts
|
|
162
|
+
* const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
|
|
163
|
+
*
|
|
164
|
+
* const result = await client.login('user@example.com', 'hunter2');
|
|
165
|
+
* if (result.status === 'mfa_required') {
|
|
166
|
+
* await client.verifyMfa(result.mfaToken, '123456');
|
|
167
|
+
* }
|
|
168
|
+
*
|
|
169
|
+
* const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });
|
|
170
|
+
* if (!decision.allowed) {
|
|
171
|
+
* throw new Error(decision.reason ?? 'access denied');
|
|
172
|
+
* }
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
declare class AxiamClient {
|
|
176
|
+
/** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */
|
|
177
|
+
readonly session: SharedSession;
|
|
178
|
+
/**
|
|
179
|
+
* @param options client configuration (§5/§6).
|
|
180
|
+
* @param session optional pre-built session to adopt instead of the default
|
|
181
|
+
* browser `SharedSession`. This is the injection point for the Node
|
|
182
|
+
* persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie
|
|
183
|
+
* jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`
|
|
184
|
+
* from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it
|
|
185
|
+
* is adopted here, so httpOnly login/refresh cookies persist. When omitted
|
|
186
|
+
* the browser `SharedSession` is built by default — the Node modules are
|
|
187
|
+
* NEVER statically imported from this browser-safe module, so a `/rest`
|
|
188
|
+
* browser bundle keeps pulling zero Node dependencies (SC#1).
|
|
189
|
+
*/
|
|
190
|
+
constructor(options: AxiamClientOptions, session?: SharedSession);
|
|
191
|
+
/** `POST /api/v1/auth/login` (§1, D-18). */
|
|
192
|
+
login(email: string, password: string): Promise<LoginResult>;
|
|
193
|
+
/** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */
|
|
194
|
+
verifyMfa(mfaToken: string, code: string): Promise<LoginResult>;
|
|
195
|
+
/** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */
|
|
196
|
+
refresh(): Promise<void>;
|
|
197
|
+
/** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */
|
|
198
|
+
logout(): Promise<void>;
|
|
199
|
+
/** `POST /api/v1/authz/check` (§1, FND-04). */
|
|
200
|
+
checkAccess(check: AccessCheck): Promise<AccessDecision>;
|
|
201
|
+
/** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */
|
|
202
|
+
can(action: string, resourceId: string, scope?: string): Promise<boolean>;
|
|
203
|
+
/** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */
|
|
204
|
+
batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export { type AccessDecision as A, type LoginResult as L, SharedSession as S, type AxiamClientOptions as a, AxiamClient as b, type AccessCheck as c, type AxiamUserInfo as d };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import * as grpc from '@grpc/grpc-js';
|
|
2
|
+
import { Interceptor } from '@grpc/grpc-js';
|
|
3
|
+
import { NodeSession } from '../node/index.cjs';
|
|
4
|
+
export { ACCESS_COOKIE, CSRF_COOKIE, REFRESH_COOKIE, TokenManager, createJar, createNodeClient, createNodeSession, extractCookieValue, wrapAxios } from '../node/index.cjs';
|
|
5
|
+
import { A as AccessDecision } from '../client-B2SB-C7c.cjs';
|
|
6
|
+
export { A as AxiamClaims, J as JWKS_PATH, V as Verifier, c as createVerifier } from '../jwks-CX-nhD6A.cjs';
|
|
7
|
+
import 'tough-cookie';
|
|
8
|
+
import '../sensitive-CWBH_tHr.cjs';
|
|
9
|
+
import 'axios';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Injects `authorization: Bearer <token>` (when a cached token is present)
|
|
13
|
+
* and `x-tenant-id` metadata on every outgoing RPC (CONTRACT.md §5). Never
|
|
14
|
+
* logs the token — `expose()` is only called at this metadata-insertion
|
|
15
|
+
* boundary.
|
|
16
|
+
*/
|
|
17
|
+
declare function authInterceptor(session: NodeSession): Interceptor;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Await `fn()`. On a gRPC UNAUTHENTICATED (16) error, drive the shared
|
|
21
|
+
* single-flight refresh, sync the token cache from the jar, and retry `fn()`
|
|
22
|
+
* exactly once. Any other error (or a second UNAUTHENTICATED) is mapped to
|
|
23
|
+
* an AxiamError via `mapGrpcStatusToError` and rethrown.
|
|
24
|
+
*/
|
|
25
|
+
declare function callWithRefresh<T>(session: NodeSession, fn: () => Promise<T>): Promise<T>;
|
|
26
|
+
|
|
27
|
+
interface WireCheckAccessRequest {
|
|
28
|
+
tenant_id: string;
|
|
29
|
+
subject_id: string;
|
|
30
|
+
action: string;
|
|
31
|
+
resource_id: string;
|
|
32
|
+
scope?: string;
|
|
33
|
+
}
|
|
34
|
+
interface WireCheckAccessResponse {
|
|
35
|
+
allowed: boolean;
|
|
36
|
+
deny_reason: string;
|
|
37
|
+
}
|
|
38
|
+
interface WireBatchCheckAccessRequest {
|
|
39
|
+
requests: WireCheckAccessRequest[];
|
|
40
|
+
}
|
|
41
|
+
interface WireBatchCheckAccessResponse {
|
|
42
|
+
results: WireCheckAccessResponse[];
|
|
43
|
+
}
|
|
44
|
+
type UnaryCallback<T> = (error: grpc.ServiceError | null, response?: T) => void;
|
|
45
|
+
/**
|
|
46
|
+
* The subset of a ts-proto (`outputServices=grpc-js`) generated
|
|
47
|
+
* `AuthorizationServiceClient` this module needs. The real generated client
|
|
48
|
+
* satisfies this shape exactly (unary Node-callback methods), so a
|
|
49
|
+
* buf-enabled build's generated client is a drop-in replacement here.
|
|
50
|
+
*/
|
|
51
|
+
interface WireAuthorizationServiceClient {
|
|
52
|
+
checkAccess(request: WireCheckAccessRequest, metadata: grpc.Metadata, callback: UnaryCallback<WireCheckAccessResponse>): grpc.ClientUnaryCall;
|
|
53
|
+
batchCheckAccess(request: WireBatchCheckAccessRequest, metadata: grpc.Metadata, callback: UnaryCallback<WireBatchCheckAccessResponse>): grpc.ClientUnaryCall;
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Public (camelCase, §1) single access-check request shape.
|
|
58
|
+
*
|
|
59
|
+
* `subjectId` is required here (unlike REST's optional `AccessCheck.subjectId`)
|
|
60
|
+
* because gRPC calls typically originate from a service-mesh caller with no
|
|
61
|
+
* request-scoped JWT to derive a subject from — the caller must pass it
|
|
62
|
+
* explicitly. REST, by contrast, derives the subject from the caller's JWT
|
|
63
|
+
* when `subjectId` is omitted (§5). This mirrors the proto's non-`optional`
|
|
64
|
+
* `subject_id` field (`proto/axiam/v1/authorization.proto`), which is not
|
|
65
|
+
* changed here (SDK-Q10, C2).
|
|
66
|
+
*/
|
|
67
|
+
interface CheckAccessRequest {
|
|
68
|
+
tenantId: string;
|
|
69
|
+
subjectId: string;
|
|
70
|
+
action: string;
|
|
71
|
+
resourceId: string;
|
|
72
|
+
scope?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Construct a real `AuthorizationServiceClient` over grpc-js's own
|
|
76
|
+
* `makeClientConstructor` primitive (the same primitive ts-proto's
|
|
77
|
+
* `outputServices=grpc-js` codegen target uses under the hood). This
|
|
78
|
+
* transport-level client encodes/decodes with JSON as a build-independent
|
|
79
|
+
* stand-in for the protobuf binary codec a buf-enabled build's generated
|
|
80
|
+
* serializers would use — swap this factory for the generated
|
|
81
|
+
* `AuthorizationServiceClient` once `src/gen` exists (D-20).
|
|
82
|
+
*/
|
|
83
|
+
declare function buildAuthorizationServiceClient(baseUrl: string, credentials: grpc.ChannelCredentials, interceptors: grpc.Interceptor[]): WireAuthorizationServiceClient;
|
|
84
|
+
type AuthorizationServiceClientFactory = (baseUrl: string, credentials: grpc.ChannelCredentials, interceptors: grpc.Interceptor[]) => WireAuthorizationServiceClient;
|
|
85
|
+
/**
|
|
86
|
+
* gRPC transport for `AuthorizationService` (`checkAccess`/`batchCheck`,
|
|
87
|
+
* SC#2 Node half), reusing one long-lived client/channel per instance (D-10
|
|
88
|
+
* — never reconstructed per-call) and injecting auth + tenant metadata via
|
|
89
|
+
* the synchronous interceptor on every RPC.
|
|
90
|
+
*/
|
|
91
|
+
declare class AuthzGrpcClient {
|
|
92
|
+
#private;
|
|
93
|
+
constructor(session: NodeSession, options: {
|
|
94
|
+
baseUrl: string;
|
|
95
|
+
customCa?: string;
|
|
96
|
+
allowInsecure?: boolean;
|
|
97
|
+
}, clientFactory?: AuthorizationServiceClientFactory);
|
|
98
|
+
/** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */
|
|
99
|
+
checkAccess(request: CheckAccessRequest): Promise<AccessDecision>;
|
|
100
|
+
/** `BatchCheckAccess` over gRPC — results preserve input order (§1). */
|
|
101
|
+
batchCheck(requests: CheckAccessRequest[]): Promise<AccessDecision[]>;
|
|
102
|
+
/** Close the underlying gRPC channel. */
|
|
103
|
+
close(): void;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { AccessDecision, type AuthorizationServiceClientFactory, AuthzGrpcClient, type CheckAccessRequest, NodeSession, type WireAuthorizationServiceClient, type WireBatchCheckAccessRequest, type WireBatchCheckAccessResponse, type WireCheckAccessRequest, type WireCheckAccessResponse, authInterceptor, buildAuthorizationServiceClient, callWithRefresh };
|