axiam-sdk 1.0.0-alpha2 → 1.0.0-alpha8

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/grpc/interceptor.ts","../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/grpc/callWithRefresh.ts","../../src/grpc/client.ts","../../src/rest/session.ts","../../src/rest/interceptors.ts","../../src/rest/auth.ts","../../src/rest/authz.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../../src/node/tokenManager.ts","../../src/node/jwks.ts","../../src/node/session.ts"],"names":["grpc","grpc2","axios","CookieJar","wrapper"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,CAAC,SAAS,QAAA,KAAa;AAC5B,IAAA,OAAO,IAASA,gBAAA,CAAA,gBAAA,CAAiB,QAAA,CAAS,OAAO,CAAA,EAAG;AAAA,MAClD,KAAA,CAAM,QAAA,EAAU,QAAA,EAAU,IAAA,EAAM;AAE9B,QAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,YAAA,CAAa,iBAAA,EAAkB;AACrD,QAAA,IAAI,KAAA,EAAO;AACT,UAAA,QAAA,CAAS,IAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,KAAA,CAAM,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,QAC1D;AACA,QAAA,QAAA,CAAS,GAAA,CAAI,aAAA,EAAe,OAAA,CAAQ,iBAAiB,CAAA;AACrD,QAAA,IAAA,CAAK,UAAU,QAAQ,CAAA;AAAA,MACzB;AAAA,KACD,CAAA;AAAA,EACH,CAAA;AACF;;;AC7BO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,I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AA,EAA0C;AACzE,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,iBAAA,CAAkB,OAAO,CAAC,CAAA;AAC5D","file":"index.js","sourcesContent":["// Synchronous auth/tenant grpc-js interceptor (D-10, Pitfall 3).\n//\n// grpc-js's `start(metadata, listener, next)` callback is SYNCHRONOUS —\n// unlike tonic's async-native interceptor trait, it must call\n// `next(metadata, listener)` without ever awaiting. This interceptor\n// therefore only reads the TokenManager's non-blocking, in-memory cached\n// access token (populated by `syncFromJar()` after REST calls/refresh) —\n// it NEVER triggers a refresh itself. UNAUTHENTICATED handling belongs to\n// the async call-wrapper (callWithRefresh.ts), never here.\n//\n// Mirrors the Rust SDK's src/grpc/interceptor.rs exactly, adapted to grpc-js's\n// structurally different (non-tower) interceptor API\n// (RESEARCH.md Area 3 / grpc/proposal L5-node-client-interceptors.md).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { Interceptor } from '@grpc/grpc-js';\nimport type { NodeSession } from '../node/session.js';\n\n/**\n * Injects `authorization: Bearer <token>` (when a cached token is present)\n * and `x-tenant-id` metadata on every outgoing RPC (CONTRACT.md §5). Never\n * logs the token — `expose()` is only called at this metadata-insertion\n * boundary.\n */\nexport function authInterceptor(session: NodeSession): Interceptor {\n return (options, nextCall) => {\n return new grpc.InterceptingCall(nextCall(options), {\n start(metadata, listener, next) {\n // Non-blocking cached-token read — NEVER await here (Pitfall 3).\n const token = session.tokenManager.cachedAccessToken();\n if (token) {\n metadata.add('authorization', `Bearer ${token.expose()}`);\n }\n metadata.add('x-tenant-id', session.tenantHeaderValue);\n next(metadata, listener);\n },\n });\n };\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Exactly three concrete error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. No error message or field may\n// embed a raw token string (D-16). The prototype chain is fixed up manually\n// in each constructor so `instanceof` works reliably across the transpiled\n// CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat when\n// extending built-ins like Error).\n\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AuthError extends AxiamError {\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport class AuthzError extends AxiamError {\n readonly action?: string;\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\nexport class NetworkError extends AxiamError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Central status -> error mapper (CONTRACT.md §2, D-17).\n//\n// The single source of truth for both rest/ and grpc/ transports so the two\n// cannot drift on the error taxonomy. Transcribes CONTRACT.md §2's HTTP and\n// gRPC tables exactly.\n//\n// GrpcStatus is exported here (not imported from @grpc/grpc-js) so that\n// core stays dependency-free — grpc/ imports the numeric codes from core\n// rather than the other way around.\n\nimport { AuthError, AuthzError, NetworkError, type AxiamError } from './errors.js';\n\n/** gRPC status codes referenced by CONTRACT.md §2 (subset of the full grpc.status enum). */\nexport const GrpcStatus = {\n DEADLINE_EXCEEDED: 4,\n PERMISSION_DENIED: 7,\n RESOURCE_EXHAUSTED: 8,\n INTERNAL: 13,\n UNAVAILABLE: 14,\n UNAUTHENTICATED: 16,\n} as const;\n\nexport interface HttpErrorContext {\n action?: string;\n resourceId?: string;\n cause?: unknown;\n /**\n * The parsed JSON response body (when available). For a 403/409\n * authorization-denied response the server shapes this as\n * `{ error: \"authorization_denied\", message, action?, resource_id? }`\n * (`action` present when known, `resource_id` present only for a\n * resource-scoped denial). `mapHttpStatusToError` prefers these body\n * fields over `action`/`resourceId` above when populating `AuthzError`.\n */\n body?: unknown;\n}\n\n/**\n * Extract `action`/`resource_id` (snake_case -> camelCase) from a parsed\n * authorization-denied response body, if present and string-typed. Any other\n * shape (missing fields, non-object body, older servers with no body at all)\n * yields `{}`, so callers fall back to caller-supplied context.\n */\nfunction extractAuthzFieldsFromBody(body: unknown): { action?: string; resourceId?: string } {\n if (body === null || typeof body !== 'object') {\n return {};\n }\n const record = body as Record<string, unknown>;\n const action = typeof record.action === 'string' ? record.action : undefined;\n const resourceId = typeof record.resource_id === 'string' ? record.resource_id : undefined;\n return { action, resourceId };\n}\n\n/**\n * ALLOWLIST (X-3) of response headers that are safe to preserve in a\n * NetworkError.cause. Every header NOT listed here has its value redacted to a\n * placeholder, so a custom sensitive header (e.g. `X-Auth-Token`) can never\n * survive into a thrown error — unlike a small denylist, which only catches the\n * headers it happens to enumerate. Names are compared case-insensitively (all\n * entries are lower-case). Keep this list small and strictly non-secret:\n * standard diagnostic response headers plus this SDK's own non-secret request\n * headers (e.g. `x-tenant-id`).\n */\nconst SAFE_RESPONSE_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'date',\n 'server',\n 'retry-after',\n 'x-request-id',\n 'x-tenant-id',\n]);\n\n/** Placeholder substituted for the value of any non-allowlisted header. */\nconst REDACTED_HEADER = '[REDACTED]';\n\n/**\n * Redact every non-allowlisted response header from an axios-error-shaped\n * `err` before it is attached as `NetworkError.cause` (CR-04, D-16, X-3). On\n * login/refresh error paths the server may have already issued Set-Cookie\n * headers containing raw `axiam_access`/`axiam_refresh` values (and callers may\n * set custom sensitive headers such as `X-Auth-Token`); none of these must be\n * reachable via `console.log`/`JSON.stringify`/`util.inspect` of the thrown\n * error. Only headers on `SAFE_RESPONSE_HEADERS` keep their value; all others\n * are replaced with `[REDACTED]`.\n *\n * Returns a new, shallow-cloned object for any input shaped like\n * `{ response: { headers: {...} } }` — the caller's original axios error\n * object is left untouched. Non-object inputs (plain Error, string,\n * undefined) and objects with no `response.headers` are returned unchanged.\n */\nexport function sanitizeAxiosError(err: unknown): unknown {\n if (err === null || typeof err !== 'object') {\n return err;\n }\n const candidate = err as { response?: unknown };\n if (candidate.response === null || typeof candidate.response !== 'object') {\n return err;\n }\n const response = candidate.response as { headers?: unknown };\n if (response.headers === null || typeof response.headers !== 'object') {\n return err;\n }\n\n const sanitizedHeaders: Record<string, unknown> = { ...(response.headers as Record<string, unknown>) };\n for (const key of Object.keys(sanitizedHeaders)) {\n if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {\n sanitizedHeaders[key] = REDACTED_HEADER;\n }\n }\n\n return {\n ...err,\n response: {\n ...response,\n headers: sanitizedHeaders,\n },\n };\n}\n\n/**\n * Map an HTTP status code to an AxiamError variant per CONTRACT.md §2's HTTP\n * status table.\n *\n * | Status | Type |\n * |-----------|--------------|\n * | 400 | NetworkError |\n * | 401 | AuthError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * NetworkError's `cause` (when provided via `ctx.cause`) is always passed\n * through `sanitizeAxiosError` first (CR-04) — this is the single choke\n * point for both rest/ auth call sites and any future caller.\n *\n * For 403/409, `action`/`resourceId` are sourced from the response body\n * (`ctx.body`) when the body carries them, falling back to the\n * caller-supplied `ctx.action`/`ctx.resourceId` (the request call-args)\n * otherwise — this keeps compatibility with older servers that don't yet\n * echo `action`/`resource_id` in the denial body.\n */\nexport function mapHttpStatusToError(\n status: number,\n message: string,\n ctx?: HttpErrorContext,\n): AxiamError {\n if (status === 401) {\n return new AuthError(message);\n }\n if (status === 403 || status === 409) {\n const fromBody = extractAuthzFieldsFromBody(ctx?.body);\n return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);\n }\n // 400, 408, 429, 5xx, and any other status fall through to NetworkError.\n return new NetworkError(message, sanitizeAxiosError(ctx?.cause));\n}\n\n/**\n * Map a gRPC status code to an AxiamError variant per CONTRACT.md §2's gRPC\n * status table.\n *\n * | Code | Type |\n * |------------------------|--------------|\n * | 16 UNAUTHENTICATED | AuthError |\n * | 7 PERMISSION_DENIED | AuthzError |\n * | 14 UNAVAILABLE | NetworkError |\n * | 4 DEADLINE_EXCEEDED | NetworkError |\n * | 13 INTERNAL | NetworkError |\n * | 8 RESOURCE_EXHAUSTED | NetworkError |\n * | other | NetworkError |\n */\nexport function mapGrpcStatusToError(code: number, message: string): AxiamError {\n if (code === GrpcStatus.UNAUTHENTICATED) {\n return new AuthError(message);\n }\n if (code === GrpcStatus.PERMISSION_DENIED) {\n return new AuthzError(message);\n }\n return new NetworkError(message);\n}\n","// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\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","// CSRF double-submit helpers (CONTRACT.md §3, D-05/D-28).\n//\n// The AXIAM server's CSRF middleware validates X-CSRF-Token against the\n// axiam_csrf cookie value directly (cookie double-submit). The regex is\n// deliberately hardcoded (not built dynamically from a configurable cookie\n// name) to avoid ReDoS/CWE-1333 — mirrors frontend/src/lib/api.ts exactly.\n\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\nexport const CSRF_HEADER = 'X-CSRF-Token';\nexport const CSRF_METHODS: ReadonlySet<string> = new Set(['post', 'put', 'patch', 'delete']);\n\nconst CSRF_COOKIE_REGEX = /(?:^|;\\s*)axiam_csrf=([^;]*)/;\n\n/** Extract the axiam_csrf cookie value from a `document.cookie`-shaped string, or null if absent. */\nexport function readCsrfCookie(cookieString: string): string | null {\n const match = CSRF_COOKIE_REGEX.exec(cookieString);\n if (!match) {\n return null;\n }\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Returns the CSRF header value for a state-changing HTTP method\n * (post/put/patch/delete, case-insensitive), or undefined for safe methods\n * (get/head/options) or when no CSRF cookie is present yet.\n */\nexport function csrfHeaderForMethod(method: string, cookieString: string): string | undefined {\n if (!CSRF_METHODS.has(method.toLowerCase())) {\n return undefined;\n }\n const token = readCsrfCookie(cookieString);\n return token ?? undefined;\n}\n","// Single-flight refresh guard (CONTRACT.md §9, D-07/D-13).\n//\n// Per-session-scoped shared-Promise guard (CR-02 gap closure, 17-VERIFICATION.md):\n// createRefreshGuard() returns a fresh, independent refreshOnce closure per\n// call, each closing over its OWN private refreshPromise. Concurrent callers\n// against the SAME guard instance share the same in-flight Promise; the\n// guard clears on settle (success or failure) so a later expiry can trigger\n// a fresh refresh — this is the exactly-one-in-flight-at-a-time semantics §9\n// requires, not a permanent single-refresh-ever lock. Distinct guard\n// instances (one per SharedSession/NodeSession, D-13) never share state, so\n// a refresh on session A can never silently satisfy a concurrent refresh on\n// session B.\n\n/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */\nexport type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;\n\n/** Test-only reset hook type, attached to each guard closure via `Object.assign`. @internal */\ninterface ResettableRefreshGuard {\n (doRefresh: () => Promise<void>): Promise<void>;\n __reset(): void;\n}\n\n/**\n * Build a fresh, independent single-flight refresh guard. Each call returns\n * its own closure with a private `refreshPromise` — instantiate one per\n * `SharedSession`/`NodeSession` (D-13) so refresh guards never cross-wire\n * between independent client instances (CR-02).\n */\nexport function createRefreshGuard(): RefreshGuard {\n let refreshPromise: Promise<void> | null = null;\n\n const guard = ((doRefresh: () => Promise<void>): Promise<void> => {\n if (!refreshPromise) {\n refreshPromise = doRefresh().finally(() => {\n refreshPromise = null;\n });\n }\n return refreshPromise;\n }) as ResettableRefreshGuard;\n\n guard.__reset = () => {\n refreshPromise = null;\n };\n\n return guard;\n}\n\n// Backward-compatible module-level default guard instance, retained for\n// test/core/singleFlightRefresh.test.ts and any caller still importing the\n// bare `refreshOnce`/`resetRefreshGuard` module-level functions. New\n// wiring (rest/interceptors.ts, grpc/callWithRefresh.ts) MUST use a\n// per-session guard from `createRefreshGuard()` instead (see\n// SharedSession.refreshGuard).\nconst defaultGuard = createRefreshGuard() as ResettableRefreshGuard;\n\n/**\n * Ensures at most one `doRefresh()` call is in flight at a time, backed by\n * the single module-level default guard instance. Concurrent callers share\n * the same in-flight Promise; after it settles, a subsequent call invokes\n * `doRefresh` again.\n *\n * @deprecated for new wiring — use a per-instance guard from\n * `createRefreshGuard()` instead (D-13/CR-02). Retained for backward\n * compatibility.\n */\nexport function refreshOnce(doRefresh: () => Promise<void>): Promise<void> {\n return defaultGuard(doRefresh);\n}\n\n/** Test-only helper to reset the module-level default guard between test cases. @internal */\nexport function resetRefreshGuard(): void {\n defaultGuard.__reset();\n}\n","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n","// UNAUTHENTICATED single-flight-retry wrapper (D-10/D-13, CONTRACT.md §9).\n//\n// The interceptor (interceptor.ts) is synchronous and never triggers a\n// refresh (Pitfall 3). This ASYNC call-site wrapper is where\n// UNAUTHENTICATED handling actually lives: on a caught error whose\n// `.code === GrpcStatus.UNAUTHENTICATED`, it awaits the session's\n// per-instance single-flight refresh guard (`session.refreshGuard` — the\n// SAME guard instance the REST transport for this session uses, D-13, but\n// NEVER shared with a different session, CR-02), resyncs the interceptor's\n// cached-token fast-path via `syncFromJar()`, then retries the call exactly\n// once. A second UNAUTHENTICATED (or any other error) maps through\n// `mapGrpcStatusToError` and rethrows — no further retry (§9.3).\n\nimport { GrpcStatus, mapGrpcStatusToError, type AxiamError } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\n\ninterface GrpcServiceErrorLike {\n code?: number;\n message?: string;\n}\n\nfunction isGrpcServiceError(err: unknown): err is GrpcServiceErrorLike {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n/**\n * Await `fn()`. On a gRPC UNAUTHENTICATED (16) error, drive the shared\n * single-flight refresh, sync the token cache from the jar, and retry `fn()`\n * exactly once. Any other error (or a second UNAUTHENTICATED) is mapped to\n * an AxiamError via `mapGrpcStatusToError` and rethrown.\n */\nexport async function callWithRefresh<T>(session: NodeSession, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (isGrpcServiceError(err) && err.code === GrpcStatus.UNAUTHENTICATED) {\n await session.refreshGuard(session.doRefresh);\n await session.tokenManager.syncFromJar();\n try {\n return await fn();\n } catch (retryErr) {\n throw toAxiamError(retryErr);\n }\n }\n throw toAxiamError(err);\n }\n}\n\nfunction toAxiamError(err: unknown): AxiamError | unknown {\n if (isGrpcServiceError(err) && typeof err.code === 'number') {\n return mapGrpcStatusToError(err.code, err.message ?? 'gRPC call failed');\n }\n return err;\n}\n","// gRPC AuthorizationService client — reused channel, checkAccess/batchCheck\n// (D-10/D-13, SC#2 Node half).\n//\n// The generated ts-proto stubs (`src/gen`, produced by `buf generate` at\n// build time — Phase 15 D-01/D-20) are NOT committed and are unavailable in\n// this sandbox (no `buf` CLI). Rather than importing from a path that does\n// not exist here, this module (a) defines local wire-shape interfaces that\n// exactly mirror `proto/axiam/v1/authorization.proto`, and (b) builds the\n// gRPC client dynamically via grpc-js's own `makeClientConstructor` (the\n// same primitive ts-proto's `outputServices=grpc-js` stubs are built on top\n// of) rather than importing a generated class. A buf-enabled build can swap\n// `buildAuthorizationServiceClient` below for the real ts-proto-generated\n// `AuthorizationServiceClient` from `../gen/...` with NO change to the\n// public `AuthzGrpcClient` surface, since both satisfy the same\n// `WireAuthorizationServiceClient` shape by construction (same .proto).\n// End-to-end wiring against real generated stubs is deferred to a\n// buf-enabled CI run (RESEARCH.md D-20; environment note in this plan).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { AccessDecision } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\nimport { authInterceptor } from './interceptor.js';\nimport { callWithRefresh } from './callWithRefresh.js';\n\n// Re-exported (not re-declared) so `grpc/index.ts` can still export\n// `AccessDecision` from `./client.js` — see `core/authz.ts` for the single\n// shared definition (SDK-Q10, C2).\nexport type { AccessDecision };\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/authorization.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\nexport interface WireCheckAccessRequest {\n tenant_id: string;\n // `subject_id` is a required (non-`optional`) proto3 field\n // (`proto/axiam/v1/authorization.proto`), unlike `scope` below — the wire\n // contract always carries it, so it stays required here too rather than\n // relaxed to match REST's optional `subjectId` (see `CheckAccessRequest`\n // below for why the two transports differ).\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n}\n\nexport interface WireCheckAccessResponse {\n allowed: boolean;\n deny_reason: string;\n}\n\nexport interface WireBatchCheckAccessRequest {\n requests: WireCheckAccessRequest[];\n}\n\nexport interface WireBatchCheckAccessResponse {\n results: WireCheckAccessResponse[];\n}\n\ntype UnaryCallback<T> = (error: grpc.ServiceError | null, response?: T) => void;\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `AuthorizationServiceClient` this module needs. The real generated client\n * satisfies this shape exactly (unary Node-callback methods), so a\n * buf-enabled build's generated client is a drop-in replacement here.\n */\nexport interface WireAuthorizationServiceClient {\n checkAccess(\n request: WireCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n batchCheckAccess(\n request: WireBatchCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireBatchCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * Public (camelCase, §1) single access-check request shape.\n *\n * `subjectId` is required here (unlike REST's optional `AccessCheck.subjectId`)\n * because gRPC calls typically originate from a service-mesh caller with no\n * request-scoped JWT to derive a subject from — the caller must pass it\n * explicitly. REST, by contrast, derives the subject from the caller's JWT\n * when `subjectId` is omitted (§5). This mirrors the proto's non-`optional`\n * `subject_id` field (`proto/axiam/v1/authorization.proto`), which is not\n * changed here (SDK-Q10, C2).\n */\nexport interface CheckAccessRequest {\n tenantId: string;\n subjectId: string;\n action: string;\n resourceId: string;\n scope?: string;\n}\n\nfunction toWireRequest(req: CheckAccessRequest): WireCheckAccessRequest {\n return {\n tenant_id: req.tenantId,\n subject_id: req.subjectId,\n action: req.action,\n resource_id: req.resourceId,\n scope: req.scope,\n };\n}\n\nfunction fromWireResponse(resp: WireCheckAccessResponse): AccessDecision {\n return {\n allowed: resp.allowed,\n reason: resp.deny_reason ? resp.deny_reason : undefined,\n };\n}\n\nfunction promisifyUnary<TReq, TResp>(\n call: (req: TReq, metadata: grpc.Metadata, callback: UnaryCallback<TResp>) => grpc.ClientUnaryCall,\n request: TReq,\n): Promise<TResp> {\n return new Promise((resolve, reject) => {\n call(request, new grpc.Metadata(), (error, response) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(response as TResp);\n });\n });\n}\n\n/**\n * Build the gRPC channel credentials for `baseUrl` (§6 — TLS is always\n * strict by default; `customCa` is the ONLY certificate escape hatch, never\n * an insecure/skip-verification surface).\n *\n * A plaintext target (`http://`/`grpc://`) is REFUSED by default (X-2): it\n * would silently drop the channel to `createInsecure()`, sending bearer tokens\n * and tenant metadata in cleartext. Callers who genuinely need a local dev\n * plaintext channel must opt in explicitly with `allowInsecure: true`, which\n * emits a `console.warn`. As a convenience the opt-in is required for ANY host\n * (including loopback) — there is no silent path to an insecure channel.\n */\nfunction buildCredentials(\n baseUrl: string,\n customCa: string | undefined,\n allowInsecure: boolean,\n): grpc.ChannelCredentials {\n const isSecure = baseUrl.startsWith('https://') || baseUrl.startsWith('grpcs://');\n if (!isSecure) {\n if (!allowInsecure) {\n throw new Error(\n `AXIAM gRPC refuses to open an insecure (plaintext) channel to \"${baseUrl}\": ` +\n 'bearer tokens and tenant metadata would be sent in cleartext. Use an ' +\n 'https:// or grpcs:// target, or pass { allowInsecure: true } to opt in ' +\n 'explicitly for a trusted local/dev channel (CONTRACT.md §6).',\n );\n }\n // Explicit opt-in only — never reached without allowInsecure.\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM gRPC: opening an INSECURE (plaintext) channel to \"${baseUrl}\" because ` +\n 'allowInsecure was set. Bearer tokens and tenant metadata are transmitted in ' +\n 'cleartext — never use this outside a trusted local/dev environment.',\n );\n return grpc.ChannelCredentials.createInsecure();\n }\n if (customCa) {\n return grpc.ChannelCredentials.createSsl(Buffer.from(customCa, 'utf8'));\n }\n // Default: verify against the platform's native trust store.\n return grpc.ChannelCredentials.createSsl();\n}\n\nfunction grpcTarget(baseUrl: string): string {\n const url = new URL(baseUrl);\n return url.port ? `${url.hostname}:${url.port}` : url.hostname;\n}\n\nconst jsonCodec = <T>() => ({\n serialize: (value: T): Buffer => Buffer.from(JSON.stringify(value)),\n deserialize: (bytes: Buffer): T => JSON.parse(bytes.toString('utf8')) as T,\n});\n\n/**\n * Construct a real `AuthorizationServiceClient` over grpc-js's own\n * `makeClientConstructor` primitive (the same primitive ts-proto's\n * `outputServices=grpc-js` codegen target uses under the hood). This\n * transport-level client encodes/decodes with JSON as a build-independent\n * stand-in for the protobuf binary codec a buf-enabled build's generated\n * serializers would use — swap this factory for the generated\n * `AuthorizationServiceClient` once `src/gen` exists (D-20).\n */\nexport function buildAuthorizationServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireAuthorizationServiceClient {\n const checkAccessCodec = jsonCodec<WireCheckAccessRequest>();\n const checkAccessRespCodec = jsonCodec<WireCheckAccessResponse>();\n const batchCodec = jsonCodec<WireBatchCheckAccessRequest>();\n const batchRespCodec = jsonCodec<WireBatchCheckAccessResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n checkAccess: {\n path: '/axiam.v1.AuthorizationService/CheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: checkAccessCodec.serialize,\n requestDeserialize: checkAccessCodec.deserialize,\n responseSerialize: checkAccessRespCodec.serialize,\n responseDeserialize: checkAccessRespCodec.deserialize,\n },\n batchCheckAccess: {\n path: '/axiam.v1.AuthorizationService/BatchCheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: batchCodec.serialize,\n requestDeserialize: batchCodec.deserialize,\n responseSerialize: batchRespCodec.serialize,\n responseDeserialize: batchRespCodec.deserialize,\n },\n },\n 'axiam.v1.AuthorizationService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireAuthorizationServiceClient;\n}\n\nexport type AuthorizationServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireAuthorizationServiceClient;\n\n/**\n * gRPC transport for `AuthorizationService` (`checkAccess`/`batchCheck`,\n * SC#2 Node half), reusing one long-lived client/channel per instance (D-10\n * — never reconstructed per-call) and injecting auth + tenant metadata via\n * the synchronous interceptor on every RPC.\n */\nexport class AuthzGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireAuthorizationServiceClient;\n\n constructor(\n session: NodeSession,\n options: { baseUrl: string; customCa?: string; allowInsecure?: boolean },\n clientFactory: AuthorizationServiceClientFactory = buildAuthorizationServiceClient,\n ) {\n this.#session = session;\n const credentials = buildCredentials(options.baseUrl, options.customCa, options.allowInsecure ?? false);\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */\n async checkAccess(request: CheckAccessRequest): Promise<AccessDecision> {\n const wireRequest = toWireRequest(request);\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.checkAccess.bind(this.#inner), wireRequest),\n );\n return fromWireResponse(response);\n }\n\n /** `BatchCheckAccess` over gRPC — results preserve input order (§1). */\n async batchCheck(requests: CheckAccessRequest[]): Promise<AccessDecision[]> {\n const wireRequest: WireBatchCheckAccessRequest = { requests: requests.map(toWireRequest) };\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.batchCheckAccess.bind(this.#inner), wireRequest),\n );\n return response.results.map(fromWireResponse);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n","// SharedSession — the object other transports (Node persona 17-03, middleware\n// 17-05) attach gRPC/JWKS/middleware state to (D-13).\n//\n// Holds: the axios instance, the tenant header value (computed once at\n// construction), a mutable csrfToken store, the base URL, and a per-instance\n// single-flight refresh guard (CR-02: NOT the module-level default guard —\n// each SharedSession gets its own via createRefreshGuard(), so two\n// independent AxiamClient/NodeSession instances never cross-wire refreshes).\n// One login() drives all transports for a given session.\n\nimport axios, { type AxiosInstance } from 'axios';\nimport type { AxiamClientOptions, RefreshGuard } from '../core/index.js';\nimport { createRefreshGuard, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS } from '../core/index.js';\n\nconst PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * The single session object every AXIAM transport (REST here, gRPC/AMQP in\n * 17-03/17-04, middleware in 17-05) attaches to. Constructed once per\n * `AxiamClient` instance.\n */\nexport class SharedSession {\n /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */\n readonly axios: AxiosInstance;\n /** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */\n readonly baseUrl: string;\n /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */\n readonly tenantHeaderValue: string;\n /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */\n csrfToken: string | undefined;\n /** Set true once a successful login/verifyMfa has completed. */\n authenticated = false;\n /**\n * Per-instance single-flight refresh guard (CR-02, D-13). Shared across\n * this session's REST and gRPC transports (rest/interceptors.ts,\n * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but\n * NEVER shared with a different SharedSession/NodeSession instance.\n *\n * @internal SDK-internal transport wiring, not intended to be invoked\n * directly by SDK consumers — refreshes are driven automatically by the\n * response interceptor (rest) or `callWithRefresh` (grpc).\n */\n readonly refreshGuard: RefreshGuard;\n\n constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string) {\n this.axios = axiosInstance;\n this.baseUrl = options.baseUrl;\n this.tenantHeaderValue = tenantHeaderValue;\n this.refreshGuard = createRefreshGuard();\n }\n\n /**\n * Optional session-level hook invoked by rest/auth.ts after a successful\n * login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser\n * persona) does not implement it — the browser reads document.cookie\n * directly on every request and has no jar to sync from. NodeSession\n * overrides this to populate `csrfToken` from its cookie jar and refresh\n * the cached access token.\n */\n onAuthenticated?(): Promise<void>;\n\n /**\n * Host-isolation guard (3A, defense in depth): returns `true` when `url`\n * targets a host other than this session's base origin — an absolute\n * third-party URL, or a redirect that axios/the browser resolved off-origin.\n * The tenant identifier and CSRF token must never be attached to such a\n * request. A relative/host-less `url` (the normal case, merged against\n * `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's\n * `_prepare_request` guard. Malformed input fails closed (treated as\n * foreign).\n */\n isForeignHost(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n const target = new URL(url, this.baseUrl);\n return target.host !== new URL(this.baseUrl).host;\n } catch {\n return true;\n }\n }\n}\n\n/**\n * Resolve the required tenant header value from options (§5). Throws if\n * neither tenantSlug nor tenantId is provided — there is no default tenant.\n */\nexport function resolveTenantHeaderValue(options: AxiamClientOptions): string {\n if (options.tenantSlug) {\n return options.tenantSlug;\n }\n if (options.tenantId) {\n return options.tenantId;\n }\n throw new Error(\n 'AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md §5).',\n );\n}\n\n/**\n * Build the Node-only `https.Agent` for a customCa PEM. Guarded by\n * `typeof process !== 'undefined'` as a CAPABILITY guard (Node has\n * node:https available), NOT a persona-sniffing branch — browsers ignore\n * customCa entirely since the platform manages TLS verification itself.\n */\nfunction maybeBuildHttpsAgent(customCa: string | undefined): unknown {\n if (!customCa) {\n return undefined;\n }\n if (!customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n if (typeof process === 'undefined') {\n // Browser: platform manages TLS; customCa has no effect there.\n return undefined;\n }\n // Node capability guard — require lazily so this branch never executes\n // (and never needs to resolve) in a browser bundle.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const https = require('node:https') as typeof import('node:https');\n return new https.Agent({ ca: customCa });\n}\n\n/** Build the axios instance + SharedSession for an AxiamClient (D-13/D-25). */\nexport function createSession(options: AxiamClientOptions): SharedSession {\n const tenantHeaderValue = resolveTenantHeaderValue(options);\n\n // customCa is validated (PEM-shape) even when running in an environment\n // that will end up ignoring it (browser), so construction fails fast and\n // consistently across personas (§6).\n if (options.customCa !== undefined && !options.customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa);\n\n const axiosInstance = axios.create({\n baseURL: options.baseUrl,\n withCredentials: true,\n timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n ...(httpsAgent ? { httpsAgent } : {}),\n });\n\n const session = new SharedSession(options, axiosInstance, tenantHeaderValue);\n\n // Attach X-Tenant-ID to every outgoing request (§5.2) — except when the\n // request targets a host other than our own origin (host-isolation, 3A).\n axiosInstance.interceptors.request.use((config) => {\n if (session.isForeignHost(config.url)) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['X-Tenant-ID'] = session.tenantHeaderValue;\n return config;\n });\n\n return session;\n}\n","// Axios interceptors: CSRF forwarding (D-05, §3) + reactive single-flight\n// 401->refresh (D-07, §9). Mirrors frontend/src/lib/api.ts's proven pattern,\n// generalized off the app store: this is a library, not an app — refresh\n// failure clears session auth state and rejects; it never redirects\n// (no window.location access anywhere in this module).\n\nimport type { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport { csrfHeaderForMethod, mapHttpStatusToError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Endpoints that must never trigger a silent refresh, to avoid infinite\n * refresh loops (§9.3): the refresh endpoint itself, plus login/logout which\n * are not authenticated-session-continuation calls.\n */\nexport const SKIP_REFRESH = ['/api/v1/auth/refresh', '/api/v1/auth/login', '/api/v1/auth/logout'];\n\ntype RetryableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean };\n\n/**\n * Request interceptor: forwards the axiam_csrf cookie as X-CSRF-Token on\n * state-changing methods (POST/PUT/PATCH/DELETE) per §3/D-05.\n *\n * Browser: reads `document.cookie` directly (guarded by `typeof document !==\n * 'undefined'`). Node: reads the session's csrfToken store, populated by the\n * Node persona's cookie-jar read (17-03) — left undefined here since no jar\n * exists in the browser-only REST core built by this plan.\n */\nexport function installCsrfInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {\n // Host-isolation (3A): never echo the CSRF token to an off-origin host.\n if (session.isForeignHost(config.url)) {\n return config;\n }\n const method = (config.method ?? 'get').toLowerCase();\n const cookieString = typeof document !== 'undefined' ? document.cookie : '';\n const csrfToken =\n typeof document !== 'undefined' ? csrfHeaderForMethod(method, cookieString) : csrfHeaderForMethod(method, session.csrfToken ? `axiam_csrf=${session.csrfToken}` : '');\n\n if (csrfToken) {\n config.headers = config.headers ?? {};\n config.headers['X-CSRF-Token'] = csrfToken;\n }\n return config;\n });\n}\n\n/**\n * Response interceptor: on 401 (when authenticated, not a SKIP_REFRESH url,\n * not already retried) performs a reactive single-flight refresh and replays\n * the original request (D-07/§9). Non-2xx responses are mapped through\n * core's mapHttpStatusToError.\n */\nexport function installRefreshInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.response.use(\n (response) => response,\n async (error: AxiosError) => {\n const originalRequest = error.config as RetryableRequestConfig | undefined;\n\n if (!originalRequest || !error.response) {\n // No response at all (network/timeout) — surface as NetworkError below via caller mapping.\n return Promise.reject(error);\n }\n\n const status = error.response.status;\n const url = originalRequest.url ?? '';\n const isSkipRefresh = SKIP_REFRESH.some((skipUrl) => url.includes(skipUrl));\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated) {\n // CQ-F32: set _retry BEFORE the refresh call so a 401 on the replayed\n // request cannot trigger a second refresh cycle.\n originalRequest._retry = true;\n\n try {\n await session.refreshGuard(async () => {\n await session.axios.post('/api/v1/auth/refresh', {});\n });\n return axiosInstance(originalRequest);\n } catch (refreshError) {\n session.authenticated = false;\n session.csrfToken = undefined;\n return Promise.reject(\n mapHttpStatusToError(401, 'session refresh failed; re-authentication required', {\n cause: refreshError,\n }),\n );\n }\n }\n\n if (status === 401 && isSkipRefresh) {\n return Promise.reject(mapHttpStatusToError(401, 'authentication failed'));\n }\n\n return Promise.reject(error);\n },\n );\n}\n\n/** Install both the CSRF and reactive single-flight refresh interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n}\n","// login/verifyMfa/refresh/logout over REST (D-18, §1).\n//\n// Mirrors the Rust SDK's src/rest/auth.rs's request/response shapes exactly\n// (mirror only, no server crate dependency). Tokens are delivered\n// exclusively via Set-Cookie — LoginResult deliberately carries no session\n// token field anywhere in the public API (T-17-07).\n\nimport { mapHttpStatusToError, NetworkError, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n RefreshSuccessResponseWire,\n} from './types.js';\n\nconst LOGIN_PATH = '/api/v1/auth/login';\nconst MFA_VERIFY_PATH = '/api/v1/auth/mfa/verify';\nconst REFRESH_PATH = '/api/v1/auth/refresh';\nconst LOGOUT_PATH = '/api/v1/auth/logout';\n\ninterface LoginRequestBody {\n username_or_email: string;\n password: string;\n}\n\ninterface MfaVerifyRequestBody {\n challenge_token: string;\n totp_code: string;\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire): LoginResult {\n return {\n status: 'authenticated',\n user: { id: wire.user.id, username: wire.user.username, email: wire.user.email },\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\nfunction mfaRequiredToResult(wire: MfaRequiredResponseWire): LoginResult {\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n}\n\nfunction extractErrorMessage(err: unknown): string {\n if (err && typeof err === 'object' && 'message' in err && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message;\n }\n return 'request failed';\n}\n\n/**\n * `POST /api/v1/auth/login` (§1).\n *\n * On a 200 response returns the authenticated branch of the LoginResult\n * discriminated union; on the MFA-required response (202) returns the\n * mfa_required branch (mfaToken sourced from the wire challenge_token).\n */\nexport async function login(client: AxiamClient, email: string, password: string): Promise<LoginResult> {\n const body: LoginRequestBody = { username_or_email: email, password };\n\n try {\n // axios treats any 2xx (including 202 MFA-required) as a resolved\n // response, not a thrown error — branch on the actual status here.\n const response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n LOGIN_PATH,\n body,\n );\n if (response.status === 202) {\n return mfaRequiredToResult(response.data as MfaRequiredResponseWire);\n }\n client.session.authenticated = true;\n // CR-01/D-05: sync the Node persona's csrfToken (and cached access token)\n // from the jar now that the session cookie(s) have landed. No-op for the\n // browser SharedSession, which has no onAuthenticated implementation.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data as LoginSuccessResponseWire);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'login failed', {\n cause: err,\n });\n }\n throw new NetworkError('login request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/mfa/verify` (§1).\n *\n * Completes the two-phase flow started by login() when status was\n * 'mfa_required', using the caller-supplied mfaToken (the challenge token\n * returned from that prior login() call).\n */\nexport async function verifyMfa(client: AxiamClient, mfaToken: string, code: string): Promise<LoginResult> {\n const body: MfaVerifyRequestBody = { challenge_token: mfaToken, totp_code: code };\n\n try {\n const response = await client.session.axios.post<LoginSuccessResponseWire>(MFA_VERIFY_PATH, body);\n client.session.authenticated = true;\n // CR-01/D-05: same post-authentication sync as login()'s 200 branch.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'verifyMfa failed', {\n cause: err,\n });\n }\n throw new NetworkError('verifyMfa request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/refresh` (§1).\n *\n * Callers typically do not invoke this directly — the response interceptor\n * (interceptors.ts) drives it reactively via the single-flight guard on a\n * 401 (D-07). Exposed as a public method for explicit proactive refresh.\n */\nexport async function refresh(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n // §9.3: 401 on the refresh call itself is AuthError, no retry loop.\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'refresh failed', {\n cause: err,\n });\n }\n throw new NetworkError('refresh request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/logout` (§1).\n *\n * Clears session csrf/auth state regardless of the response outcome once\n * the request has been sent successfully.\n */\nexport async function logout(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post(LOGOUT_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'logout failed', {\n cause: err,\n });\n }\n throw new NetworkError('logout request failed', sanitizeAxiosError(err));\n } finally {\n client.session.authenticated = false;\n client.session.csrfToken = undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// axios error helpers (kept local — core stays dependency-free of axios)\n// ---------------------------------------------------------------------------\n\nfunction extractAxiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number } }).response;\n return response?.status;\n }\n return undefined;\n}\n\nfunction extractAxiosData<T>(err: unknown): T | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { data?: T } }).response;\n return response?.data;\n }\n return undefined;\n}\n","// checkAccess/can/batchCheck over REST (D-08, FND-04, §1).\n//\n// Mirrors the Rust SDK's src/rest/authz.rs and\n// crates/axiam-api-rest/src/handlers/authz_check.rs exactly. tenant_id is\n// never sent in the body — the server derives it from the JWT (§5); the SDK\n// only sends X-Tenant-ID (already attached by session.ts's request\n// interceptor on every call). No client-side cache (D-08) — plain stateless\n// async functions.\n\nimport { mapHttpStatusToError, NetworkError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n AccessCheck,\n AccessDecision,\n BatchCheckAccessBodyWire,\n BatchCheckAccessResponseWire,\n CheckAccessBodyWire,\n CheckAccessResponseWire,\n} from './types.js';\n\nconst CHECK_PATH = '/api/v1/authz/check';\nconst BATCH_CHECK_PATH = '/api/v1/authz/check/batch';\n\nfunction toWireBody(check: AccessCheck): CheckAccessBodyWire {\n return {\n action: check.action,\n resource_id: check.resourceId,\n scope: check.scope,\n subject_id: check.subjectId,\n };\n}\n\nfunction fromWireDecision(wire: CheckAccessResponseWire): AccessDecision {\n return { allowed: wire.allowed, reason: wire.reason };\n}\n\n/**\n * `POST /api/v1/authz/check` (§1, FND-04).\n *\n * A 403 authz denial (server-side error, distinct from the `allowed: false`\n * decision the endpoint itself returns) is mapped to AuthzError, not treated\n * as a transport failure.\n */\nexport async function checkAccess(client: AxiamClient, check: AccessCheck): Promise<AccessDecision> {\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n return fromWireDecision(response.data);\n } catch (err) {\n throw mapAuthzError(err, check.action, check.resourceId);\n }\n}\n\n/**\n * `can` — alias for checkAccess targeting browser/UI scenarios (§1 note),\n * returning just the boolean `allowed` outcome.\n */\nexport async function can(client: AxiamClient, action: string, resourceId: string, scope?: string): Promise<boolean> {\n const decision = await checkAccess(client, { action, resourceId, scope });\n return decision.allowed;\n}\n\n/**\n * `POST /api/v1/authz/check/batch` (§1). Results are returned in the same\n * order as the input `checks` array (server-guaranteed ordering).\n */\nexport async function batchCheck(client: AxiamClient, checks: AccessCheck[]): Promise<AccessDecision[]> {\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n throw mapAuthzError(err);\n }\n}\n\nfunction mapAuthzError(err: unknown, action?: string, resourceId?: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: { message?: string } } }).response;\n if (response?.status !== undefined) {\n if (response.status === 403) {\n // Body (response.data) carries the server's own action/resource_id\n // for the denial (structured 403 body) — preferred by the mapper\n // over the call-args action/resourceId below when present.\n return mapHttpStatusToError(403, response.data?.message ?? 'authorization denied', {\n action,\n resourceId,\n body: response.data,\n });\n }\n return mapHttpStatusToError(response.status, response.data?.message ?? 'authz request failed', {\n action,\n resourceId,\n body: response.data,\n cause: err,\n });\n }\n }\n return new NetworkError('authz request failed', err);\n}\n","// AxiamClient — the isomorphic REST + auth core (D-01/D-25).\n//\n// Constructor validates the required tenant (§5), builds the SharedSession\n// (D-13), and installs the CSRF + reactive single-flight refresh\n// interceptors (D-05/D-07). REST method implementations (login/verifyMfa/\n// refresh/logout/checkAccess/can/batchCheck) are added by Task 2's\n// auth.ts/authz.ts, which extend this class's prototype.\n\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as authzMethods from './authz.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\n\n/**\n * The main entry point for the AXIAM TypeScript/JavaScript SDK — an\n * isomorphic (browser + Node) REST client for authentication and\n * authorization against an AXIAM server.\n *\n * @remarks\n * `AxiamClient` implements the SDK's cross-language behavioral contract\n * (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/\n * `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the\n * three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic\n * CSRF forwarding (§3), the required tenant context (§5), and a per-instance\n * single-flight refresh guard that de-duplicates concurrent token refreshes\n * (§9).\n *\n * A `tenantSlug` or `tenantId` is mandatory at construction — there is no\n * default tenant, and AXIAM is a multi-tenant system where every\n * authenticated call is scoped by the `X-Tenant-ID` header this client\n * injects on every request (§5). Session tokens never appear as a return\n * value or public property anywhere on this class: they arrive exclusively\n * via `httpOnly` cookies set by the server.\n *\n * @example\n * ```ts\n * const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });\n *\n * const result = await client.login('user@example.com', 'hunter2');\n * if (result.status === 'mfa_required') {\n * await client.verifyMfa(result.mfaToken, '123456');\n * }\n *\n * const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });\n * if (!decision.allowed) {\n * throw new Error(decision.reason ?? 'access denied');\n * }\n * ```\n */\nexport class AxiamClient {\n /** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */\n readonly session: SharedSession;\n\n /**\n * @param options client configuration (§5/§6).\n * @param session optional pre-built session to adopt instead of the default\n * browser `SharedSession`. This is the injection point for the Node\n * persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie\n * jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`\n * from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it\n * is adopted here, so httpOnly login/refresh cookies persist. When omitted\n * the browser `SharedSession` is built by default — the Node modules are\n * NEVER statically imported from this browser-safe module, so a `/rest`\n * browser bundle keeps pulling zero Node dependencies (SC#1).\n */\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n }\n\n /** `POST /api/v1/auth/login` (§1, D-18). */\n login(email: string, password: string): Promise<LoginResult> {\n return authMethods.login(this, email, password);\n }\n\n /** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */\n verifyMfa(mfaToken: string, code: string): Promise<LoginResult> {\n return authMethods.verifyMfa(this, mfaToken, code);\n }\n\n /** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */\n refresh(): Promise<void> {\n return authMethods.refresh(this);\n }\n\n /** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */\n logout(): Promise<void> {\n return authMethods.logout(this);\n }\n\n /** `POST /api/v1/authz/check` (§1, FND-04). */\n checkAccess(check: AccessCheck): Promise<AccessDecision> {\n return authzMethods.checkAccess(this, check);\n }\n\n /** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */\n can(action: string, resourceId: string, scope?: string): Promise<boolean> {\n return authzMethods.can(this, action, resourceId, scope);\n }\n\n /** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */\n batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]> {\n return authzMethods.batchCheck(this, checks);\n }\n}\n","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { wrapper } from 'axios-cookiejar-support';\nimport type { AxiosInstance } from 'axios';\n\n/** The `axiam_access` cookie name (httpOnly, path `/`). */\nexport const ACCESS_COOKIE = 'axiam_access';\n/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */\nexport const REFRESH_COOKIE = 'axiam_refresh';\n/** The `axiam_csrf` cookie name (JS-readable, path `/`). */\nexport const CSRF_COOKIE = 'axiam_csrf';\n\n/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */\nexport function createJar(): CookieJar {\n return new CookieJar();\n}\n\n/**\n * Wrap an axios instance with `axios-cookiejar-support` so the jar persists\n * `Set-Cookie` responses across requests and replays them on subsequent\n * requests to the same origin/path (§4). Mutates and returns the same\n * instance (matches `axios-cookiejar-support`'s documented in-place wrap).\n */\nexport function wrapAxios(instance: AxiosInstance, jar: CookieJar): AxiosInstance {\n const wrapped = wrapper(instance);\n wrapped.defaults.jar = jar;\n return wrapped;\n}\n\n/**\n * Read a single cookie's value out of the jar by name, for the given URL.\n * This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body\n * fallback exists on the wire).\n */\nexport async function extractCookieValue(\n jar: CookieJar,\n url: string,\n name: string,\n): Promise<string | undefined> {\n const cookies = await jar.getCookies(url);\n return cookies.find((c) => c.key === name)?.value;\n}\n","// TokenManager — Node-persona token state (CONTRACT.md §7, D-09/D-11/D-26).\n//\n// Tokens are read from the tough-cookie jar by name (the ONLY token-source\n// path — login/refresh response bodies carry no token fields; see\n// RESEARCH.md Area 3) and wrapped in Sensitive<T> immediately. A\n// synchronous, non-blocking `cachedAccessToken()` fast-path is provided for\n// the grpc-js interceptor's `start()`, which cannot await (Pitfall 3) —\n// mirrors the Rust SDK's src/token/manager.rs::cached_access_token exactly.\n\nimport type { CookieJar } from 'tough-cookie';\nimport { Sensitive } from '../core/index.js';\nimport { ACCESS_COOKIE, REFRESH_COOKIE, extractCookieValue } from './cookieJar.js';\n\n/** Path the server scopes the `axiam_refresh` cookie to (mirrors csrf.rs). */\nconst REFRESH_COOKIE_PATH = '/api/v1/auth/refresh';\n\nexport class TokenManager {\n readonly #jar: CookieJar;\n readonly #baseUrl: string;\n #tenantId: string | undefined;\n /**\n * Non-blocking cached copy of the current access token, kept in sync via\n * `syncFromJar()` after each REST call/refresh. Read via\n * `cachedAccessToken()` without ever touching the jar's async API — this\n * is the fast-path the grpc-js interceptor's synchronous `start()` needs\n * (Pitfall 3).\n */\n #cachedAccess: Sensitive<string> | null = null;\n\n constructor(jar: CookieJar, baseUrl: string, tenantId?: string) {\n this.#jar = jar;\n this.#baseUrl = baseUrl;\n this.#tenantId = tenantId;\n }\n\n /**\n * Synchronous, best-effort read of the last-known access token. Returns\n * `null` if no token has been cached yet (no request/refresh has\n * completed since construction, or `syncFromJar()` was never called).\n */\n cachedAccessToken(): Sensitive<string> | null {\n return this.#cachedAccess;\n }\n\n /**\n * Async read of the current `axiam_refresh` cookie value from the jar,\n * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL\n * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible\n * at the bare base URL).\n */\n async refreshTokenValue(): Promise<Sensitive<string> | null> {\n const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);\n return value === undefined ? null : new Sensitive(value);\n }\n\n /**\n * Refresh the in-memory cached access token from the jar. Call this after\n * every REST request/refresh so the synchronous gRPC-interceptor fast-path\n * (`cachedAccessToken()`) stays current (Pitfall 3).\n */\n async syncFromJar(): Promise<void> {\n const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);\n this.#cachedAccess = value === undefined ? null : new Sensitive(value);\n }\n\n /** The resolved tenant identifier (slug or UUID form), if known. */\n tenantId(): string | undefined {\n return this.#tenantId;\n }\n\n /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */\n setTenantId(tenantId: string): void {\n this.#tenantId = tenantId;\n }\n\n /** Clear all cached token state (used by logout()). */\n clear(): void {\n this.#cachedAccess = null;\n }\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist).\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n iss: string;\n iat?: number;\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n}\n\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\nexport interface Verifier {\n verifyAccessToken(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * Build a verifier bound to `{baseUrl}/oauth2/jwks`. `jose` is loaded lazily\n * via dynamic `import()` (Pitfall 1 — CJS-safe); the remote JWKS itself is\n * also fetched/cached lazily by `jose`, not eagerly here.\n */\nexport function createVerifier(baseUrl: string): Verifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // the same createRemoteJWKSet cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent invalid-`kid` burst\n // against a cold cache must collapse to exactly ONE network fetch. Proven\n // (not just assumed) by `test/node/jwks.test.ts`'s \"collapses N concurrent\n // verifyAccessToken calls ... to exactly one JWKS fetch\" test, which mocks\n // global `fetch` with a call counter and fires 8 concurrent calls: jose's\n // `createRemoteJWKSet` (see jose's `RemoteJWKSet.reload()`,\n // `this.#pendingFetch ||= fetchJwks(...).then(...)`) ALREADY holds its own\n // internal lazy-promise-singleton around the underlying fetch, so\n // concurrent callers reaching a cold/unknown-kid getter share the same\n // in-flight fetch promise natively — no additional `inFlightFetch` guard\n // is added here (it would be redundant). If a future `jose` upgrade\n // removes that internal guarantee, the burst test above will start\n // failing and an explicit guard (mirroring `jwksPromise`'s shape) must be\n // added at that point.\n let jwksPromise: Promise<ReturnType<typeof import('jose').createRemoteJWKSet>> | null = null;\n\n async function getJwks() {\n if (!jwksPromise) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n jwksPromise = import('jose').then(({ createRemoteJWKSet }) =>\n createRemoteJWKSet(new URL(`${baseUrl}${JWKS_PATH}`), {\n cooldownDuration: COOLDOWN_DURATION_MS,\n timeoutDuration: TIMEOUT_DURATION_MS,\n }),\n );\n }\n return jwksPromise;\n }\n\n return {\n async verifyAccessToken(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Explicit algorithm allowlist — never trust the token's own `alg`\n // header; defense against algorithm-confusion attacks (T-17-14).\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n };\n}\n","// createNodeSession — extends the 17-02 SharedSession with the Node\n// persona's auth internals (D-13).\n//\n// Builds the same REST SharedSession the browser persona uses, then swaps\n// in a tough-cookie jar (via wrapAxios) so httpOnly Set-Cookie tokens\n// persist, and attaches a TokenManager + JWKS verifier. This is the ONE\n// shared session object gRPC (interceptor.ts/callWithRefresh.ts) and REST\n// both operate on — the single-flight refresh guard (`session.refreshGuard`,\n// a per-session instance created in the SharedSession constructor, CR-02)\n// is therefore transparently shared across both transports FOR THIS\n// SESSION ONLY, since both call it with an equivalent `POST\n// /api/v1/auth/refresh` closure. A different NodeSession/SharedSession\n// instance gets its own independent guard — refreshes never cross-wire\n// between sessions.\n\nimport type { CookieJar } from 'tough-cookie';\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from '../rest/session.js';\nimport { AxiamClient } from '../rest/client.js';\nimport { CSRF_COOKIE, createJar, extractCookieValue, wrapAxios } from './cookieJar.js';\nimport { TokenManager } from './tokenManager.js';\nimport { createVerifier, type Verifier } from './jwks.js';\n\nexport class NodeSession extends SharedSession {\n readonly tokenManager: TokenManager;\n readonly jwksVerifier: Verifier;\n readonly #jar: CookieJar;\n\n constructor(\n options: AxiamClientOptions,\n base: SharedSession,\n tokenManager: TokenManager,\n jwksVerifier: Verifier,\n jar: CookieJar,\n ) {\n super(options, base.axios, base.tenantHeaderValue);\n this.tokenManager = tokenManager;\n this.jwksVerifier = jwksVerifier;\n this.#jar = jar;\n }\n\n /**\n * Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this\n * session's per-instance `refreshGuard` (inherited from SharedSession) by\n * both REST's reactive interceptor (rest/interceptors.ts) and gRPC's\n * callWithRefresh — since `refreshGuard` is scoped to THIS session\n * instance (CR-02, D-13), both transports share exactly one in-flight\n * refresh for this session regardless of which one triggers it, while\n * remaining fully independent from any other session's guard.\n */\n doRefresh = async (): Promise<void> => {\n await this.axios.post('/api/v1/auth/refresh', {});\n await this.tokenManager.syncFromJar();\n // The refresh response may rotate the axiam_csrf cookie — resync\n // session.csrfToken from the jar so the next state-changing request\n // still forwards a valid X-CSRF-Token (CR-01).\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a\n * successful login()/verifyMfa(). Refreshes the cached access token (so\n * the gRPC interceptor's synchronous fast-path is current immediately\n * after login) and reads the `axiam_csrf` cookie out of the jar into\n * `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.\n */\n onAuthenticated = async (): Promise<void> => {\n await this.tokenManager.syncFromJar();\n await this.#syncCsrfFromJar();\n };\n\n async #syncCsrfFromJar(): Promise<void> {\n this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);\n }\n}\n\n/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */\nexport function createNodeSession(options: AxiamClientOptions): NodeSession {\n const base = createSession(options);\n const jar = createJar();\n wrapAxios(base.axios, jar);\n\n const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);\n const jwksVerifier = createVerifier(options.baseUrl);\n\n return new NodeSession(options, base, tokenManager, jwksVerifier, jar);\n}\n\n/**\n * Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node\n * counterpart to `new AxiamClient(options)` (which builds the browser\n * `SharedSession` with no cookie jar): it constructs a `NodeSession`\n * (tough-cookie jar + CSRF/refresh token sync) and adopts it via the\n * `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens\n * from login/refresh persist and every post-login REST call authenticates\n * correctly under Node.\n *\n * Lives in this Node-only module (reachable via the `axiam-sdk/node` and\n * `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`\n * entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).\n * The returned client shares the single session with any `AuthzGrpcClient`\n * built from the same `NodeSession`.\n */\nexport function createNodeClient(options: AxiamClientOptions): AxiamClient {\n return new AxiamClient(options, createNodeSession(options));\n}\n"]}
1
+ {"version":3,"sources":["../../src/grpc/interceptor.ts","../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/grpc/callWithRefresh.ts","../../src/grpc/client.ts","../../src/rest/session.ts","../../src/rest/interceptors.ts","../../src/rest/auth.ts","../../src/rest/authz.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../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IpC,IAAA,MAAM,KAAK,gBAAA,EAAiB;AAAA,EAC9B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,kBAAkB,YAA2B;AAC3C,IAAA,MAAM,IAAA,CAAK,aAAa,WAAA,EAAY;AACpC,IAAA,MAAM,KAAK,gBAAA,EAAiB;AAAA,EAC9B,CAAA;AAAA,EAEA,MAAM,gBAAA,GAAkC;AACtC,IAAA,IAAA,CAAK,YAAY,MAAM,kBAAA,CAAmB,KAAK,IAAA,EAAM,IAAA,CAAK,SAAS,WAAW,CAAA;AAAA,EAChF;AACF;AAGO,SAAS,kBAAkB,OAAA,EAA0C;AAC1E,EAAA,MAAM,IAAA,GAAO,cAAc,OAAO,CAAA;AAClC,EAAA,MAAM,MAAM,SAAA,EAAU;AACtB,EAAA,SAAA,CAAU,IAAA,CAAK,OAAO,GAAG,CAAA;AAEzB,EAAA,MAAM,eAAe,IAAI,YAAA,CAAa,KAAK,OAAA,CAAQ,OAAA,EAAS,KAAK,iBAAiB,CAAA;AAClF,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,CAAQ,OAAO,CAAA;AAEnD,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,IAAA,EAAM,YAAA,EAAc,cAAc,GAAG,CAAA;AACvE;AAiBO,SAAS,iBAAiB,OAAA,EAA0C;AACzE,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,iBAAA,CAAkB,OAAO,CAAC,CAAA;AAC5D","file":"index.js","sourcesContent":["// Synchronous auth/tenant grpc-js interceptor (D-10, Pitfall 3).\n//\n// grpc-js's `start(metadata, listener, next)` callback is SYNCHRONOUS —\n// unlike tonic's async-native interceptor trait, it must call\n// `next(metadata, listener)` without ever awaiting. This interceptor\n// therefore only reads the TokenManager's non-blocking, in-memory cached\n// access token (populated by `syncFromJar()` after REST calls/refresh) —\n// it NEVER triggers a refresh itself. UNAUTHENTICATED handling belongs to\n// the async call-wrapper (callWithRefresh.ts), never here.\n//\n// Mirrors the Rust SDK's src/grpc/interceptor.rs exactly, adapted to grpc-js's\n// structurally different (non-tower) interceptor API\n// (RESEARCH.md Area 3 / grpc/proposal L5-node-client-interceptors.md).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { Interceptor } from '@grpc/grpc-js';\nimport type { NodeSession } from '../node/session.js';\n\n/**\n * Injects `authorization: Bearer <token>` (when a cached token is present)\n * and `x-tenant-id` metadata on every outgoing RPC (CONTRACT.md §5). Never\n * logs the token — `expose()` is only called at this metadata-insertion\n * boundary.\n */\nexport function authInterceptor(session: NodeSession): Interceptor {\n return (options, nextCall) => {\n return new grpc.InterceptingCall(nextCall(options), {\n start(metadata, listener, next) {\n // Non-blocking cached-token read — NEVER await here (Pitfall 3).\n const token = session.tokenManager.cachedAccessToken();\n if (token) {\n metadata.add('authorization', `Bearer ${token.expose()}`);\n }\n metadata.add('x-tenant-id', session.tenantHeaderValue);\n next(metadata, listener);\n },\n });\n };\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Exactly three concrete error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. No error message or field may\n// embed a raw token string (D-16). The prototype chain is fixed up manually\n// in each constructor so `instanceof` works reliably across the transpiled\n// CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat when\n// extending built-ins like Error).\n\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AuthError extends AxiamError {\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport class AuthzError extends AxiamError {\n readonly action?: string;\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\nexport class NetworkError extends AxiamError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Central status -> error mapper (CONTRACT.md §2, D-17).\n//\n// The single source of truth for both rest/ and grpc/ transports so the two\n// cannot drift on the error taxonomy. Transcribes CONTRACT.md §2's HTTP and\n// gRPC tables exactly.\n//\n// GrpcStatus is exported here (not imported from @grpc/grpc-js) so that\n// core stays dependency-free — grpc/ imports the numeric codes from core\n// rather than the other way around.\n\nimport { AuthError, AuthzError, NetworkError, type AxiamError } from './errors.js';\n\n/** gRPC status codes referenced by CONTRACT.md §2 (subset of the full grpc.status enum). */\nexport const GrpcStatus = {\n DEADLINE_EXCEEDED: 4,\n PERMISSION_DENIED: 7,\n RESOURCE_EXHAUSTED: 8,\n INTERNAL: 13,\n UNAVAILABLE: 14,\n UNAUTHENTICATED: 16,\n} as const;\n\nexport interface HttpErrorContext {\n action?: string;\n resourceId?: string;\n cause?: unknown;\n /**\n * The parsed JSON response body (when available). For a 403/409\n * authorization-denied response the server shapes this as\n * `{ error: \"authorization_denied\", message, action?, resource_id? }`\n * (`action` present when known, `resource_id` present only for a\n * resource-scoped denial). `mapHttpStatusToError` prefers these body\n * fields over `action`/`resourceId` above when populating `AuthzError`.\n */\n body?: unknown;\n}\n\n/**\n * Extract `action`/`resource_id` (snake_case -> camelCase) from a parsed\n * authorization-denied response body, if present and string-typed. Any other\n * shape (missing fields, non-object body, older servers with no body at all)\n * yields `{}`, so callers fall back to caller-supplied context.\n */\nfunction extractAuthzFieldsFromBody(body: unknown): { action?: string; resourceId?: string } {\n if (body === null || typeof body !== 'object') {\n return {};\n }\n const record = body as Record<string, unknown>;\n const action = typeof record.action === 'string' ? record.action : undefined;\n const resourceId = typeof record.resource_id === 'string' ? record.resource_id : undefined;\n return { action, resourceId };\n}\n\n/**\n * ALLOWLIST (X-3) of response headers that are safe to preserve in a\n * NetworkError.cause. Every header NOT listed here has its value redacted to a\n * placeholder, so a custom sensitive header (e.g. `X-Auth-Token`) can never\n * survive into a thrown error — unlike a small denylist, which only catches the\n * headers it happens to enumerate. Names are compared case-insensitively (all\n * entries are lower-case). Keep this list small and strictly non-secret:\n * standard diagnostic response headers plus this SDK's own non-secret request\n * headers (e.g. `x-tenant-id`).\n */\nconst SAFE_RESPONSE_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'date',\n 'server',\n 'retry-after',\n 'x-request-id',\n 'x-tenant-id',\n]);\n\n/** Placeholder substituted for the value of any non-allowlisted header. */\nconst REDACTED_HEADER = '[REDACTED]';\n\n/**\n * Redact every non-allowlisted response header from an axios-error-shaped\n * `err` before it is attached as `NetworkError.cause` (CR-04, D-16, X-3). On\n * login/refresh error paths the server may have already issued Set-Cookie\n * headers containing raw `axiam_access`/`axiam_refresh` values (and callers may\n * set custom sensitive headers such as `X-Auth-Token`); none of these must be\n * reachable via `console.log`/`JSON.stringify`/`util.inspect` of the thrown\n * error. Only headers on `SAFE_RESPONSE_HEADERS` keep their value; all others\n * are replaced with `[REDACTED]`.\n *\n * Returns a new, shallow-cloned object for any input shaped like\n * `{ response: { headers: {...} } }` — the caller's original axios error\n * object is left untouched. Non-object inputs (plain Error, string,\n * undefined) and objects with no `response.headers` are returned unchanged.\n */\nexport function sanitizeAxiosError(err: unknown): unknown {\n if (err === null || typeof err !== 'object') {\n return err;\n }\n const candidate = err as { response?: unknown };\n if (candidate.response === null || typeof candidate.response !== 'object') {\n return err;\n }\n const response = candidate.response as { headers?: unknown };\n if (response.headers === null || typeof response.headers !== 'object') {\n return err;\n }\n\n const sanitizedHeaders: Record<string, unknown> = { ...(response.headers as Record<string, unknown>) };\n for (const key of Object.keys(sanitizedHeaders)) {\n if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {\n sanitizedHeaders[key] = REDACTED_HEADER;\n }\n }\n\n return {\n ...err,\n response: {\n ...response,\n headers: sanitizedHeaders,\n },\n };\n}\n\n/**\n * Map an HTTP status code to an AxiamError variant per CONTRACT.md §2's HTTP\n * status table.\n *\n * | Status | Type |\n * |-----------|--------------|\n * | 400 | NetworkError |\n * | 401 | AuthError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * NetworkError's `cause` (when provided via `ctx.cause`) is always passed\n * through `sanitizeAxiosError` first (CR-04) — this is the single choke\n * point for both rest/ auth call sites and any future caller.\n *\n * For 403/409, `action`/`resourceId` are sourced from the response body\n * (`ctx.body`) when the body carries them, falling back to the\n * caller-supplied `ctx.action`/`ctx.resourceId` (the request call-args)\n * otherwise — this keeps compatibility with older servers that don't yet\n * echo `action`/`resource_id` in the denial body.\n */\nexport function mapHttpStatusToError(\n status: number,\n message: string,\n ctx?: HttpErrorContext,\n): AxiamError {\n if (status === 401) {\n return new AuthError(message);\n }\n if (status === 403 || status === 409) {\n const fromBody = extractAuthzFieldsFromBody(ctx?.body);\n return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);\n }\n // 400, 408, 429, 5xx, and any other status fall through to NetworkError.\n return new NetworkError(message, sanitizeAxiosError(ctx?.cause));\n}\n\n/**\n * Map a gRPC status code to an AxiamError variant per CONTRACT.md §2's gRPC\n * status table.\n *\n * | Code | Type |\n * |------------------------|--------------|\n * | 16 UNAUTHENTICATED | AuthError |\n * | 7 PERMISSION_DENIED | AuthzError |\n * | 14 UNAVAILABLE | NetworkError |\n * | 4 DEADLINE_EXCEEDED | NetworkError |\n * | 13 INTERNAL | NetworkError |\n * | 8 RESOURCE_EXHAUSTED | NetworkError |\n * | other | NetworkError |\n */\nexport function mapGrpcStatusToError(code: number, message: string): AxiamError {\n if (code === GrpcStatus.UNAUTHENTICATED) {\n return new AuthError(message);\n }\n if (code === GrpcStatus.PERMISSION_DENIED) {\n return new AuthzError(message);\n }\n return new NetworkError(message);\n}\n","// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\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","// CSRF double-submit helpers (CONTRACT.md §3, D-05/D-28).\n//\n// The AXIAM server's CSRF middleware validates X-CSRF-Token against the\n// axiam_csrf cookie value directly (cookie double-submit). The regex is\n// deliberately hardcoded (not built dynamically from a configurable cookie\n// name) to avoid ReDoS/CWE-1333 — mirrors frontend/src/lib/api.ts exactly.\n\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\nexport const CSRF_HEADER = 'X-CSRF-Token';\nexport const CSRF_METHODS: ReadonlySet<string> = new Set(['post', 'put', 'patch', 'delete']);\n\nconst CSRF_COOKIE_REGEX = /(?:^|;\\s*)axiam_csrf=([^;]*)/;\n\n/** Extract the axiam_csrf cookie value from a `document.cookie`-shaped string, or null if absent. */\nexport function readCsrfCookie(cookieString: string): string | null {\n const match = CSRF_COOKIE_REGEX.exec(cookieString);\n if (!match) {\n return null;\n }\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Returns the CSRF header value for a state-changing HTTP method\n * (post/put/patch/delete, case-insensitive), or undefined for safe methods\n * (get/head/options) or when no CSRF cookie is present yet.\n */\nexport function csrfHeaderForMethod(method: string, cookieString: string): string | undefined {\n if (!CSRF_METHODS.has(method.toLowerCase())) {\n return undefined;\n }\n const token = readCsrfCookie(cookieString);\n return token ?? undefined;\n}\n","// Single-flight refresh guard (CONTRACT.md §9, D-07/D-13).\n//\n// Per-session-scoped shared-Promise guard (CR-02 gap closure, 17-VERIFICATION.md):\n// createRefreshGuard() returns a fresh, independent refreshOnce closure per\n// call, each closing over its OWN private refreshPromise. Concurrent callers\n// against the SAME guard instance share the same in-flight Promise; the\n// guard clears on settle (success or failure) so a later expiry can trigger\n// a fresh refresh — this is the exactly-one-in-flight-at-a-time semantics §9\n// requires, not a permanent single-refresh-ever lock. Distinct guard\n// instances (one per SharedSession/NodeSession, D-13) never share state, so\n// a refresh on session A can never silently satisfy a concurrent refresh on\n// session B.\n\n/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */\nexport type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;\n\n/** Test-only reset hook type, attached to each guard closure via `Object.assign`. @internal */\ninterface ResettableRefreshGuard {\n (doRefresh: () => Promise<void>): Promise<void>;\n __reset(): void;\n}\n\n/**\n * Build a fresh, independent single-flight refresh guard. Each call returns\n * its own closure with a private `refreshPromise` — instantiate one per\n * `SharedSession`/`NodeSession` (D-13) so refresh guards never cross-wire\n * between independent client instances (CR-02).\n */\nexport function createRefreshGuard(): RefreshGuard {\n let refreshPromise: Promise<void> | null = null;\n\n const guard = ((doRefresh: () => Promise<void>): Promise<void> => {\n if (!refreshPromise) {\n refreshPromise = doRefresh().finally(() => {\n refreshPromise = null;\n });\n }\n return refreshPromise;\n }) as ResettableRefreshGuard;\n\n guard.__reset = () => {\n refreshPromise = null;\n };\n\n return guard;\n}\n\n// Backward-compatible module-level default guard instance, retained for\n// test/core/singleFlightRefresh.test.ts and any caller still importing the\n// bare `refreshOnce`/`resetRefreshGuard` module-level functions. New\n// wiring (rest/interceptors.ts, grpc/callWithRefresh.ts) MUST use a\n// per-session guard from `createRefreshGuard()` instead (see\n// SharedSession.refreshGuard).\nconst defaultGuard = createRefreshGuard() as ResettableRefreshGuard;\n\n/**\n * Ensures at most one `doRefresh()` call is in flight at a time, backed by\n * the single module-level default guard instance. Concurrent callers share\n * the same in-flight Promise; after it settles, a subsequent call invokes\n * `doRefresh` again.\n *\n * @deprecated for new wiring — use a per-instance guard from\n * `createRefreshGuard()` instead (D-13/CR-02). Retained for backward\n * compatibility.\n */\nexport function refreshOnce(doRefresh: () => Promise<void>): Promise<void> {\n return defaultGuard(doRefresh);\n}\n\n/** Test-only helper to reset the module-level default guard between test cases. @internal */\nexport function resetRefreshGuard(): void {\n defaultGuard.__reset();\n}\n","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n","// UNAUTHENTICATED single-flight-retry wrapper (D-10/D-13, CONTRACT.md §9).\n//\n// The interceptor (interceptor.ts) is synchronous and never triggers a\n// refresh (Pitfall 3). This ASYNC call-site wrapper is where\n// UNAUTHENTICATED handling actually lives: on a caught error whose\n// `.code === GrpcStatus.UNAUTHENTICATED`, it awaits the session's\n// per-instance single-flight refresh guard (`session.refreshGuard` — the\n// SAME guard instance the REST transport for this session uses, D-13, but\n// NEVER shared with a different session, CR-02), resyncs the interceptor's\n// cached-token fast-path via `syncFromJar()`, then retries the call exactly\n// once. A second UNAUTHENTICATED (or any other error) maps through\n// `mapGrpcStatusToError` and rethrows — no further retry (§9.3).\n\nimport { GrpcStatus, mapGrpcStatusToError, type AxiamError } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\n\ninterface GrpcServiceErrorLike {\n code?: number;\n message?: string;\n}\n\nfunction isGrpcServiceError(err: unknown): err is GrpcServiceErrorLike {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n/**\n * Await `fn()`. On a gRPC UNAUTHENTICATED (16) error, drive the shared\n * single-flight refresh, sync the token cache from the jar, and retry `fn()`\n * exactly once. Any other error (or a second UNAUTHENTICATED) is mapped to\n * an AxiamError via `mapGrpcStatusToError` and rethrown.\n */\nexport async function callWithRefresh<T>(session: NodeSession, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (isGrpcServiceError(err) && err.code === GrpcStatus.UNAUTHENTICATED) {\n await session.refreshGuard(session.doRefresh);\n await session.tokenManager.syncFromJar();\n try {\n return await fn();\n } catch (retryErr) {\n throw toAxiamError(retryErr);\n }\n }\n throw toAxiamError(err);\n }\n}\n\nfunction toAxiamError(err: unknown): AxiamError | unknown {\n if (isGrpcServiceError(err) && typeof err.code === 'number') {\n return mapGrpcStatusToError(err.code, err.message ?? 'gRPC call failed');\n }\n return err;\n}\n","// gRPC AuthorizationService client — reused channel, checkAccess/batchCheck\n// (D-10/D-13, SC#2 Node half).\n//\n// The generated ts-proto stubs (`src/gen`, produced by `buf generate` at\n// build time — Phase 15 D-01/D-20) are NOT committed and are unavailable in\n// this sandbox (no `buf` CLI). Rather than importing from a path that does\n// not exist here, this module (a) defines local wire-shape interfaces that\n// exactly mirror `proto/axiam/v1/authorization.proto`, and (b) builds the\n// gRPC client dynamically via grpc-js's own `makeClientConstructor` (the\n// same primitive ts-proto's `outputServices=grpc-js` stubs are built on top\n// of) rather than importing a generated class. A buf-enabled build can swap\n// `buildAuthorizationServiceClient` below for the real ts-proto-generated\n// `AuthorizationServiceClient` from `../gen/...` with NO change to the\n// public `AuthzGrpcClient` surface, since both satisfy the same\n// `WireAuthorizationServiceClient` shape by construction (same .proto).\n// End-to-end wiring against real generated stubs is deferred to a\n// buf-enabled CI run (RESEARCH.md D-20; environment note in this plan).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { AccessDecision } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\nimport { authInterceptor } from './interceptor.js';\nimport { callWithRefresh } from './callWithRefresh.js';\n\n// Re-exported (not re-declared) so `grpc/index.ts` can still export\n// `AccessDecision` from `./client.js` — see `core/authz.ts` for the single\n// shared definition (SDK-Q10, C2).\nexport type { AccessDecision };\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/authorization.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\nexport interface WireCheckAccessRequest {\n tenant_id: string;\n // `subject_id` is a required (non-`optional`) proto3 field\n // (`proto/axiam/v1/authorization.proto`), unlike `scope` below — the wire\n // contract always carries it, so it stays required here too rather than\n // relaxed to match REST's optional `subjectId` (see `CheckAccessRequest`\n // below for why the two transports differ).\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n}\n\nexport interface WireCheckAccessResponse {\n allowed: boolean;\n deny_reason: string;\n}\n\nexport interface WireBatchCheckAccessRequest {\n requests: WireCheckAccessRequest[];\n}\n\nexport interface WireBatchCheckAccessResponse {\n results: WireCheckAccessResponse[];\n}\n\ntype UnaryCallback<T> = (error: grpc.ServiceError | null, response?: T) => void;\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `AuthorizationServiceClient` this module needs. The real generated client\n * satisfies this shape exactly (unary Node-callback methods), so a\n * buf-enabled build's generated client is a drop-in replacement here.\n */\nexport interface WireAuthorizationServiceClient {\n checkAccess(\n request: WireCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n batchCheckAccess(\n request: WireBatchCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireBatchCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * Public (camelCase, §1) single access-check request shape.\n *\n * `subjectId` is required here (unlike REST's optional `AccessCheck.subjectId`)\n * because gRPC calls typically originate from a service-mesh caller with no\n * request-scoped JWT to derive a subject from — the caller must pass it\n * explicitly. REST, by contrast, derives the subject from the caller's JWT\n * when `subjectId` is omitted (§5). This mirrors the proto's non-`optional`\n * `subject_id` field (`proto/axiam/v1/authorization.proto`), which is not\n * changed here (SDK-Q10, C2).\n */\nexport interface CheckAccessRequest {\n tenantId: string;\n subjectId: string;\n action: string;\n resourceId: string;\n scope?: string;\n}\n\nfunction toWireRequest(req: CheckAccessRequest): WireCheckAccessRequest {\n return {\n tenant_id: req.tenantId,\n subject_id: req.subjectId,\n action: req.action,\n resource_id: req.resourceId,\n scope: req.scope,\n };\n}\n\nfunction fromWireResponse(resp: WireCheckAccessResponse): AccessDecision {\n return {\n allowed: resp.allowed,\n reason: resp.deny_reason ? resp.deny_reason : undefined,\n };\n}\n\nfunction promisifyUnary<TReq, TResp>(\n call: (req: TReq, metadata: grpc.Metadata, callback: UnaryCallback<TResp>) => grpc.ClientUnaryCall,\n request: TReq,\n): Promise<TResp> {\n return new Promise((resolve, reject) => {\n call(request, new grpc.Metadata(), (error, response) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(response as TResp);\n });\n });\n}\n\n/**\n * Build the gRPC channel credentials for `baseUrl` (§6 — TLS is always\n * strict by default; `customCa` is the ONLY certificate escape hatch, never\n * an insecure/skip-verification surface).\n *\n * A plaintext target (`http://`/`grpc://`) is REFUSED by default (X-2): it\n * would silently drop the channel to `createInsecure()`, sending bearer tokens\n * and tenant metadata in cleartext. Callers who genuinely need a local dev\n * plaintext channel must opt in explicitly with `allowInsecure: true`, which\n * emits a `console.warn`. As a convenience the opt-in is required for ANY host\n * (including loopback) — there is no silent path to an insecure channel.\n */\nfunction buildCredentials(\n baseUrl: string,\n customCa: string | undefined,\n allowInsecure: boolean,\n): grpc.ChannelCredentials {\n const isSecure = baseUrl.startsWith('https://') || baseUrl.startsWith('grpcs://');\n if (!isSecure) {\n if (!allowInsecure) {\n throw new Error(\n `AXIAM gRPC refuses to open an insecure (plaintext) channel to \"${baseUrl}\": ` +\n 'bearer tokens and tenant metadata would be sent in cleartext. Use an ' +\n 'https:// or grpcs:// target, or pass { allowInsecure: true } to opt in ' +\n 'explicitly for a trusted local/dev channel (CONTRACT.md §6).',\n );\n }\n // Explicit opt-in only — never reached without allowInsecure.\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM gRPC: opening an INSECURE (plaintext) channel to \"${baseUrl}\" because ` +\n 'allowInsecure was set. Bearer tokens and tenant metadata are transmitted in ' +\n 'cleartext — never use this outside a trusted local/dev environment.',\n );\n return grpc.ChannelCredentials.createInsecure();\n }\n if (customCa) {\n return grpc.ChannelCredentials.createSsl(Buffer.from(customCa, 'utf8'));\n }\n // Default: verify against the platform's native trust store.\n return grpc.ChannelCredentials.createSsl();\n}\n\nfunction grpcTarget(baseUrl: string): string {\n const url = new URL(baseUrl);\n return url.port ? `${url.hostname}:${url.port}` : url.hostname;\n}\n\nconst jsonCodec = <T>() => ({\n serialize: (value: T): Buffer => Buffer.from(JSON.stringify(value)),\n deserialize: (bytes: Buffer): T => JSON.parse(bytes.toString('utf8')) as T,\n});\n\n/**\n * Construct a real `AuthorizationServiceClient` over grpc-js's own\n * `makeClientConstructor` primitive (the same primitive ts-proto's\n * `outputServices=grpc-js` codegen target uses under the hood). This\n * transport-level client encodes/decodes with JSON as a build-independent\n * stand-in for the protobuf binary codec a buf-enabled build's generated\n * serializers would use — swap this factory for the generated\n * `AuthorizationServiceClient` once `src/gen` exists (D-20).\n */\nexport function buildAuthorizationServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireAuthorizationServiceClient {\n const checkAccessCodec = jsonCodec<WireCheckAccessRequest>();\n const checkAccessRespCodec = jsonCodec<WireCheckAccessResponse>();\n const batchCodec = jsonCodec<WireBatchCheckAccessRequest>();\n const batchRespCodec = jsonCodec<WireBatchCheckAccessResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n checkAccess: {\n path: '/axiam.v1.AuthorizationService/CheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: checkAccessCodec.serialize,\n requestDeserialize: checkAccessCodec.deserialize,\n responseSerialize: checkAccessRespCodec.serialize,\n responseDeserialize: checkAccessRespCodec.deserialize,\n },\n batchCheckAccess: {\n path: '/axiam.v1.AuthorizationService/BatchCheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: batchCodec.serialize,\n requestDeserialize: batchCodec.deserialize,\n responseSerialize: batchRespCodec.serialize,\n responseDeserialize: batchRespCodec.deserialize,\n },\n },\n 'axiam.v1.AuthorizationService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireAuthorizationServiceClient;\n}\n\nexport type AuthorizationServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireAuthorizationServiceClient;\n\n/**\n * gRPC transport for `AuthorizationService` (`checkAccess`/`batchCheck`,\n * SC#2 Node half), reusing one long-lived client/channel per instance (D-10\n * — never reconstructed per-call) and injecting auth + tenant metadata via\n * the synchronous interceptor on every RPC.\n */\nexport class AuthzGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireAuthorizationServiceClient;\n\n constructor(\n session: NodeSession,\n options: { baseUrl: string; customCa?: string; allowInsecure?: boolean },\n clientFactory: AuthorizationServiceClientFactory = buildAuthorizationServiceClient,\n ) {\n this.#session = session;\n const credentials = buildCredentials(options.baseUrl, options.customCa, options.allowInsecure ?? false);\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */\n async checkAccess(request: CheckAccessRequest): Promise<AccessDecision> {\n const wireRequest = toWireRequest(request);\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.checkAccess.bind(this.#inner), wireRequest),\n );\n return fromWireResponse(response);\n }\n\n /** `BatchCheckAccess` over gRPC — results preserve input order (§1). */\n async batchCheck(requests: CheckAccessRequest[]): Promise<AccessDecision[]> {\n const wireRequest: WireBatchCheckAccessRequest = { requests: requests.map(toWireRequest) };\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.batchCheckAccess.bind(this.#inner), wireRequest),\n );\n return response.results.map(fromWireResponse);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n","// SharedSession — the object other transports (Node persona 17-03, middleware\n// 17-05) attach gRPC/JWKS/middleware state to (D-13).\n//\n// Holds: the axios instance, the tenant header value (computed once at\n// construction), a mutable csrfToken store, the base URL, and a per-instance\n// single-flight refresh guard (CR-02: NOT the module-level default guard —\n// each SharedSession gets its own via createRefreshGuard(), so two\n// independent AxiamClient/NodeSession instances never cross-wire refreshes).\n// One login() drives all transports for a given session.\n\nimport axios, { type AxiosInstance } from 'axios';\nimport type { AxiamClientOptions, RefreshGuard } from '../core/index.js';\nimport { createRefreshGuard, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS } from '../core/index.js';\n\nconst PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * The single session object every AXIAM transport (REST here, gRPC/AMQP in\n * 17-03/17-04, middleware in 17-05) attaches to. Constructed once per\n * `AxiamClient` instance.\n */\nexport class SharedSession {\n /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */\n readonly axios: AxiosInstance;\n /** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */\n readonly baseUrl: string;\n /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */\n readonly tenantHeaderValue: string;\n /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */\n csrfToken: string | undefined;\n /** Set true once a successful login/verifyMfa has completed. */\n authenticated = false;\n /**\n * Per-instance single-flight refresh guard (CR-02, D-13). Shared across\n * this session's REST and gRPC transports (rest/interceptors.ts,\n * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but\n * NEVER shared with a different SharedSession/NodeSession instance.\n *\n * @internal SDK-internal transport wiring, not intended to be invoked\n * directly by SDK consumers — refreshes are driven automatically by the\n * response interceptor (rest) or `callWithRefresh` (grpc).\n */\n readonly refreshGuard: RefreshGuard;\n\n constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string) {\n this.axios = axiosInstance;\n this.baseUrl = options.baseUrl;\n this.tenantHeaderValue = tenantHeaderValue;\n this.refreshGuard = createRefreshGuard();\n }\n\n /**\n * Optional session-level hook invoked by rest/auth.ts after a successful\n * login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser\n * persona) does not implement it — the browser reads document.cookie\n * directly on every request and has no jar to sync from. NodeSession\n * overrides this to populate `csrfToken` from its cookie jar and refresh\n * the cached access token.\n */\n onAuthenticated?(): Promise<void>;\n\n /**\n * Host-isolation guard (3A, defense in depth): returns `true` when `url`\n * targets a host other than this session's base origin — an absolute\n * third-party URL, or a redirect that axios/the browser resolved off-origin.\n * The tenant identifier and CSRF token must never be attached to such a\n * request. A relative/host-less `url` (the normal case, merged against\n * `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's\n * `_prepare_request` guard. Malformed input fails closed (treated as\n * foreign).\n */\n isForeignHost(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n const target = new URL(url, this.baseUrl);\n return target.host !== new URL(this.baseUrl).host;\n } catch {\n return true;\n }\n }\n}\n\n/**\n * Resolve the required tenant header value from options (§5). Throws if\n * neither tenantSlug nor tenantId is provided — there is no default tenant.\n */\nexport function resolveTenantHeaderValue(options: AxiamClientOptions): string {\n if (options.tenantSlug) {\n return options.tenantSlug;\n }\n if (options.tenantId) {\n return options.tenantId;\n }\n throw new Error(\n 'AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md §5).',\n );\n}\n\n/**\n * Build the Node-only `https.Agent` for a customCa PEM. Guarded by\n * `typeof process !== 'undefined'` as a CAPABILITY guard (Node has\n * node:https available), NOT a persona-sniffing branch — browsers ignore\n * customCa entirely since the platform manages TLS verification itself.\n */\nfunction maybeBuildHttpsAgent(customCa: string | undefined): unknown {\n if (!customCa) {\n return undefined;\n }\n if (!customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n if (typeof process === 'undefined') {\n // Browser: platform manages TLS; customCa has no effect there.\n return undefined;\n }\n // Node capability guard — require lazily so this branch never executes\n // (and never needs to resolve) in a browser bundle.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const https = require('node:https') as typeof import('node:https');\n return new https.Agent({ ca: customCa });\n}\n\n/** Build the axios instance + SharedSession for an AxiamClient (D-13/D-25). */\nexport function createSession(options: AxiamClientOptions): SharedSession {\n const tenantHeaderValue = resolveTenantHeaderValue(options);\n\n // customCa is validated (PEM-shape) even when running in an environment\n // that will end up ignoring it (browser), so construction fails fast and\n // consistently across personas (§6).\n if (options.customCa !== undefined && !options.customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa);\n\n const axiosInstance = axios.create({\n baseURL: options.baseUrl,\n withCredentials: true,\n timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n ...(httpsAgent ? { httpsAgent } : {}),\n });\n\n const session = new SharedSession(options, axiosInstance, tenantHeaderValue);\n\n // Attach X-Tenant-ID to every outgoing request (§5.2) — except when the\n // request targets a host other than our own origin (host-isolation, 3A).\n axiosInstance.interceptors.request.use((config) => {\n if (session.isForeignHost(config.url)) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['X-Tenant-ID'] = session.tenantHeaderValue;\n return config;\n });\n\n return session;\n}\n","// Axios interceptors: CSRF forwarding (D-05, §3) + reactive single-flight\n// 401->refresh (D-07, §9). Mirrors frontend/src/lib/api.ts's proven pattern,\n// generalized off the app store: this is a library, not an app — refresh\n// failure clears session auth state and rejects; it never redirects\n// (no window.location access anywhere in this module).\n\nimport type { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport { csrfHeaderForMethod, mapHttpStatusToError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Endpoints that must never trigger a silent refresh, to avoid infinite\n * refresh loops (§9.3): the refresh endpoint itself, plus login/logout which\n * are not authenticated-session-continuation calls.\n */\nexport const SKIP_REFRESH = ['/api/v1/auth/refresh', '/api/v1/auth/login', '/api/v1/auth/logout'];\n\ntype RetryableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean };\n\n/**\n * Request interceptor: forwards the axiam_csrf cookie as X-CSRF-Token on\n * state-changing methods (POST/PUT/PATCH/DELETE) per §3/D-05.\n *\n * Browser: reads `document.cookie` directly (guarded by `typeof document !==\n * 'undefined'`). Node: reads the session's csrfToken store, populated by the\n * Node persona's cookie-jar read (17-03) — left undefined here since no jar\n * exists in the browser-only REST core built by this plan.\n */\nexport function installCsrfInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {\n // Host-isolation (3A): never echo the CSRF token to an off-origin host.\n if (session.isForeignHost(config.url)) {\n return config;\n }\n const method = (config.method ?? 'get').toLowerCase();\n const cookieString = typeof document !== 'undefined' ? document.cookie : '';\n const csrfToken =\n typeof document !== 'undefined' ? csrfHeaderForMethod(method, cookieString) : csrfHeaderForMethod(method, session.csrfToken ? `axiam_csrf=${session.csrfToken}` : '');\n\n if (csrfToken) {\n config.headers = config.headers ?? {};\n config.headers['X-CSRF-Token'] = csrfToken;\n }\n return config;\n });\n}\n\n/**\n * Response interceptor: on 401 (when authenticated, not a SKIP_REFRESH url,\n * not already retried) performs a reactive single-flight refresh and replays\n * the original request (D-07/§9). Non-2xx responses are mapped through\n * core's mapHttpStatusToError.\n */\nexport function installRefreshInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.response.use(\n (response) => response,\n async (error: AxiosError) => {\n const originalRequest = error.config as RetryableRequestConfig | undefined;\n\n if (!originalRequest || !error.response) {\n // No response at all (network/timeout) — surface as NetworkError below via caller mapping.\n return Promise.reject(error);\n }\n\n const status = error.response.status;\n const url = originalRequest.url ?? '';\n const isSkipRefresh = SKIP_REFRESH.some((skipUrl) => url.includes(skipUrl));\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated) {\n // CQ-F32: set _retry BEFORE the refresh call so a 401 on the replayed\n // request cannot trigger a second refresh cycle.\n originalRequest._retry = true;\n\n try {\n await session.refreshGuard(async () => {\n await session.axios.post('/api/v1/auth/refresh', {});\n });\n return axiosInstance(originalRequest);\n } catch (refreshError) {\n session.authenticated = false;\n session.csrfToken = undefined;\n return Promise.reject(\n mapHttpStatusToError(401, 'session refresh failed; re-authentication required', {\n cause: refreshError,\n }),\n );\n }\n }\n\n if (status === 401 && isSkipRefresh) {\n return Promise.reject(mapHttpStatusToError(401, 'authentication failed'));\n }\n\n return Promise.reject(error);\n },\n );\n}\n\n/** Install both the CSRF and reactive single-flight refresh interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n}\n","// login/verifyMfa/refresh/logout over REST (D-18, §1).\n//\n// Mirrors the Rust SDK's src/rest/auth.rs's request/response shapes exactly\n// (mirror only, no server crate dependency). Tokens are delivered\n// exclusively via Set-Cookie — LoginResult deliberately carries no session\n// token field anywhere in the public API (T-17-07).\n\nimport { mapHttpStatusToError, NetworkError, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n RefreshSuccessResponseWire,\n} from './types.js';\n\nconst LOGIN_PATH = '/api/v1/auth/login';\nconst MFA_VERIFY_PATH = '/api/v1/auth/mfa/verify';\nconst REFRESH_PATH = '/api/v1/auth/refresh';\nconst LOGOUT_PATH = '/api/v1/auth/logout';\n\ninterface LoginRequestBody {\n username_or_email: string;\n password: string;\n}\n\ninterface MfaVerifyRequestBody {\n challenge_token: string;\n totp_code: string;\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire): LoginResult {\n return {\n status: 'authenticated',\n user: { id: wire.user.id, username: wire.user.username, email: wire.user.email },\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\nfunction mfaRequiredToResult(wire: MfaRequiredResponseWire): LoginResult {\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n}\n\nfunction extractErrorMessage(err: unknown): string {\n if (err && typeof err === 'object' && 'message' in err && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message;\n }\n return 'request failed';\n}\n\n/**\n * `POST /api/v1/auth/login` (§1).\n *\n * On a 200 response returns the authenticated branch of the LoginResult\n * discriminated union; on the MFA-required response (202) returns the\n * mfa_required branch (mfaToken sourced from the wire challenge_token).\n */\nexport async function login(client: AxiamClient, email: string, password: string): Promise<LoginResult> {\n const body: LoginRequestBody = { username_or_email: email, password };\n\n try {\n // axios treats any 2xx (including 202 MFA-required) as a resolved\n // response, not a thrown error — branch on the actual status here.\n const response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n LOGIN_PATH,\n body,\n );\n if (response.status === 202) {\n return mfaRequiredToResult(response.data as MfaRequiredResponseWire);\n }\n client.session.authenticated = true;\n // CR-01/D-05: sync the Node persona's csrfToken (and cached access token)\n // from the jar now that the session cookie(s) have landed. No-op for the\n // browser SharedSession, which has no onAuthenticated implementation.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data as LoginSuccessResponseWire);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'login failed', {\n cause: err,\n });\n }\n throw new NetworkError('login request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/mfa/verify` (§1).\n *\n * Completes the two-phase flow started by login() when status was\n * 'mfa_required', using the caller-supplied mfaToken (the challenge token\n * returned from that prior login() call).\n */\nexport async function verifyMfa(client: AxiamClient, mfaToken: string, code: string): Promise<LoginResult> {\n const body: MfaVerifyRequestBody = { challenge_token: mfaToken, totp_code: code };\n\n try {\n const response = await client.session.axios.post<LoginSuccessResponseWire>(MFA_VERIFY_PATH, body);\n client.session.authenticated = true;\n // CR-01/D-05: same post-authentication sync as login()'s 200 branch.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'verifyMfa failed', {\n cause: err,\n });\n }\n throw new NetworkError('verifyMfa request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/refresh` (§1).\n *\n * Callers typically do not invoke this directly — the response interceptor\n * (interceptors.ts) drives it reactively via the single-flight guard on a\n * 401 (D-07). Exposed as a public method for explicit proactive refresh.\n */\nexport async function refresh(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n // §9.3: 401 on the refresh call itself is AuthError, no retry loop.\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'refresh failed', {\n cause: err,\n });\n }\n throw new NetworkError('refresh request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/logout` (§1).\n *\n * Clears session csrf/auth state regardless of the response outcome once\n * the request has been sent successfully.\n */\nexport async function logout(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post(LOGOUT_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'logout failed', {\n cause: err,\n });\n }\n throw new NetworkError('logout request failed', sanitizeAxiosError(err));\n } finally {\n client.session.authenticated = false;\n client.session.csrfToken = undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// axios error helpers (kept local — core stays dependency-free of axios)\n// ---------------------------------------------------------------------------\n\nfunction extractAxiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number } }).response;\n return response?.status;\n }\n return undefined;\n}\n\nfunction extractAxiosData<T>(err: unknown): T | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { data?: T } }).response;\n return response?.data;\n }\n return undefined;\n}\n","// checkAccess/can/batchCheck over REST (D-08, FND-04, §1).\n//\n// Mirrors the Rust SDK's src/rest/authz.rs and\n// crates/axiam-api-rest/src/handlers/authz_check.rs exactly. tenant_id is\n// never sent in the body — the server derives it from the JWT (§5); the SDK\n// only sends X-Tenant-ID (already attached by session.ts's request\n// interceptor on every call). No client-side cache (D-08) — plain stateless\n// async functions.\n\nimport { mapHttpStatusToError, NetworkError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n AccessCheck,\n AccessDecision,\n BatchCheckAccessBodyWire,\n BatchCheckAccessResponseWire,\n CheckAccessBodyWire,\n CheckAccessResponseWire,\n} from './types.js';\n\nconst CHECK_PATH = '/api/v1/authz/check';\nconst BATCH_CHECK_PATH = '/api/v1/authz/check/batch';\n\nfunction toWireBody(check: AccessCheck): CheckAccessBodyWire {\n return {\n action: check.action,\n resource_id: check.resourceId,\n scope: check.scope,\n subject_id: check.subjectId,\n };\n}\n\nfunction fromWireDecision(wire: CheckAccessResponseWire): AccessDecision {\n return { allowed: wire.allowed, reason: wire.reason };\n}\n\n/**\n * `POST /api/v1/authz/check` (§1, FND-04).\n *\n * A 403 authz denial (server-side error, distinct from the `allowed: false`\n * decision the endpoint itself returns) is mapped to AuthzError, not treated\n * as a transport failure.\n */\nexport async function checkAccess(client: AxiamClient, check: AccessCheck): Promise<AccessDecision> {\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n return fromWireDecision(response.data);\n } catch (err) {\n throw mapAuthzError(err, check.action, check.resourceId);\n }\n}\n\n/**\n * `can` — alias for checkAccess targeting browser/UI scenarios (§1 note),\n * returning just the boolean `allowed` outcome.\n */\nexport async function can(client: AxiamClient, action: string, resourceId: string, scope?: string): Promise<boolean> {\n const decision = await checkAccess(client, { action, resourceId, scope });\n return decision.allowed;\n}\n\n/**\n * `POST /api/v1/authz/check/batch` (§1). Results are returned in the same\n * order as the input `checks` array (server-guaranteed ordering).\n */\nexport async function batchCheck(client: AxiamClient, checks: AccessCheck[]): Promise<AccessDecision[]> {\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n throw mapAuthzError(err);\n }\n}\n\nfunction mapAuthzError(err: unknown, action?: string, resourceId?: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: { message?: string } } }).response;\n if (response?.status !== undefined) {\n if (response.status === 403) {\n // Body (response.data) carries the server's own action/resource_id\n // for the denial (structured 403 body) — preferred by the mapper\n // over the call-args action/resourceId below when present.\n return mapHttpStatusToError(403, response.data?.message ?? 'authorization denied', {\n action,\n resourceId,\n body: response.data,\n });\n }\n return mapHttpStatusToError(response.status, response.data?.message ?? 'authz request failed', {\n action,\n resourceId,\n body: response.data,\n cause: err,\n });\n }\n }\n return new NetworkError('authz request failed', err);\n}\n","// AxiamClient — the isomorphic REST + auth core (D-01/D-25).\n//\n// Constructor validates the required tenant (§5), builds the SharedSession\n// (D-13), and installs the CSRF + reactive single-flight refresh\n// interceptors (D-05/D-07). REST method implementations (login/verifyMfa/\n// refresh/logout/checkAccess/can/batchCheck) are added by Task 2's\n// auth.ts/authz.ts, which extend this class's prototype.\n\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as authzMethods from './authz.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\n\n/**\n * The main entry point for the AXIAM TypeScript/JavaScript SDK — an\n * isomorphic (browser + Node) REST client for authentication and\n * authorization against an AXIAM server.\n *\n * @remarks\n * `AxiamClient` implements the SDK's cross-language behavioral contract\n * (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/\n * `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the\n * three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic\n * CSRF forwarding (§3), the required tenant context (§5), and a per-instance\n * single-flight refresh guard that de-duplicates concurrent token refreshes\n * (§9).\n *\n * A `tenantSlug` or `tenantId` is mandatory at construction — there is no\n * default tenant, and AXIAM is a multi-tenant system where every\n * authenticated call is scoped by the `X-Tenant-ID` header this client\n * injects on every request (§5). Session tokens never appear as a return\n * value or public property anywhere on this class: they arrive exclusively\n * via `httpOnly` cookies set by the server.\n *\n * @example\n * ```ts\n * const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });\n *\n * const result = await client.login('user@example.com', 'hunter2');\n * if (result.status === 'mfa_required') {\n * await client.verifyMfa(result.mfaToken, '123456');\n * }\n *\n * const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });\n * if (!decision.allowed) {\n * throw new Error(decision.reason ?? 'access denied');\n * }\n * ```\n */\nexport class AxiamClient {\n /** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */\n readonly session: SharedSession;\n\n /**\n * @param options client configuration (§5/§6).\n * @param session optional pre-built session to adopt instead of the default\n * browser `SharedSession`. This is the injection point for the Node\n * persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie\n * jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`\n * from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it\n * is adopted here, so httpOnly login/refresh cookies persist. When omitted\n * the browser `SharedSession` is built by default — the Node modules are\n * NEVER statically imported from this browser-safe module, so a `/rest`\n * browser bundle keeps pulling zero Node dependencies (SC#1).\n */\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n }\n\n /** `POST /api/v1/auth/login` (§1, D-18). */\n login(email: string, password: string): Promise<LoginResult> {\n return authMethods.login(this, email, password);\n }\n\n /** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */\n verifyMfa(mfaToken: string, code: string): Promise<LoginResult> {\n return authMethods.verifyMfa(this, mfaToken, code);\n }\n\n /** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */\n refresh(): Promise<void> {\n return authMethods.refresh(this);\n }\n\n /** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */\n logout(): Promise<void> {\n return authMethods.logout(this);\n }\n\n /** `POST /api/v1/authz/check` (§1, FND-04). */\n checkAccess(check: AccessCheck): Promise<AccessDecision> {\n return authzMethods.checkAccess(this, check);\n }\n\n /** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */\n can(action: string, resourceId: string, scope?: string): Promise<boolean> {\n return authzMethods.can(this, action, resourceId, scope);\n }\n\n /** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */\n batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]> {\n return authzMethods.batchCheck(this, checks);\n }\n}\n","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { wrapper } from 'axios-cookiejar-support';\nimport type { AxiosInstance } from 'axios';\n\n/** The `axiam_access` cookie name (httpOnly, path `/`). */\nexport const ACCESS_COOKIE = 'axiam_access';\n/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */\nexport const REFRESH_COOKIE = 'axiam_refresh';\n/** The `axiam_csrf` cookie name (JS-readable, path `/`). */\nexport const CSRF_COOKIE = 'axiam_csrf';\n\n/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */\nexport function createJar(): CookieJar {\n return new CookieJar();\n}\n\n/**\n * Wrap an axios instance with `axios-cookiejar-support` so the jar persists\n * `Set-Cookie` responses across requests and replays them on subsequent\n * requests to the same origin/path (§4). Mutates and returns the same\n * instance (matches `axios-cookiejar-support`'s documented in-place wrap).\n */\nexport function wrapAxios(instance: AxiosInstance, jar: CookieJar): AxiosInstance {\n const wrapped = wrapper(instance);\n wrapped.defaults.jar = jar;\n return wrapped;\n}\n\n/**\n * Read a single cookie's value out of the jar by name, for the given URL.\n * This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body\n * fallback exists on the wire).\n */\nexport async function extractCookieValue(\n jar: CookieJar,\n url: string,\n name: string,\n): Promise<string | undefined> {\n const cookies = await jar.getCookies(url);\n return cookies.find((c) => c.key === name)?.value;\n}\n","// TokenManager — Node-persona token state (CONTRACT.md §7, D-09/D-11/D-26).\n//\n// Tokens are read from the tough-cookie jar by name (the ONLY token-source\n// path — login/refresh response bodies carry no token fields; see\n// RESEARCH.md Area 3) and wrapped in Sensitive<T> immediately. A\n// synchronous, non-blocking `cachedAccessToken()` fast-path is provided for\n// the grpc-js interceptor's `start()`, which cannot await (Pitfall 3) —\n// mirrors the Rust SDK's src/token/manager.rs::cached_access_token exactly.\n\nimport type { CookieJar } from 'tough-cookie';\nimport { Sensitive } from '../core/index.js';\nimport { ACCESS_COOKIE, REFRESH_COOKIE, extractCookieValue } from './cookieJar.js';\n\n/** Path the server scopes the `axiam_refresh` cookie to (mirrors csrf.rs). */\nconst REFRESH_COOKIE_PATH = '/api/v1/auth/refresh';\n\n/** Tracks the access/refresh token pair for a Node session, kept in sync with the cookie jar after each REST call/refresh. */\nexport class TokenManager {\n readonly #jar: CookieJar;\n readonly #baseUrl: string;\n #tenantId: string | undefined;\n /**\n * Non-blocking cached copy of the current access token, kept in sync via\n * `syncFromJar()` after each REST call/refresh. Read via\n * `cachedAccessToken()` without ever touching the jar's async API — this\n * is the fast-path the grpc-js interceptor's synchronous `start()` needs\n * (Pitfall 3).\n */\n #cachedAccess: Sensitive<string> | null = null;\n\n constructor(jar: CookieJar, baseUrl: string, tenantId?: string) {\n this.#jar = jar;\n this.#baseUrl = baseUrl;\n this.#tenantId = tenantId;\n }\n\n /**\n * Synchronous, best-effort read of the last-known access token. Returns\n * `null` if no token has been cached yet (no request/refresh has\n * completed since construction, or `syncFromJar()` was never called).\n */\n cachedAccessToken(): Sensitive<string> | null {\n return this.#cachedAccess;\n }\n\n /**\n * Async read of the current `axiam_refresh` cookie value from the jar,\n * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL\n * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible\n * at the bare base URL).\n */\n async refreshTokenValue(): Promise<Sensitive<string> | null> {\n const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);\n return value === undefined ? null : new Sensitive(value);\n }\n\n /**\n * Refresh the in-memory cached access token from the jar. Call this after\n * every REST request/refresh so the synchronous gRPC-interceptor fast-path\n * (`cachedAccessToken()`) stays current (Pitfall 3).\n */\n async syncFromJar(): Promise<void> {\n const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);\n this.#cachedAccess = value === undefined ? null : new Sensitive(value);\n }\n\n /** The resolved tenant identifier (slug or UUID form), if known. */\n tenantId(): string | undefined {\n return this.#tenantId;\n }\n\n /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */\n setTenantId(tenantId: string): void {\n this.#tenantId = tenantId;\n }\n\n /** Clear all cached token state (used by logout()). */\n clear(): void {\n this.#cachedAccess = null;\n }\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist).\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /** Verify `token` against the cached JWKS (EdDSA only) and return its claims; rejects any invalid/expired/wrong-algorithm token. */\n verifyAccessToken(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * Build a verifier bound to `{baseUrl}/oauth2/jwks`. `jose` is loaded lazily\n * via dynamic `import()` (Pitfall 1 — CJS-safe); the remote JWKS itself is\n * also fetched/cached lazily by `jose`, not eagerly here.\n */\nexport function createVerifier(baseUrl: string): Verifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // the same createRemoteJWKSet cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent invalid-`kid` burst\n // against a cold cache must collapse to exactly ONE network fetch. Proven\n // (not just assumed) by `test/node/jwks.test.ts`'s \"collapses N concurrent\n // verifyAccessToken calls ... to exactly one JWKS fetch\" test, which mocks\n // global `fetch` with a call counter and fires 8 concurrent calls: jose's\n // `createRemoteJWKSet` (see jose's `RemoteJWKSet.reload()`,\n // `this.#pendingFetch ||= fetchJwks(...).then(...)`) ALREADY holds its own\n // internal lazy-promise-singleton around the underlying fetch, so\n // concurrent callers reaching a cold/unknown-kid getter share the same\n // in-flight fetch promise natively — no additional `inFlightFetch` guard\n // is added here (it would be redundant). If a future `jose` upgrade\n // removes that internal guarantee, the burst test above will start\n // failing and an explicit guard (mirroring `jwksPromise`'s shape) must be\n // added at that point.\n let jwksPromise: Promise<ReturnType<typeof import('jose').createRemoteJWKSet>> | null = null;\n\n async function getJwks() {\n if (!jwksPromise) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n jwksPromise = import('jose').then(({ createRemoteJWKSet }) =>\n createRemoteJWKSet(new URL(`${baseUrl}${JWKS_PATH}`), {\n cooldownDuration: COOLDOWN_DURATION_MS,\n timeoutDuration: TIMEOUT_DURATION_MS,\n }),\n );\n }\n return jwksPromise;\n }\n\n return {\n async verifyAccessToken(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Explicit algorithm allowlist — never trust the token's own `alg`\n // header; defense against algorithm-confusion attacks (T-17-14).\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n };\n}\n","// createNodeSession — extends the 17-02 SharedSession with the Node\n// persona's auth internals (D-13).\n//\n// Builds the same REST SharedSession the browser persona uses, then swaps\n// in a tough-cookie jar (via wrapAxios) so httpOnly Set-Cookie tokens\n// persist, and attaches a TokenManager + JWKS verifier. This is the ONE\n// shared session object gRPC (interceptor.ts/callWithRefresh.ts) and REST\n// both operate on — the single-flight refresh guard (`session.refreshGuard`,\n// a per-session instance created in the SharedSession constructor, CR-02)\n// is therefore transparently shared across both transports FOR THIS\n// SESSION ONLY, since both call it with an equivalent `POST\n// /api/v1/auth/refresh` closure. A different NodeSession/SharedSession\n// instance gets its own independent guard — refreshes never cross-wire\n// between sessions.\n\nimport type { CookieJar } from 'tough-cookie';\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from '../rest/session.js';\nimport { AxiamClient } from '../rest/client.js';\nimport { CSRF_COOKIE, createJar, extractCookieValue, wrapAxios } from './cookieJar.js';\nimport { TokenManager } from './tokenManager.js';\nimport { createVerifier, type Verifier } from './jwks.js';\n\n/** Node-only {@link SharedSession} adding a {@link TokenManager} and a JWKS {@link Verifier} for local (offline) access-token verification. */\nexport class NodeSession extends SharedSession {\n /** Manages the access/refresh token pair backing this session. */\n readonly tokenManager: TokenManager;\n /** Local JWKS verifier for validating access tokens without a server round-trip. */\n readonly jwksVerifier: Verifier;\n readonly #jar: CookieJar;\n\n constructor(\n options: AxiamClientOptions,\n base: SharedSession,\n tokenManager: TokenManager,\n jwksVerifier: Verifier,\n jar: CookieJar,\n ) {\n super(options, base.axios, base.tenantHeaderValue);\n this.tokenManager = tokenManager;\n this.jwksVerifier = jwksVerifier;\n this.#jar = jar;\n }\n\n /**\n * Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this\n * session's per-instance `refreshGuard` (inherited from SharedSession) by\n * both REST's reactive interceptor (rest/interceptors.ts) and gRPC's\n * callWithRefresh — since `refreshGuard` is scoped to THIS session\n * instance (CR-02, D-13), both transports share exactly one in-flight\n * refresh for this session regardless of which one triggers it, while\n * remaining fully independent from any other session's guard.\n */\n doRefresh = async (): Promise<void> => {\n await this.axios.post('/api/v1/auth/refresh', {});\n await this.tokenManager.syncFromJar();\n // The refresh response may rotate the axiam_csrf cookie — resync\n // session.csrfToken from the jar so the next state-changing request\n // still forwards a valid X-CSRF-Token (CR-01).\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a\n * successful login()/verifyMfa(). Refreshes the cached access token (so\n * the gRPC interceptor's synchronous fast-path is current immediately\n * after login) and reads the `axiam_csrf` cookie out of the jar into\n * `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.\n */\n onAuthenticated = async (): Promise<void> => {\n await this.tokenManager.syncFromJar();\n await this.#syncCsrfFromJar();\n };\n\n async #syncCsrfFromJar(): Promise<void> {\n this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);\n }\n}\n\n/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */\nexport function createNodeSession(options: AxiamClientOptions): NodeSession {\n const base = createSession(options);\n const jar = createJar();\n wrapAxios(base.axios, jar);\n\n const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);\n const jwksVerifier = createVerifier(options.baseUrl);\n\n return new NodeSession(options, base, tokenManager, jwksVerifier, jar);\n}\n\n/**\n * Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node\n * counterpart to `new AxiamClient(options)` (which builds the browser\n * `SharedSession` with no cookie jar): it constructs a `NodeSession`\n * (tough-cookie jar + CSRF/refresh token sync) and adopts it via the\n * `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens\n * from login/refresh persist and every post-login REST call authenticates\n * correctly under Node.\n *\n * Lives in this Node-only module (reachable via the `axiam-sdk/node` and\n * `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`\n * entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).\n * The returned client shares the single session with any `AuthzGrpcClient`\n * built from the same `NodeSession`.\n */\nexport function createNodeClient(options: AxiamClientOptions): AxiamClient {\n return new AxiamClient(options, createNodeSession(options));\n}\n"]}
@@ -813,7 +813,9 @@ function createVerifier(baseUrl) {
813
813
 
814
814
  // src/node/session.ts
815
815
  var NodeSession = class extends SharedSession {
816
+ /** Manages the access/refresh token pair backing this session. */
816
817
  tokenManager;
818
+ /** Local JWKS verifier for validating access tokens without a server round-trip. */
817
819
  jwksVerifier;
818
820
  #jar;
819
821
  constructor(options, base, tokenManager, jwksVerifier, jar) {