axiam-sdk 1.0.0-alpha40 → 1.0.0-alpha41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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/core/decisionMemo.ts","../src/core/telemetry.ts","../src/core/telemetryReporter.ts","../src/rest/session.ts","../src/rest/interceptors.ts","../src/rest/auth.ts","../src/core/opaque.ts","../src/rest/opaque.ts","../src/rest/retry.ts","../src/rest/authz.ts","../src/rest/webauthn.ts","../src/rest/accountLifecycle.ts","../src/rest/client.ts","../src/rest/webauthnErrors.ts"],"names":["axios","response","wire","axiosStatus","post","expose","serverMessage"],"mappings":";;;;;;;;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU/B,MAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,UAAA,CAAU,SAAS,CAAA;AAAA,EACjD;AACF;AA0CO,IAAM,kBAAA,GAAN,MAAM,mBAAA,SAA2B,SAAA,CAAU;AAAA;AAAA,EAEvC,KAAA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AAA;AAAS,IACf,KAAK,WAAA;AACH,MAAA,OAAO,4DAAA;AAAA,IACT,KAAK,oBAAA;AACH,MAAA,OAAO,8GAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,8DAAA;AAAA,IACT,KAAK,aAAA;AACH,MAAA,OAAO,6GAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,yCAAA;AAAA;AAEb;AAGA,SAAS,UAAU,GAAA,EAAkC;AACnD,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,MAAA;AACpD,EAAA,MAAM,OAAQ,GAAA,CAA2B,IAAA;AACzC,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,MAAA;AAC3C","file":"index.js","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\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 {\n AuthError,\n AuthzError,\n NetworkError,\n OAuthProtocolError,\n type AxiamError,\n} 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 request URL (absolute or path-only) the error came from, when\n * available. Load-bearing for the two **endpoint-qualified** rows of §2's\n * HTTP table (added by contract 1.4): a `400`/`401` carrying an\n * `OAuth2ErrorResponse` body maps to `OAuthProtocolError` only when it came\n * from an `/oauth2/*` endpoint. Omitting it simply keeps the generic rows.\n */\n url?: string;\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 * The RFC 6749 error body shape (`OAuth2ErrorResponse` in `openapi.json`)\n * returned by AXIAM's `/oauth2/*` endpoints. Both fields are required by the\n * schema.\n */\nexport interface OAuth2ErrorResponseWire {\n /** RFC 6749 error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable description of the failure. */\n error_description: string;\n}\n\n/**\n * Path prefix identifying AXIAM's OAuth2 endpoint family (`/oauth2/token`,\n * `/oauth2/introspect`, `/oauth2/revoke`, …). The two endpoint-qualified §2\n * rows apply only to URLs whose path starts with it.\n */\nconst OAUTH2_PATH_PREFIX = '/oauth2/';\n\n/**\n * Whether `url` targets an `/oauth2/*` endpoint. Accepts both an absolute URL\n * (as taken from the discovery document) and a bare path (as axios request\n * configs carry), and never throws on a malformed value — an unparseable URL\n * simply falls back to a substring test, so a mis-shaped URL can only ever\n * *fail* to qualify for the OAuth2 rows, never wrongly qualify for them.\n */\nexport function isOAuth2EndpointUrl(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n // A relative path has no base here, so `URL` throws and we fall through.\n return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);\n } catch {\n return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);\n }\n}\n\n/**\n * Narrow a parsed response body to {@link OAuth2ErrorResponseWire}. Both\n * `error` and `error_description` must be present and string-typed — a body\n * that carries only one of them is NOT an `OAuth2ErrorResponse` and keeps the\n * generic §2 mapping (better a generic error than a fabricated\n * `error_description`).\n */\nexport function isOAuth2ErrorBody(body: unknown): body is OAuth2ErrorResponseWire {\n if (body === null || typeof body !== 'object') {\n return false;\n }\n const record = body as Record<string, unknown>;\n return typeof record.error === 'string' && typeof record.error_description === 'string';\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 * | 400 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 401 | AuthError |\n * | 401 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * Where two rows match the same response the more specific\n * (endpoint- and body-qualified) row wins, per §2 — so the two\n * `OAuthProtocolError` rows are evaluated first. They require BOTH an\n * `/oauth2/*` `ctx.url` AND an `OAuth2ErrorResponse`-shaped `ctx.body`;\n * anything else keeps the generic mapping.\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 // Endpoint-qualified rows first (§2 \"the more specific row wins\",\n // §12.3 rule 3). `message` is deliberately ignored here: the contract fixes\n // OAuthProtocolError's message to \"<error>: <error_description>\".\n if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {\n return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);\n }\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\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// 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/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\nimport type { TelemetryHook } from './telemetry.js';\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /**\n * Human-readable organization identifier (CONTRACT.md §5). Optional at\n * construction, but the server REQUIRES an org context on login — a tenant\n * slug is only unique *within* an organization — so a client that omits both\n * `orgSlug` and `orgId` will fail login with a 400/401. Forwarded as\n * `org_slug` in the login body. Mutually exclusive with {@link orgId}\n * (if both are given, `orgId` wins, mirroring how `tenantSlug`/`tenantId`\n * resolve).\n */\n orgSlug?: string;\n /**\n * Organization UUID (CONTRACT.md §5). Optional at construction (see\n * {@link orgSlug}). When supplied it is forwarded as `org_id` on login and\n * used to build the `refresh` body; otherwise the resolved organization UUID\n * is decoded from the authenticated session's access-token `org_id` claim\n * after the first successful login. Mutually exclusive with {@link orgSlug}.\n */\n orgId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /**\n * Enable the CONTRACT.md §16 bounded read-only retry policy. **Default:\n * `true`.**\n *\n * Set `false` to make every operation exactly one attempt. That is the right\n * choice for a caller who owns their own retry layer — they know their\n * deadline and this SDK does not — but it is not a way to make failures\n * quieter: a transient `NetworkError` simply surfaces immediately.\n *\n * §16.1 permits this switch but forbids raising the attempt cap, base delay\n * or delay cap above the contract's values, so there is no knob for those:\n * eleven SDKs agreeing on one table is the point.\n */\n retryEnabled?: boolean;\n /**\n * Enable the CONTRACT.md §17 client-side decision memo, in milliseconds.\n * **Default: `0`, which means disabled** — not \"cache for zero milliseconds\".\n *\n * ## What you are accepting\n *\n * The staleness bound is this TTL, **in both directions**. A grant revoked on\n * the server can still read as allowed for up to the TTL, and a grant just\n * added can still read as denied for up to the TTL.\n *\n * **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role\n * and immediately re-checks is the case that breaks, and it breaks silently.\n * If that is your workload, leave this off.\n *\n * Clamped to 5000 ms rather than rejected, so asking for a minute gets you\n * five seconds. Allows and denies are memoized identically (asymmetric\n * caching leaks the outcome through latency), failures are never memoized,\n * and the memo is cleared on any credential change.\n */\n decisionMemoTtlMs?: number;\n /**\n * Install a CONTRACT.md §19 telemetry sink.\n *\n * Receives request start/end, §16 retry and §9 refresh events, so metrics can\n * be wired without this package depending on any metrics library. See\n * `examples/telemetry-hook.ts`.\n *\n * A hook that throws cannot fail the operation that fired it (§19.2 rule 2),\n * and no event payload can carry a token — {@link TelemetryEvent} is a closed\n * union with a fixed field set (§19.2 rule 3). Invoked on the calling path,\n * so it must not block; buffer on your side if you need async delivery.\n */\n telemetryHook?: TelemetryHook;\n /**\n * PEM-encoded client-certificate chain for mutual TLS (§6.1). Presented to\n * the server to authenticate an IoT device / service account. MUST be\n * provided together with {@link AxiamClientOptions.clientKey}. Node only —\n * ignored in the browser (browsers cannot present a client certificate from\n * JS). Presenting a client certificate NEVER relaxes server verification.\n */\n clientCert?: string;\n /**\n * PEM-encoded private key (PKCS#8 or PKCS#1) matching {@link\n * AxiamClientOptions.clientCert} (§6.1). Secret material: it is passed\n * straight to the Node TLS stack and is never retained on a public property,\n * logged, or serialized (§7). MUST be provided together with `clientCert`.\n * Node only — ignored in the browser.\n */\n clientKey?: string;\n /**\n * Expected `iss` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 5). Optional and unset by default — the rule is conditional on\n * configuration, and the SDK never hardcodes an issuer. When set, the §10\n * middleware rejects a token whose `iss` differs.\n */\n expectedIssuer?: string;\n /**\n * Expected `aud` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 6). Optional and unset by default. A resource server guarding\n * user-facing routes SHOULD set `\"axiam:user\"`; a machine-to-machine one\n * `\"axiam:m2m\"`. When set, the §10 middleware rejects a token whose `aud`\n * does not contain it.\n */\n expectedAudience?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** PEM header that must appear in a certificate chain (§6/§6.1). */\nexport const CERT_PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * PEM header for a private key — PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1\n * (`BEGIN RSA PRIVATE KEY`), or an EC key (`BEGIN EC PRIVATE KEY`) (§6.1).\n */\nconst PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;\n\n/**\n * A validated mTLS client identity (§6.1). The private key is held behind\n * {@link Sensitive} so it can never leak through a debug/log/serialize path\n * (§7); call `key.expose()` only at the point of handing it to the TLS stack.\n */\nexport interface ClientIdentity {\n /** PEM certificate chain (not secret). */\n cert: string;\n /** PEM private key, redaction-wrapped (§7). */\n key: Sensitive<string>;\n}\n\n/**\n * Validate the §6.1 client-certificate options and, when configured, return\n * the resolved identity. Throws at construction time (consistent with §6's\n * PEM-only rule) when:\n * - exactly one of clientCert/clientKey is present (they are all-or-nothing);\n * - clientCert is not a PEM certificate chain;\n * - clientKey is not a PEM private key.\n *\n * Returns `undefined` when neither is configured. This validation runs on\n * every persona (including the browser, which then ignores the identity) so\n * construction fails fast and identically everywhere.\n */\nexport function resolveClientIdentity(options: {\n clientCert?: string;\n clientKey?: string;\n}): ClientIdentity | undefined {\n const hasCert = options.clientCert !== undefined;\n const hasKey = options.clientKey !== undefined;\n if (hasCert !== hasKey) {\n throw new Error(\n 'clientCert and clientKey must be provided together for mutual TLS ' +\n '(one was given without the other) (CONTRACT.md §6.1).',\n );\n }\n if (!hasCert || !hasKey) {\n return undefined;\n }\n if (!options.clientCert!.includes(CERT_PEM_MARKER)) {\n throw new Error(\n 'clientCert must be a PEM-encoded certificate chain (expected to contain ' +\n '\"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6.1).',\n );\n }\n if (!PRIVATE_KEY_PEM_RE.test(options.clientKey!)) {\n throw new Error(\n 'clientKey must be a PEM-encoded private key (expected to contain ' +\n '\"-----BEGIN PRIVATE KEY-----\" or \"-----BEGIN RSA PRIVATE KEY-----\") ' +\n '(CONTRACT.md §6.1).',\n );\n }\n return { cert: options.clientCert!, key: new Sensitive(options.clientKey!) };\n}\n","// Client-side decision memo — CONTRACT.md §17.\n//\n// **Disabled by default.** §11.2 rule 6's ban on caching allow/deny decisions\n// is still the default behaviour; this is the single opt-in exception that\n// section carves out, and a caller has to switch it on having read the cost.\n//\n// # What it costs\n//\n// The staleness bound is the TTL, **in both directions**. A grant revoked on\n// the server can still read as allowed for up to the TTL, and a grant just\n// added can still read as denied for up to the TTL. That second direction is\n// the one that surprises people: **reads-your-own-writes is not guaranteed.**\n// An admin UI that grants a role and immediately re-checks is the case that\n// breaks, and it breaks silently.\n//\n// This mirrors the server's own bound rather than inventing a second staleness\n// story — AXIAM__AUTHZ__DECISION_CACHE_TTL_SECS (default 5 s) makes the same\n// trade server-side. One deliberate difference: the server's setting is an\n// unclamped integer, so an operator can configure a multi-hour staleness\n// window. MAX_TTL_MS clamps this one at 5 s, because the client has no reason\n// to repeat that.\n\nimport type { AccessDecision } from './authz.js';\nimport type { TelemetryDispatcher } from './telemetry.js';\n\n/**\n * The §17.1 rule 2 ceiling. A configured TTL above this is clamped, not\n * rejected: a caller who asked for 60 s wants caching, and silently giving them\n * the maximum safe value beats failing construction.\n */\nexport const MAX_TTL_MS = 5_000;\n\n/**\n * Entry cap before FIFO eviction (§17.1 rule 8). The memo is a latency\n * optimisation, so dropping an entry is always correct.\n */\nconst MAX_ENTRIES = 1024;\n\n/**\n * The §17.1 rule 3 key: all four components, with absent distinguished from\n * present.\n *\n * `\\u001f` (unit separator) joins the parts because it cannot appear in an\n * action, a UUID or a scope, so no combination of values can forge a\n * collision. `\\u0000` marks an *absent* optional, which is why an absent scope\n * can never collide with a present one — a memo that let them collide would\n * answer a narrower question with a broader answer.\n */\nexport function memoKey(check: {\n action: string;\n resourceId: string;\n scope?: string;\n subjectId?: string;\n}): string {\n const ABSENT = '\\u0000';\n return [\n check.subjectId ?? ABSENT,\n check.resourceId,\n check.action,\n check.scope ?? ABSENT,\n ].join('\\u001f');\n}\n\ninterface Entry {\n decision: AccessDecision;\n storedAt: number;\n}\n\n/**\n * A bounded, TTL-clamped decision memo.\n *\n * `ttlMs === 0` means **disabled** — not \"cache for zero milliseconds\". That is\n * the default, and both `get` and `set` become no-ops.\n */\nexport class DecisionMemo {\n private readonly ttlMs: number;\n private readonly entries = new Map<string, Entry>();\n\n /**\n * @param ttlMs requested TTL in milliseconds; `0` disables the memo and any\n * value above {@link MAX_TTL_MS} is clamped to it.\n * @param now injected clock, so the TTL can be tested without waiting.\n */\n constructor(\n ttlMs = 0,\n /** Injected so the TTL can be tested without waiting. */\n private readonly now: () => number = Date.now,\n ) {\n this.ttlMs = Math.min(Math.max(ttlMs, 0), MAX_TTL_MS);\n }\n\n /** Whether this memo does anything. `false` for the default configuration. */\n get enabled(): boolean {\n return this.ttlMs > 0;\n }\n\n /** The effective TTL after clamping. */\n get effectiveTtlMs(): number {\n return this.ttlMs;\n }\n\n /** A live decision for `key`, if one is memoized and unexpired. */\n get(key: string): AccessDecision | undefined {\n if (!this.enabled) return undefined;\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (this.now() - entry.storedAt >= this.ttlMs) {\n this.entries.delete(key);\n return undefined;\n }\n // Returned whole, including `reasonCode`: §17.1 rule 5 forbids returning\n // `allowed` while dropping the code, which would make the field\n // intermittently absent — worse than never having had it.\n return entry.decision;\n }\n\n /**\n * Memoize a decision the server actually returned.\n *\n * Callers must only reach here on success. §17.1 rule 7 forbids\n * negative-caching a failure: memoizing a transport error as a deny would\n * turn a blip into a TTL-long outage, and memoizing it as an allow is\n * unthinkable.\n */\n set(key: string, decision: AccessDecision): void {\n if (!this.enabled) return;\n // Re-inserting moves the key to the end of Map iteration order, which is\n // what makes the eviction below FIFO by insertion.\n this.entries.delete(key);\n this.entries.set(key, { decision, storedAt: this.now() });\n while (this.entries.size > MAX_ENTRIES) {\n const oldest = this.entries.keys().next().value;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n /**\n * Drop every entry (§17.1 rule 9).\n *\n * Called on login, verifyMfa, refresh and logout. Entries are keyed by\n * subject, not by session, so a re-authentication as a *different* principal\n * would otherwise read the previous principal's decisions.\n */\n clear(): void {\n this.entries.clear();\n }\n\n /**\n * Emit a {@link ConfigClampedEvent} if the requested TTL was clamped (§19.2\n * rule 6).\n *\n * This is the clamp that matters most to get right: an operator who set a\n * 60-second TTL believes their staleness bound is 60 seconds. It is five, and\n * without this event nothing anywhere says so.\n *\n * Nothing is emitted when the requested value was already inside the limit,\n * or when the memo is disabled — an event that fires when nothing happened\n * trains its reader to ignore it.\n */\n reportClamp(requestedMs: number, telemetry: TelemetryDispatcher): void {\n if (!telemetry.installed || requestedMs <= 0 || requestedMs === this.ttlMs) return;\n telemetry.emit({\n type: 'configClamped',\n setting: 'decisionMemoTtlMs',\n requested: String(requestedMs),\n effective: String(this.ttlMs),\n contractReference: '§17.1 rule 2',\n });\n }\n\n /** Entry count, for tests. */\n get size(): number {\n return this.entries.size;\n }\n}\n","// Telemetry hooks — CONTRACT.md §19.\n//\n// An optional callback surface so callers can wire OpenTelemetry, Prometheus,\n// or a log line **without this package depending on any of them**. No hook\n// installed costs one undefined check per request.\n//\n// Two rules from §19.2 are enforced here rather than left to documentation:\n//\n// * A hook cannot break the SDK. `TelemetryDispatcher.emit` swallows anything\n// a sink throws, so a broken hook cannot fail an authorization check.\n// * No secrets, ever. `TelemetryEvent` is a closed discriminated union with a\n// fixed field set and no index signature, so there is no way to put a token\n// into a payload bound for a metrics backend. The type system, not a review\n// comment, is what keeps them out.\n\n/** Why a request finished. */\nexport type Outcome = 'success' | 'failure';\n\n/** Whether this caller performed a §9 refresh or waited on another's. */\nexport type RefreshRole = 'leader' | 'follower';\n\n/** Emitted before an outbound call leaves the SDK. */\nexport interface RequestStartEvent {\n /** Discriminant. */\n type: 'requestStart';\n /** Canonical operation name, e.g. `checkAccess`. */\n operation: string;\n /** HTTP method. */\n method: string;\n /**\n * Path **template** — `/api/v1/authz/check`, never a URL with ids\n * substituted in. A metric label carrying a UUID is a cardinality bomb.\n */\n pathTemplate: string;\n /** 1 for the first attempt, incrementing per §16 retry. */\n attempt: number;\n}\n\n/** Emitted after a call completes, success or failure. */\nexport interface RequestEndEvent {\n /** Discriminant. */\n type: 'requestEnd';\n /** Canonical operation name. */\n operation: string;\n /** HTTP method. */\n method: string;\n /** Path template — see {@link RequestStartEvent.pathTemplate}. */\n pathTemplate: string;\n /** Attempt this event closes. */\n attempt: number;\n /** HTTP status, or `undefined` when the call never got a response. */\n status?: number;\n /** Wall-clock duration of this attempt, in milliseconds. */\n durationMs: number;\n /** Success or failure. */\n outcome: Outcome;\n}\n\n/**\n * Emitted before each §16 retry wait.\n *\n * §16.5 requires this: a retried-then-succeeded operation is otherwise\n * invisible — the caller sees a slow success and no signal that the server is\n * failing. That silence is the standing objection to automatic retry.\n */\nexport interface RetryEvent {\n /** Discriminant. */\n type: 'retry';\n /** Canonical operation name. */\n operation: string;\n /** The attempt that just failed. */\n attempt: number;\n /** The delay about to be taken, after jitter and any `Retry-After`. */\n delayMs: number;\n /** Redacted failure description. Never carries a token (§2 redaction rules). */\n reason: string;\n}\n\n/** Emitted around a §9 single-flight refresh. */\nexport interface RefreshEvent {\n /** Discriminant. */\n type: 'refresh';\n /** Whether this caller performed the refresh or waited on another's. */\n role: RefreshRole;\n /** How long the refresh (or the wait for one) took, in milliseconds. */\n durationMs: number;\n}\n\n/**\n * Emitted at construction, once per caller-supplied setting the SDK clamped\n * (§19.1, §19.2 rule 6).\n *\n * Two places in the contract require clamping rather than rejecting: §16.1's\n * attempt cap, base delay and delay cap, and §17.1 rule 2's memo TTL. Both\n * clamps are right — rejecting would break a caller whose configuration was\n * merely optimistic, and honoring would let one client become the herd §16\n * exists to prevent. Doing it *silently* is the part that is wrong.\n *\n * An operator who set a 60-second memo TTL believes they have one. They have\n * five seconds, and their staleness reasoning is off by a factor of twelve with\n * nothing anywhere to say so.\n *\n * Not emitted for a value already within its limit: an event that fires when\n * nothing happened trains its reader to ignore it.\n */\nexport interface ConfigClampedEvent {\n /** Discriminant. */\n type: 'configClamped';\n /** The setting's name, e.g. `decisionMemoTtlMs`. */\n setting: string;\n /** The value the caller asked for, rendered. */\n requested: string;\n /** The value actually in force, rendered. */\n effective: string;\n /** The §-reference for the limit, e.g. `§17.1 rule 2`. */\n contractReference: string;\n}\n\n/** A §19 telemetry event. Closed union — see the file header for why. */\nexport type TelemetryEvent =\n | RequestStartEvent\n | RequestEndEvent\n | RetryEvent\n | RefreshEvent\n | ConfigClampedEvent;\n\n/**\n * A caller-supplied telemetry sink (§19).\n *\n * Invoked on the calling path, so it must not block: §19.2 rule 4 makes\n * buffering the caller's job so they can pick the policy. Every mature metrics\n * library already buffers.\n */\nexport type TelemetryHook = (event: TelemetryEvent) => void;\n\n/**\n * Internal dispatcher. `undefined` is the overwhelmingly common case and costs\n * one check.\n */\nexport class TelemetryDispatcher {\n constructor(private readonly hook?: TelemetryHook) {}\n\n /**\n * Emit an event, swallowing anything the caller's hook throws.\n *\n * §19.2 rule 2: telemetry is not permitted to fail an authorization check.\n */\n emit(event: TelemetryEvent): void {\n if (!this.hook) return;\n try {\n this.hook(event);\n } catch {\n // Deliberately swallowed. A hook that throws is the caller's bug, and\n // surfacing it here would turn a metrics problem into an authorization\n // failure.\n }\n }\n\n /** Whether a hook is installed. */\n get installed(): boolean {\n return this.hook !== undefined;\n }\n}\n","// Request-pair helper for CONTRACT.md §19.\n//\n// Kept apart from `telemetry.ts` (which is pure event types + the dispatcher)\n// so the browser bundle can import the types without pulling timing code it\n// does not use.\n\nimport { TelemetryDispatcher, type Outcome } from './telemetry.js';\n\n/** Closes a §19 request pair. Call exactly once, on every exit path. */\nexport type FinishRequest = (status: number | undefined, outcome: Outcome) => void;\n\n/**\n * Emits the §19 `requestStart`/`requestEnd` pair around one **attempt**.\n *\n * Per attempt, not per logical call: §19.2 rule 5 requires a caller to be able\n * to count real wire calls from the events, which one pair per operation would\n * hide — a retried call would look like a single slow one.\n */\nexport class TelemetryReporter {\n /** @param dispatcher the sink these events are emitted to. */\n constructor(\n /** The underlying §19 dispatcher. */\n readonly dispatcher: TelemetryDispatcher,\n ) {}\n\n /**\n * Emit `requestStart` and return the function that emits its `requestEnd`.\n *\n * `pathTemplate` must be the route constant — `/api/v1/authz/check`, never a\n * path with ids substituted in. A metric label carrying a UUID is a\n * cardinality bomb.\n */\n startRequest(operation: string, method: string, pathTemplate: string, attempt = 1): FinishRequest {\n if (!this.dispatcher.installed) {\n // Fast path: no hook, no timing work at all.\n return () => {};\n }\n this.dispatcher.emit({ type: 'requestStart', operation, method, pathTemplate, attempt });\n const started = Date.now();\n return (status, outcome) => {\n this.dispatcher.emit({\n type: 'requestEnd',\n operation,\n method,\n pathTemplate,\n attempt,\n status,\n durationMs: Date.now() - started,\n outcome,\n });\n };\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, ClientIdentity, RefreshGuard } from '../core/index.js';\nimport {\n CERT_PEM_MARKER,\n createRefreshGuard,\n DEFAULT_CONNECT_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n resolveClientIdentity,\n} from '../core/index.js';\n\nconst PEM_MARKER = CERT_PEM_MARKER;\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 /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */\n readonly tenantId: string | undefined;\n /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */\n readonly tenantSlug: string | undefined;\n /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */\n readonly orgId: string | undefined;\n /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */\n readonly orgSlug: string | undefined;\n /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */\n readonly expectedIssuer: string | undefined;\n /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */\n readonly expectedAudience: string | undefined;\n /**\n * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`\n * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config\n * when the UUID was supplied, then updated from the access-token `tenant_id`\n * claim after each successful login/refresh (Node persona only — the browser\n * cannot read the httpOnly access-token cookie).\n */\n resolvedTenantId: string | undefined;\n /**\n * Resolved organization UUID used to build the `refresh` body. Seeded from\n * `orgId` config, then updated from the access-token `org_id` claim after a\n * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.\n */\n resolvedOrgId: string | undefined;\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.tenantId = options.tenantId;\n this.tenantSlug = options.tenantSlug;\n this.orgId = options.orgId;\n this.orgSlug = options.orgSlug;\n this.expectedIssuer = options.expectedIssuer;\n this.expectedAudience = options.expectedAudience;\n // Seed the resolved UUIDs from any UUID-form config so the browser persona\n // (which cannot decode the httpOnly access token) can still build a valid\n // refresh body. The Node persona later overwrites these from the\n // access-token claims (NodeSession#resolveIdentifiersFromToken).\n this.resolvedTenantId = options.tenantId;\n this.resolvedOrgId = options.orgId;\n this.refreshGuard = createRefreshGuard();\n }\n\n /**\n * Build the `POST /api/v1/auth/refresh` request body (§1). The server's\n * `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this\n * emits the resolved UUIDs — from the access-token claims after login, or\n * from UUID-form construction options as a fallback. Fields that could not\n * be resolved are omitted (the server then answers with a clear 400), rather\n * than sending a slug where a UUID is required.\n */\n buildRefreshBody(): Record<string, string> {\n const body: Record<string, string> = {};\n if (this.resolvedTenantId) {\n body.tenant_id = this.resolvedTenantId;\n }\n if (this.resolvedOrgId) {\n body.org_id = this.resolvedOrgId;\n }\n return body;\n }\n\n /**\n * Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the\n * configured tenant and organization identifiers (UUID or slug form) in\n * addition to the credentials — the server resolves the workspace from the\n * body, not the `X-Tenant-ID` header, and rejects a login that omits org\n * context. Undefined identifiers are omitted.\n */\n buildLoginBody(email: string, password: string): Record<string, string> {\n const body: Record<string, string> = { username_or_email: email, password };\n if (this.tenantId) {\n body.tenant_id = this.tenantId;\n }\n if (this.tenantSlug) {\n body.tenant_slug = this.tenantSlug;\n }\n if (this.orgId) {\n body.org_id = this.orgId;\n }\n if (this.orgSlug) {\n body.org_slug = this.orgSlug;\n }\n return body;\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` carrying the customCa server-trust PEM\n * (§6) and/or the mTLS client identity (§6.1). Guarded by\n * `typeof process !== 'undefined'` as a CAPABILITY guard (Node has node:https\n * available), NOT a persona-sniffing branch — browsers ignore both customCa\n * and the client certificate entirely since the platform manages TLS itself.\n *\n * The client cert/key (§6.1) is an ADDITIVE client credential: it is passed\n * as `{ cert, key }` alongside `{ ca }` and NEVER touches `rejectUnauthorized`\n * — strict server verification stays at its secure default. The private key is\n * exposed from its {@link ClientIdentity} `Sensitive` wrapper only here, at the\n * point of handing it to the TLS stack, and is not retained anywhere else.\n */\nfunction loadNodeHttps(): typeof import('node:https') {\n // Node >= 20.16 / >= 22.3: `process.getBuiltinModule` loads a builtin\n // SYNCHRONOUSLY with no module system involved — no `import`, no `require`,\n // nothing for a bundler to rewrite. That is the whole point here: this file\n // is shared with the browser-safe `.`/`/rest` entries, so it must never\n // statically reference a Node builtin, yet the Node persona needs one\n // synchronously (buildSession is called from a constructor).\n //\n // The previous `require('node:https')` satisfied the first constraint but\n // not the second: tsup rewrites a bare `require` in ESM output into a shim\n // that throws `Dynamic require of \"https\" is not supported`, so under\n // genuine Node ESM — which is what `axiam-sdk/node`'s `import` condition\n // resolves to — EVERY call needing customCa or a client certificate failed\n // before the TLS handshake. It is reached off `process`, which the caller\n // has already capability-guarded, so a browser bundle never evaluates it.\n const getBuiltinModule = (\n process as unknown as { getBuiltinModule?: (id: string) => unknown }\n ).getBuiltinModule;\n if (typeof getBuiltinModule === 'function') {\n return getBuiltinModule.call(process, 'node:https') as typeof import('node:https');\n }\n // Older Node (the package still declares engines.node >= 18). `require` is\n // real in the CJS build, so this keeps working there; in the ESM build it is\n // the throwing shim, and the catch turns that into an error that says what\n // to actually do instead of leaking a bundler implementation detail.\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require('node:https') as typeof import('node:https');\n } catch {\n throw new Error(\n `customCa and clientCert require Node's https module, which this ESM build cannot load on Node ${process.version}: ` +\n 'process.getBuiltinModule is unavailable (added in Node 20.16 / 22.3) and `require` does not exist in an ES module. ' +\n 'Upgrade Node to >= 20.16, or load the CommonJS build (CONTRACT.md §6 / §6.1).',\n );\n }\n}\n\nexport interface NodeTlsOptions {\n /** §6 server-trust PEM bundle. */\n ca?: string;\n /** §6.1 client-certificate chain (PEM). */\n cert?: string;\n /** §6.1 private key (PEM). Secret material — never logged or retained. */\n key?: string;\n}\n\n/**\n * The TLS material for a Node agent, or `undefined` when there is nothing to\n * configure. `rejectUnauthorized` is deliberately absent: strict server\n * verification stays at its secure default and this object never carries a\n * TLS-bypass switch (§6).\n *\n * Split out from {@link maybeBuildHttpsAgent} because the Node persona cannot\n * use a plain `https.Agent` at all — see {@link resolveNodeTlsOptions}.\n */\nfunction tlsOptionsFrom(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): NodeTlsOptions | undefined {\n if (!customCa) {\n // Still short-circuit only when there is nothing to configure at all.\n if (!identity) {\n return undefined;\n }\n } else 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 return {\n ...(customCa ? { ca: customCa } : {}),\n ...(identity ? { cert: identity.cert, key: identity.key.expose() } : {}),\n };\n}\n\n/**\n * Re-derive the Node TLS options from client options, for a persona that must\n * build its own agent rather than use the one {@link createSession} attaches.\n *\n * The Node persona is exactly that case. `axios-cookiejar-support`'s request\n * interceptor THROWS (\"does not support for use with other http(s).Agent\")\n * when it finds an `httpsAgent` it did not create, and otherwise overwrites\n * the agent with a bare `HttpsCookieAgent` — so under `createNodeClient` a\n * customCa or client certificate was either fatal or silently discarded,\n * independently of the ESM/require problem in {@link loadNodeHttps}. The Node\n * persona therefore constructs ONE agent that is both jar-aware and\n * TLS-configured (see `src/node/cookieJar.ts`), using these options.\n *\n * Not exported from the package barrel: the returned object holds the private\n * key (§6.1 rule 3 / §7), and its only legitimate consumer is the agent\n * construction inside this SDK.\n */\nexport function resolveNodeTlsOptions(options: AxiamClientOptions): NodeTlsOptions | undefined {\n return tlsOptionsFrom(options.customCa, resolveClientIdentity(options));\n}\n\nfunction maybeBuildHttpsAgent(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): unknown {\n const tls = tlsOptionsFrom(customCa, identity);\n if (!tls) {\n return undefined;\n }\n if (typeof process === 'undefined') {\n // Browser: platform manages TLS; customCa and the client cert have no\n // effect there (a browser cannot present a client certificate from JS).\n return undefined;\n }\n // Node capability guard — resolved lazily (see loadNodeHttps) so this\n // branch never executes, and never needs to resolve, in a browser bundle.\n const https = loadNodeHttps();\n return new https.Agent(tls);\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 // The mTLS client identity (§6.1) is likewise validated on every persona so\n // a one-of/bad-PEM misconfiguration throws identically in browser and Node,\n // even though only Node presents the certificate.\n const clientIdentity = resolveClientIdentity(options);\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);\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 (§9.3, §12.3 rule 3).\n *\n * Two groups:\n * - the refresh endpoint itself plus login/logout — not\n * authenticated-session-continuation calls, so refreshing would only build\n * an infinite loop;\n * - the `/oauth2/*` endpoints — they authenticate the *client* with\n * `client_id`/`client_secret`, not the user session. A `401` there is a\n * client-credential failure, not a session expiry, so retrying after a\n * session refresh cannot help and MUST NOT enter the §9 guard\n * (CONTRACT.md §12.3 rule 3). `oidcRefresh` reaches the §9 guard through\n * its own explicit call path instead (`OidcClient.oidcRefresh`).\n */\nexport const SKIP_REFRESH = [\n '/api/v1/auth/refresh',\n '/api/v1/auth/login',\n '/api/v1/auth/logout',\n '/oauth2/token',\n '/oauth2/introspect',\n '/oauth2/revoke',\n];\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', session.buildRefreshBody());\n // H8 fix: resync the Node persona's cached access token + CSRF\n // token after a reactive refresh too — see the matching fix\n // and comment on rest/auth.ts's explicit refresh(). Without\n // this the replayed request below (and every request after it)\n // echoes a stale X-CSRF-Token and 403s.\n await session.onAuthenticated?.();\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 // url + body are forwarded so the mapper can apply the\n // endpoint-qualified §2 row: a 401 from /oauth2/introspect or\n // /oauth2/revoke carrying an OAuth2ErrorResponse body becomes an\n // OAuthProtocolError rather than a bare AuthError (§12.3 rule 3).\n return Promise.reject(\n mapHttpStatusToError(401, 'authentication failed', {\n url,\n body: error.response.data,\n cause: error,\n }),\n );\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, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n MfaSetupRequiredResponseWire,\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 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\n/**\n * CONTRACT.md §25.2 rule 1 — the `403 mfa_setup_required` branch of `login`.\n *\n * The server answers `403` when the tenant requires MFA and the account has\n * none, and hands back the token to fix it. Mapping that through §2 to\n * `AuthzError` told the caller they lacked permission to log in, when what the\n * server said was recoverable and came with the means to recover. It is an\n * outcome, so it is returned rather than thrown.\n *\n * Matched on the body's own discriminant, not on the status alone: a genuine\n * authorization refusal is also a `403`, and only one of the two carries a\n * `setup_token`.\n *\n * Exported so `loginOpaque` shares it — that endpoint answers the identical\n * `403`, and a second copy of this check is a second place for the two to\n * disagree about what a setup branch looks like.\n *\n * @internal\n */\nexport function mfaSetupRequired(err: unknown): LoginResult | undefined {\n if (extractAxiosStatus(err) !== 403) return undefined;\n const body = extractAxiosData<Partial<MfaSetupRequiredResponseWire>>(err);\n if (body?.mfa_setup_required !== true || typeof body.setup_token !== 'string') {\n return undefined;\n }\n return { status: 'mfa_setup_required', setupToken: new Sensitive(body.setup_token) };\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\n // The server resolves the workspace from the login body (org + tenant), not\n // the X-Tenant-ID header, so tenant/org context must travel here (§5).\n const body = client.session.buildLoginBody(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 // §25.2 rule 1: a recoverable, guided state, not a refusal.\n const setup = mfaSetupRequired(err);\n if (setup) return setup;\n\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, client.session.buildRefreshBody());\n // H8 fix (SDK bench harness validation): a successful refresh rotates\n // the `axiam_csrf` cookie (new random token, CONTRACT.md §3) the same\n // way login does, but — unlike login/verifyMfa just below, which both\n // call `onAuthenticated?.()` — this path never resynced the Node\n // persona's in-memory `session.csrfToken` (only NodeSession.doRefresh\n // did that, and doRefresh is wired to gRPC's callWithRefresh only, never\n // to this REST path). Every REST call after the FIRST refresh() then\n // echoed a now-stale X-CSRF-Token and failed with 403 \"CSRF validation\n // failed\" — refresh() effectively broke the session after one use.\n // `onAuthenticated` is exactly the right hook to reuse: same\n // access/csrf resync as login, it's a no-op on the browser persona\n // (undefined there), and Node's implementation is idempotent.\n await client.session.onAuthenticated?.();\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\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","/**\n * OPAQUE (RFC 9807) — the protocol half.\n *\n * This file contains **no cryptography**. Its predecessor, `core/srp.ts`, was\n * 419 lines of modular exponentiation, `PAD()` and SHA-256 transcript hashing,\n * because SRP is arithmetic every language can express and so every AXIAM\n * client wrote its own. OPAQUE is not — it needs an oblivious PRF,\n * `hash_to_curve`, `expand_message_xmd`, an envelope construction and a\n * three-message AKE — so CONTRACT.md §23.1 forbids an SDK from implementing\n * it, and this module is a loader around the one implementation the server and\n * every other SDK also use.\n *\n * # Loading\n *\n * `@axiam/opaque-wasm` is an **optional peer dependency**, resolved at runtime.\n * An installation that never touches the OPAQUE path should not be made to\n * carry a WebAssembly module, and a checkout without it must still build. When\n * it is absent, {@link opaqueAvailable} reports `false` and callers fall back\n * to password login — the posture §23.1 requires of an SDK whose native\n * artifact failed to load, and the reason it must *report* rather than throw at\n * login time.\n */\n\nimport { NetworkError } from './errors.js';\n\ntype OpaqueModule = typeof import('@axiam/opaque-wasm');\n\nlet modulePromise: Promise<OpaqueModule | null> | null = null;\n\n/**\n * The package specifier, held in a variable so bundlers do not try to resolve\n * it statically.\n *\n * This is the mechanism behind the graceful degradation above: a static\n * `import('@axiam/opaque-wasm')` is a hard resolution failure in an\n * installation that skipped the optional peer, which would make the whole SDK\n * unloadable for consumers who never wanted OPAQUE.\n */\nconst WASM_PACKAGE = '@axiam/opaque-wasm';\n\n/**\n * Load the WASM module once per process.\n *\n * Memoized on the *promise*, not the result, so two concurrent logins do not\n * instantiate the module twice. A failure is memoized too: retrying a package\n * that is not installed on every login would be a per-request cost for a file\n * that is not going to appear.\n */\nasync function loadModule(): Promise<OpaqueModule | null> {\n modulePromise ??= (async () => {\n try {\n const mod = (await import(/* @vite-ignore */ WASM_PACKAGE)) as OpaqueModule;\n await mod.default();\n return mod;\n } catch {\n return null;\n }\n })();\n return modulePromise;\n}\n\n/** Reset the memoized module. Test-only. */\nexport function __resetOpaqueModuleForTests(): void {\n modulePromise = null;\n}\n\n/**\n * Inject a module, bypassing the loader. Test-only.\n *\n * Exists because the dynamic specifier above is deliberately unresolvable at\n * build time, which also puts it out of reach of `vi.mock`.\n */\nexport function __setOpaqueModuleForTests(mod: unknown): void {\n modulePromise = Promise.resolve(mod as OpaqueModule);\n}\n\n/**\n * Whether this installation can perform OPAQUE at all (CONTRACT §23.2).\n *\n * Reports rather than throws, so a caller can decide to use the password path\n * before attempting a login rather than discovering it mid-exchange.\n */\nexport async function opaqueAvailable(): Promise<boolean> {\n const mod = await loadModule();\n return mod !== null && mod.opaqueAvailable();\n}\n\n/**\n * The key-stretching fields a `register/start` or `login/start` response\n * carries.\n *\n * Flat and optional, matching the wire format: the fields that do not apply to\n * the named function are **absent, not zero**. Reading an absent field as `0`\n * would stretch with the wrong cost and fail against a record that is\n * perfectly good — CONTRACT §23.4 rule 5.\n */\nexport interface OpaqueKsfFields {\n ksf: string;\n memory_kib?: number;\n iterations?: number;\n parallelism?: number;\n log_n?: number;\n r?: number;\n p?: number;\n}\n\n/** Accepted cost bands, matching `axiam_opaque::AxiamKsf` (§23.4 rule 4). */\nconst BOUNDS = {\n memory_kib: [8192, 1_048_576],\n iterations: [1, 10],\n parallelism: [1, 16],\n log_n: [14, 20],\n r: [1, 16],\n p: [1, 16],\n} as const;\n\nfunction requireInBand(name: keyof typeof BOUNDS, value: number | undefined, ksf: string): number {\n if (value === undefined) {\n throw new NetworkError(`OPAQUE: the server named ksf \\`${ksf}\\` without \\`${name}\\``);\n }\n const [min, max] = BOUNDS[name];\n if (!Number.isInteger(value) || value < min || value > max) {\n throw new NetworkError(\n `OPAQUE: the server named ${name}=${value} for \\`${ksf}\\`, outside the accepted ${min}..${max}`,\n );\n }\n return value;\n}\n\n/**\n * Build the stretching function from what the **server** named.\n *\n * Never from local defaults, and never cached across exchanges: a credential\n * enrolled under one cost keeps working after a tenant raises its policy, so a\n * client that guessed would derive a different randomized password and fail\n * against a record that is perfectly good (§23.4 rule 2).\n *\n * An unrecognised function is refused, never substituted — substituting\n * produces a well-formed randomized password that no AXIAM server agrees with,\n * surfacing to the user as a wrong password (§23.4 rule 3). The refusal is a\n * `NetworkError`, deliberately not an `AuthError`, so it cannot be mistaken for\n * bad credentials.\n */\nfunction buildKsf(mod: OpaqueModule, fields: OpaqueKsfFields) {\n switch (fields.ksf) {\n case 'argon2id':\n return mod.OpaqueKsf.argon2id(\n requireInBand('memory_kib', fields.memory_kib, fields.ksf),\n requireInBand('iterations', fields.iterations, fields.ksf),\n requireInBand('parallelism', fields.parallelism, fields.ksf),\n );\n case 'scrypt':\n return mod.OpaqueKsf.scrypt(\n requireInBand('log_n', fields.log_n, fields.ksf),\n requireInBand('r', fields.r, fields.ksf),\n requireInBand('p', fields.p, fields.ksf),\n );\n default:\n throw new NetworkError(\n `OPAQUE: this SDK cannot perform the key-stretching function the server named (\\`${fields.ksf}\\`)`,\n );\n }\n}\n\n/**\n * Raised when `@axiam/opaque-wasm` is not installed.\n *\n * A `NetworkError` subclass on purpose: §2 puts \"this client cannot do the\n * thing\" in the network/configuration bucket, never the credential one, so a\n * caller catching `NetworkError` falls back to password login without a special\n * case — while a caller that wants to tell \"not installed\" from \"tenant has it\n * disabled\" still can.\n */\nexport class OpaqueUnavailableError extends NetworkError {\n constructor() {\n super('OPAQUE is not available: install the optional peer dependency `@axiam/opaque-wasm`');\n this.name = 'OpaqueUnavailableError';\n // Re-set AFTER `super`, which pins the prototype to `NetworkError.prototype`\n // to survive transpilation to ES5. That is correct for `NetworkError` and\n // wrong for anything extending it: without this line\n // `err instanceof OpaqueUnavailableError` is false for an error that\n // demonstrably is one, and the distinction this class exists to draw\n // silently disappears.\n Object.setPrototypeOf(this, OpaqueUnavailableError.prototype);\n }\n}\n\nasync function requireModule(): Promise<OpaqueModule> {\n const mod = await loadModule();\n if (mod === null) throw new OpaqueUnavailableError();\n return mod;\n}\n\n/** One in-flight registration. */\nexport interface RegistrationExchange {\n readonly request: string;\n finish(registrationResponse: string, ksf: OpaqueKsfFields): string;\n}\n\n/** Begin an enrolment. The returned `request` goes to `register/start`. */\nexport async function startRegistration(password: string): Promise<RegistrationExchange> {\n const mod = await requireModule();\n const state = new mod.OpaqueRegistration(password);\n return {\n request: state.request,\n finish(registrationResponse, ksfFields) {\n return state.finish(password, registrationResponse, buildKsf(mod, ksfFields)).record;\n },\n };\n}\n\n/** One in-flight login. */\nexport interface LoginExchange {\n readonly ke1: string;\n finish(ke2: string, ksf: OpaqueKsfFields): string;\n}\n\n/** Begin a login. The returned `ke1` goes to `login/start`. */\nexport async function startLogin(password: string): Promise<LoginExchange> {\n const mod = await requireModule();\n const state = new mod.OpaqueLogin(password);\n return {\n ke1: state.ke1,\n finish(ke2, ksfFields) {\n return state.finish(password, ke2, buildKsf(mod, ksfFields)).ke3;\n },\n };\n}\n","// loginOpaque / opaqueEnrollment — the OPAQUE (RFC 9807) login path\n// (CONTRACT.md §23).\n//\n// A sibling of `login`, not a replacement. It establishes the same fact — this\n// principal knows the password — by a route that never puts the password on the\n// wire, and returns the **same** `LoginResult`, so an application can switch a\n// tenant to OPAQUE without touching its own code.\n//\n// The protocol lives in `core/opaque.ts`, which is a loader around the one\n// shared implementation and performs no I/O; this module is the HTTP calls and\n// the policy around them.\n\nimport { NetworkError, mapHttpStatusToError, sanitizeAxiosError } from '../core/index.js';\nimport {\n OpaqueUnavailableError,\n startLogin,\n startRegistration,\n type OpaqueKsfFields,\n} from '../core/opaque.js';\nimport { mfaSetupRequired } from './auth.js';\nimport type { AxiamClient } from './client.js';\nimport type { LoginResult, LoginSuccessResponseWire, MfaRequiredResponseWire } from './types.js';\n\nconst OPAQUE_REGISTER_START_PATH = '/api/v1/auth/opaque/register/start';\nconst OPAQUE_LOGIN_START_PATH = '/api/v1/auth/opaque/login/start';\nconst OPAQUE_LOGIN_FINISH_PATH = '/api/v1/auth/opaque/login/finish';\n\ninterface LoginStartWire extends OpaqueKsfFields {\n opaque_session: string;\n ke2: string;\n suite: string;\n}\n\ninterface RegisterStartWire extends OpaqueKsfFields {\n opaque_session: string;\n registration_response: string;\n suite: string;\n}\n\n/**\n * A completed enrolment, to send with any request that sets a password.\n *\n * Two fields, where the SRP verifier it replaces had seven. The server chose\n * the credential identifier, the ciphersuite and the costs and sealed them into\n * `opaque_session` — which is why a client cannot name any of them, and why it\n * cannot enrol a record against somebody else's account.\n */\nexport interface OpaqueEnrollment {\n /**\n * The `opaque_session` from `register/start`, echoed **verbatim**.\n *\n * Opaque sealed server state carrying the credential identifier, the\n * ciphersuite and the costs. Do not parse, cache, or reuse it across\n * exchanges (§23.4 rule 8) — it is valid for 120 seconds.\n */\n opaque_session: string;\n /** Lowercase-hex serialized RFC 9807 `RegistrationRecord`. */\n registration_record: string;\n}\n\nfunction axiosStatus(err: unknown): number | undefined {\n return (err as { response?: { status?: number } })?.response?.status;\n}\n\nfunction axiosMessage(err: unknown): string {\n return (err as { message?: string })?.message ?? 'request failed';\n}\n\n/**\n * Perform a full OPAQUE login (CONTRACT.md §23).\n *\n * Returns the same `LoginResult` as `login`, including the MFA-challenge case,\n * so a caller needs one result handler for both.\n *\n * ## What this does that `login` does not\n *\n * The password never leaves this process. What crosses the wire is a blinded\n * group element and a MAC, neither useful without the account's record **and**\n * the tenant's OPRF seed — so a TLS-terminating proxy, an accidentally verbose\n * request log or a heap dump on the server cannot capture a plaintext password,\n * because the server never has one. It also means a stolen record database is\n * not offline-crackable on its own, which is the property SRP could not offer.\n *\n * It does **not** protect against a compromised AXIAM server, and in a browser\n * it does not protect against AXIAM serving malicious JavaScript.\n *\n * ## What a caller no longer has to do\n *\n * Under SRP this returned only after verifying the server's `M2`, and §23.3\n * rule 6 had to mandate that in capitals because skipping it kept only the half\n * of the protocol that authenticates the client. RFC 9807's AKE authenticates\n * the server during the handshake — opening `KE2` *is* the proof that the\n * server holds the record — so there is no separate check and no way to omit\n * one.\n *\n * ## Errors\n *\n * - `NetworkError` when the tenant has OPAQUE disabled (`404` — a property of\n * the tenant, not of any user), when `@axiam/opaque-wasm` is not installed,\n * and when the server names a KSF this SDK cannot perform. These are\n * configuration or client-side faults, deliberately **not** `AuthError`:\n * reporting them as a credential failure would send a user off to reset a\n * password that works, and would stop a caller falling back to `login()`.\n * - `AuthError` for a wrong password, an account that does not exist, and a\n * server that does not hold the record — indistinguishable by design.\n * **Nothing is sent to `login/finish` in that case** (§23.4 rule 7), and a\n * caller must not retry over `login()`: that would hand the plaintext to a\n * server that just failed to prove itself.\n *\n * ## Cost\n *\n * Runs the tenant's key-stretching function: Argon2id at 19 MiB by default,\n * tens to hundreds of milliseconds of synchronous work. That cost is the point\n * — it is what makes a stolen record expensive to attack even by someone\n * holding the OPRF seed. In a browser, consider a Web Worker.\n */\nexport async function loginOpaque(\n client: AxiamClient,\n usernameOrEmail: string,\n password: string,\n): Promise<LoginResult> {\n // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, so any credential change must\n // drop them, or a re-authentication as a different principal inherits the\n // previous one's decisions.\n client.decisionMemo.clear();\n\n const exchange = await startLogin(password);\n\n // Reuses the login body builder so tenant/org resolution cannot drift between\n // the two login paths. The password field is deleted rather than sent — it\n // has no business on this request, and this is the assertion the tests make.\n const body: Record<string, string> = {\n ...client.session.buildLoginBody(usernameOrEmail, ''),\n ke1: exchange.ke1,\n };\n delete body.password;\n\n let started: LoginStartWire;\n try {\n const response = await client.session.axios.post<LoginStartWire>(\n OPAQUE_LOGIN_START_PATH,\n body,\n );\n started = response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status === 404) {\n throw new NetworkError(\n 'this tenant does not offer OPAQUE (opaque_mode is disabled); use login() instead',\n );\n }\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE login/start request failed', sanitizeAxiosError(err));\n }\n\n // The whole of the client's authentication check. A failure covers both\n // halves of the mutual authentication — the envelope only opens under the\n // right password, and KE2's MAC only verifies if the server holds the record\n // — and nothing further may be sent.\n //\n // A KSF the SDK cannot perform throws `NetworkError` from `buildKsf` and is\n // deliberately allowed to propagate rather than being flattened into an\n // authentication failure.\n let ke3: string;\n try {\n ke3 = exchange.finish(started.ke2, started);\n } catch (err) {\n if (err instanceof NetworkError) throw err;\n throw mapHttpStatusToError(401, 'invalid credentials', { cause: err });\n }\n\n let response;\n try {\n response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n OPAQUE_LOGIN_FINISH_PATH,\n { opaque_session: started.opaque_session, ke3 },\n );\n } catch (err) {\n // §25.2 rule 1 — this endpoint answers the same `403 mfa_setup_required`\n // as `POST /api/v1/auth/login`, and it is the same outcome here.\n const setup = mfaSetupRequired(err);\n if (setup) return setup;\n\n const status = axiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE login/finish request failed', sanitizeAxiosError(err));\n }\n\n if (response.status === 202) {\n const wire = response.data as MfaRequiredResponseWire;\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n }\n\n const wire = response.data as LoginSuccessResponseWire;\n client.session.authenticated = true;\n await client.session.onAuthenticated?.();\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\n/**\n * Build a registration record for `password`, to send with any request that\n * sets one (user creation, change-password, reset completion).\n *\n * This performs a `register/start` round trip, which the SRP verifier it\n * replaces did not need: OPAQUE's envelope is sealed under the server's\n * oblivious PRF, so there is no offline computation that produces a valid\n * record.\n *\n * Note the absence of an `identity` argument. The SRP version required the\n * account's canonical username, and passing an email produced a verifier no\n * login could ever satisfy. A record binds to a credential identifier the\n * server chooses, so there is nothing here to get wrong — and a later rename\n * cannot invalidate it.\n */\nexport async function opaqueEnrollment(\n client: AxiamClient,\n password: string,\n): Promise<OpaqueEnrollment> {\n client.ensureOpen();\n\n const exchange = await startRegistration(password);\n\n const body: Record<string, string> = {\n ...client.session.buildLoginBody('', ''),\n registration_request: exchange.request,\n };\n delete body.password;\n delete body.username_or_email;\n\n let started: RegisterStartWire;\n try {\n const response = await client.session.axios.post<RegisterStartWire>(\n OPAQUE_REGISTER_START_PATH,\n body,\n );\n started = response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status === 404) {\n throw new NetworkError('this tenant does not offer OPAQUE (opaque_mode is disabled)');\n }\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE register/start request failed', sanitizeAxiosError(err));\n }\n\n return {\n opaque_session: started.opaque_session,\n registration_record: exchange.finish(started.registration_response, started),\n };\n}\n\nexport { OpaqueUnavailableError };\nexport { opaqueAvailable } from '../core/opaque.js';\n","// Bounded read-only retry policy — CONTRACT.md §16.\n//\n// This file previously held a policy of its own invention: 1000 ms base, 8 s\n// cap, partial jitter (`base + 0–20%`), and `Retry-After` *replacing* the\n// computed backoff rather than flooring it. Two problems with that, both now\n// fixed:\n//\n// * `retryAfterMs ?? backoffDelayMs(attempt)` meant a `Retry-After: 0`\n// retried immediately, defeating the backoff entirely — exactly what\n// §16.1's \"floor, never a ceiling\" forbids.\n// * It was exported and unit-tested but **never called by any production\n// path**. `checkAccess` did not route through it, so this SDK performed no\n// read-only retries at all while appearing to. A tested helper nobody calls\n// is worse than an absent one: the green tests are what stop anyone from\n// looking.\n//\n// §16 is the normative table all eleven SDKs now share. `withRetry` is wired\n// into the authz surface in `authz.ts`; the §16.7 tests assert the policy\n// through the public `checkAccess` API, not just against this helper.\n\nimport { NetworkError } from '../core/index.js';\nimport type { TelemetryDispatcher } from '../core/telemetry.js';\n\n/** Attempt cap: 1 initial + 2 retries (§16.1). */\nexport const MAX_ATTEMPTS = 3;\n/** First backoff step, in milliseconds (§16.1). */\nexport const BASE_DELAY_MS = 200;\n/** Ceiling on any single computed backoff, in milliseconds (§16.1). */\nexport const MAX_DELAY_MS = 5_000;\n\n/** Options controlling {@link withRetry}. */\nexport interface RetryOptions {\n /**\n * Only operations that change **no server state** may be retried (§16.2).\n *\n * Note this means side-effect-free, **not** \"is an HTTP GET\": AXIAM's\n * authorization check is a `POST` with a request body and is the single most\n * important operation covered by this policy.\n */\n idempotent: boolean;\n /** Canonical operation name, for the §19 `retry` event. */\n operation?: string;\n /** Set `false` to disable retrying entirely (§16.1 disable switch). */\n enabled?: boolean;\n /** §19 sink, notified before each retry wait. */\n telemetry?: TelemetryDispatcher;\n /** Injected for tests — see §16.7 (\"a test that really waits 200 ms is a test nobody runs\"). */\n sleepFn?: (ms: number) => Promise<void>;\n /** Injected for tests: returns the jitter fraction in [0, 1]. */\n randomFn?: () => number;\n}\n\ninterface RetryAfterCarrier {\n retryAfterMs?: number;\n}\n\nfunction isRetryAfterCarrier(err: unknown): err is RetryAfterCarrier {\n return typeof err === 'object' && err !== null && 'retryAfterMs' in err;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The un-jittered backoff for a 1-based attempt: `min(cap, base * 2^(n-1))`.\n * Attempt 1 → 200 ms, attempt 2 → 400 ms.\n */\nexport function backoffMs(attempt: number): number {\n return Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attempt - 1));\n}\n\n/**\n * The actual wait: **full jitter** over `[0, backoff]`, then raised to any\n * server-supplied `Retry-After` (§16.1).\n *\n * Full jitter, not `backoff ± 10%`. Partial jitter keeps every client's retries\n * clustered around the same instant, which is the thundering herd retries are\n * supposed to prevent rather than cause.\n *\n * `Retry-After` is a **floor, never a ceiling**: the server is saying when it\n * will be ready, so retrying sooner is not permitted — and a `Retry-After: 0`\n * cannot shorten the wait below what jitter chose.\n */\nexport function delayMs(attempt: number, retryAfterMs: number | undefined, fraction: number): number {\n const jittered = backoffMs(attempt) * Math.min(Math.max(fraction, 0), 1);\n return retryAfterMs === undefined ? jittered : Math.max(jittered, retryAfterMs);\n}\n\n/**\n * Runs `fn` under the §16 policy.\n *\n * `fn` receives the 1-based attempt number so it can label its §19\n * `requestStart`/`requestEnd` pair. That is not cosmetic: §19.2 rule 5 requires\n * one pair **per attempt** with the attempt distinguishing them, so a caller\n * can count real wire calls. Emitting every pair as attempt 1 would make a\n * retried call indistinguishable from a single slow one — the exact blindness\n * §16.5 exists to remove.\n *\n * `fn` MUST be side-effect-free. This helper — like every retry helper — cannot\n * tell the difference, so routing a mutation through it would silently\n * duplicate a side effect, or replay a single-use credential (an authorization\n * code, a device code at redemption, a rotating refresh token) into a hard\n * `invalid_grant`.\n *\n * Only `NetworkError` is retried. The §2 taxonomy folds `408`/`429`/`5xx`/\n * transport into that one type, so this implements the whole §16.3 table:\n * `AuthError` and `AuthzError` are decisive answers, not transport failures.\n */\nexport async function withRetry<T>(\n fn: (attempt: number) => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const retryable = options.idempotent && options.enabled !== false;\n const maxAttempts = retryable ? MAX_ATTEMPTS : 1;\n const sleep = options.sleepFn ?? defaultSleep;\n const random = options.randomFn ?? Math.random;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n return await fn(attempt);\n } catch (err) {\n const isLastAttempt = attempt === maxAttempts;\n if (!retryable || !(err instanceof NetworkError) || isLastAttempt) {\n throw err;\n }\n const retryAfterMs = isRetryAfterCarrier(err) ? err.retryAfterMs : undefined;\n const delay = delayMs(attempt, retryAfterMs, random());\n // §16.5 — without this event a retried-then-succeeded call is invisible:\n // a slow success with no signal that the server is failing.\n options.telemetry?.emit({\n type: 'retry',\n operation: options.operation ?? 'unknown',\n attempt,\n delayMs: delay,\n reason: err instanceof Error ? err.message : String(err),\n });\n await sleep(delay);\n }\n }\n\n // Unreachable: the loop above always returns or throws.\n throw new NetworkError('retry loop exhausted without a result');\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 { memoKey } from '../core/decisionMemo.js';\nimport { withRetry } from './retry.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 // §11 rule 9: `reason_code` is surfaced verbatim, including a value this\n // SDK has never heard of — the outcome is carried by `allowed` alone, so an\n // unknown code can never change it.\n return { allowed: wire.allowed, reason: wire.reason, reasonCode: wire.reason_code };\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 client.ensureOpen();\n\n // §17: consult the decision memo first. Disabled by default, in which case\n // this is one map lookup that always misses.\n const key = memoKey(check);\n const memoized = client.decisionMemo.get(key);\n if (memoized) return memoized;\n\n // §16: a `POST`, but side-effect-free, so it is retry-eligible. Eligibility\n // is \"changes no server state\", NOT \"is a GET\" — gating on the verb would\n // exclude the single most important operation this policy covers.\n const decision = await withRetry(\n (attempt) => attemptCheck(client, check, attempt),\n client.retryOptions('checkAccess'),\n );\n\n // Only a decision the server actually returned is memoized: reaching here\n // means success, so §17.1 rule 7's ban on negative-caching a failure is\n // structural rather than a check that could be forgotten.\n client.decisionMemo.set(key, decision);\n return decision;\n}\n\n/** One attempt at the single-check call, with its §19 event pair. */\nasync function attemptCheck(\n client: AxiamClient,\n check: AccessCheck,\n attempt: number,\n): Promise<AccessDecision> {\n const done = client.telemetry.startRequest('checkAccess', 'POST', CHECK_PATH, attempt);\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n done(response.status, 'success');\n return fromWireDecision(response.data);\n } catch (err) {\n done(statusOf(err), 'failure');\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 client.ensureOpen();\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n return withRetry(async (attempt) => {\n const done = client.telemetry.startRequest('batchCheck', 'POST', BATCH_CHECK_PATH, attempt);\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n done(response.status, 'success');\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n done(statusOf(err), 'failure');\n throw mapAuthzError(err);\n }\n }, client.retryOptions('batchCheck'));\n}\n\n/** The HTTP status an axios-shaped error carries, if any. */\nfunction statusOf(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { status?: number } }).response?.status;\n }\n return undefined;\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","// WebAuthn / passkeys — the relying-party layer (CONTRACT.md §24.1–§24.5).\n//\n// Six wire operations. None of them touches an authenticator: that is §24.6,\n// which lives in `axiam-sdk/browser` because it needs a DOM. These six are the\n// half of a ceremony that talks to AXIAM, and they work identically in Node —\n// a service completing a ceremony its native client ran is the relying party\n// here, exactly as a browser is.\n//\n// The rule everything below obeys is §24.0: the server chooses every option\n// and verifies every response, so this module carries both through untouched.\n// It does not default a field, does not normalize one, and does not re-encode\n// a buffer.\n\nimport { mapHttpStatusToError, NetworkError, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCredential,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnWorkspace,\n} from './webauthnTypes.js';\n\nconst REGISTER_START = '/api/v1/auth/webauthn/register/start';\nconst REGISTER_FINISH = '/api/v1/auth/webauthn/register/finish';\nconst AUTH_START = '/api/v1/auth/webauthn/authenticate/start';\nconst AUTH_FINISH = '/api/v1/auth/webauthn/authenticate/finish';\nconst DISCOVERABLE_START = '/api/v1/auth/webauthn/authenticate/discoverable/start';\nconst DISCOVERABLE_FINISH = '/api/v1/auth/webauthn/authenticate/discoverable/finish';\n\n// ---------------------------------------------------------------------------\n// Public result types\n// ---------------------------------------------------------------------------\n\n/**\n * A started ceremony: the server's challenge, plus the state token that binds\n * a response to it.\n *\n * `stateToken` is `Sensitive` (§24.5) — it is a bearer credential for the\n * length of the ceremony, and one that leaks inside that window is a ceremony\n * an attacker can try to complete. Pass it straight back to the matching\n * `*Finish` call; the SDK never decodes it and neither should a caller.\n */\nexport interface WebauthnRegistrationChallenge {\n /** The server's options. Hand them to the authenticator unchanged (§24.0). */\n challenge: WebauthnCreationChallenge;\n /** Binds the authenticator's answer to this challenge. Pass it back to `webauthnRegisterFinish`. */\n stateToken: Sensitive<string>;\n}\n\n/** A started authentication ceremony (both the second-factor and discoverable forms). */\nexport interface WebauthnAuthenticationChallenge {\n /** The server's options. Hand them to the authenticator unchanged (§24.0). */\n challenge: WebauthnRequestChallenge;\n /** Binds the authenticator's answer to this challenge. Pass it back to the matching `*Finish`. */\n stateToken: Sensitive<string>;\n}\n\n/**\n * The outcome of a completed passkey sign-in.\n *\n * The client is **already authenticated** when this resolves (§24.3 rule 1) —\n * the tokens are returned as well because a caller may want to hand them\n * onward, not because adoption is optional.\n */\nexport interface WebauthnLoginResult {\n /** The new access token. Already adopted by this client (§24.3 rule 1). */\n accessToken: Sensitive<string>;\n /** The session refresh token — refreshed through `refresh()`, not `oidcRefresh` (§24.3 rule 5). */\n refreshToken: Sensitive<string>;\n /** Opaque identifier for the session just created. */\n sessionId: string;\n /** Access-token lifetime in seconds, from the time of this response. */\n expiresIn: number;\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes\n// ---------------------------------------------------------------------------\n\ninterface StartRegistrationWire {\n challenge: WebauthnCreationChallenge;\n state_token: string;\n}\ninterface StartAuthenticationWire {\n challenge: WebauthnRequestChallenge;\n state_token: string;\n}\ninterface CredentialWire {\n id: string;\n credential_id: string;\n name: string;\n credential_type: string;\n created_at: string;\n last_used_at?: string | null;\n}\ninterface WebauthnLoginWire {\n access_token: string;\n refresh_token: string;\n session_id: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// Registration — requires an authenticated session (§24.1)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/register/start` (§24.1).\n *\n * Enrolling a passkey is something a signed-in user does to their own account,\n * so this requires a session and fails **client-side with no wire call** when\n * there is none.\n *\n * A `503` here means the tenant's attestation policy requires attestation and\n * the FIDO metadata service has no usable snapshot. That is a server\n * configuration state, not a transient failure, so it is surfaced as a\n * `AxiamError` and — per §24.4 rule 2 — deliberately **not** retried.\n */\nexport async function webauthnRegisterStart(\n client: AxiamClient,\n): Promise<WebauthnRegistrationChallenge> {\n client.ensureOpen();\n requireSession(client, 'webauthnRegisterStart');\n\n const wire = await post<StartRegistrationWire>(client, REGISTER_START, {}, 'webauthnRegisterStart');\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/**\n * `POST /api/v1/auth/webauthn/register/finish` (§24.1).\n *\n * `response` goes to the server exactly as the authenticator produced it\n * (§24.0 rule 3).\n *\n * A `403` is the tenant's attestation policy refusing **this authenticator** —\n * an AAGUID that is not allow-listed, a missing FIDO certification, a revoked\n * status. It is not a permission problem with the user, and the server's\n * message is surfaced verbatim (§24.4 rule 1) because it is the only way the\n * person holding the key learns that a different one would work.\n */\nexport async function webauthnRegisterFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n credentialName: string,\n response: WebauthnRegistrationResponse | string,\n): Promise<WebauthnCredential> {\n client.ensureOpen();\n requireSession(client, 'webauthnRegisterFinish');\n\n const wire = await post<CredentialWire>(\n client,\n REGISTER_FINISH,\n {\n state_token: expose(stateToken),\n credential_name: credentialName,\n response: asResponse(response, 'webauthnRegisterFinish'),\n },\n 'webauthnRegisterFinish',\n );\n\n return {\n id: wire.id,\n credentialId: wire.credential_id,\n name: wire.name,\n credentialType: wire.credential_type,\n createdAt: wire.created_at,\n ...(wire.last_used_at ? { lastUsedAt: wire.last_used_at } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Authentication as a second factor (§24.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/start` (§24.1).\n *\n * The **second-factor** ceremony: it continues a `login()` that answered\n * `mfa_required` and listed `\"webauthn\"` among its methods. `challengeToken`\n * is that result's `mfaToken`.\n *\n * This is a different flow from {@link webauthnDiscoverableStart}, not the\n * same one with an optional argument — see §24.2 for why they cannot be\n * merged.\n */\nexport async function webauthnAuthenticateStart(\n client: AxiamClient,\n challengeToken: Sensitive<string> | string,\n): Promise<WebauthnAuthenticationChallenge> {\n client.ensureOpen();\n const wire = await post<StartAuthenticationWire>(\n client,\n AUTH_START,\n { challenge_token: expose(challengeToken) },\n 'webauthnAuthenticateStart',\n );\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/** `POST /api/v1/auth/webauthn/authenticate/finish` (§24.1). Adopts the session (§24.3). */\nexport async function webauthnAuthenticateFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n): Promise<WebauthnLoginResult> {\n return finishSignIn(client, AUTH_FINISH, stateToken, response, 'webauthnAuthenticateFinish');\n}\n\n// ---------------------------------------------------------------------------\n// Usernameless (discoverable) authentication (§24.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/discoverable/start` (§24.1).\n *\n * The **primary-factor** ceremony: nothing precedes it, the server sends an\n * empty `allowCredentials`, and the assertion itself identifies the user.\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant's isolation boundary — but the SDK fills it from its own\n * configured identity, and this endpoint accepts slugs, so a slug-only client\n * can run the ceremony.\n */\nexport async function webauthnDiscoverableStart(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n): Promise<WebauthnAuthenticationChallenge> {\n client.ensureOpen();\n\n const body = resolveWorkspace(client, workspace);\n const wire = await post<StartAuthenticationWire>(\n client,\n DISCOVERABLE_START,\n body,\n 'webauthnDiscoverableStart',\n );\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/discoverable/finish` (§24.1).\n * Adopts the session (§24.3).\n *\n * Unlike its username-bound twin this fires the server's `login.post_auth`\n * reactor hook (§22.5): there was no password step for the event to have been\n * fired at.\n */\nexport async function webauthnDiscoverableFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n): Promise<WebauthnLoginResult> {\n return finishSignIn(\n client,\n DISCOVERABLE_FINISH,\n stateToken,\n response,\n 'webauthnDiscoverableFinish',\n );\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/**\n * The shared tail of both authentication ceremonies.\n *\n * §24.3 rule 1: a completed passkey sign-in leaves the client authenticated,\n * in exactly the state `login()` leaves it. This is not §14.3's \"MAY adopt\"\n * posture — `deviceLogin` mints tokens a caller may want to route elsewhere,\n * and this is the SDK's own primary authentication. Returning a token set\n * without adopting it would make `webauthnLogin()` the one way to log in that\n * does not log you in.\n */\nasync function finishSignIn(\n client: AxiamClient,\n path: string,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n operation: string,\n): Promise<WebauthnLoginResult> {\n client.ensureOpen();\n // §17.1 rule 9 / §24.3 rule 4: memo entries are keyed by subject, and this\n // call changes the subject.\n client.decisionMemo.clear();\n\n const wire = await post<WebauthnLoginWire>(\n client,\n path,\n { state_token: expose(stateToken), response: asResponse(response, operation) },\n operation,\n );\n\n client.session.authenticated = true;\n // Syncs the Node persona's csrfToken (and cached access token) out of the\n // jar. Load-bearing since the server started setting the cookie triple on\n // these two endpoints: without it the first state-changing call after a\n // passkey sign-in echoes no `X-CSRF-Token` and is refused (§24.3 rule 2).\n await client.session.onAuthenticated?.();\n\n return {\n accessToken: new Sensitive(wire.access_token),\n refreshToken: new Sensitive(wire.refresh_token),\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\n/**\n * §24.1: `register/*` needs a session, and the failure is raised client-side\n * with no wire call — the same shape §1.1 rule 3 requires of `getUserInfo`.\n */\nfunction requireSession(client: AxiamClient, operation: string): void {\n if (!client.session.authenticated) {\n throw mapHttpStatusToError(\n 401,\n `${operation} requires an authenticated session: enrol a passkey while signed in ` +\n '(CONTRACT.md §24.1).',\n );\n }\n}\n\n/**\n * Fill the discoverable ceremony's workspace from the client's own configured\n * identity when the caller passed none.\n *\n * Only the fields that actually have a value are emitted: the server takes\n * either form for either level, and sending `null` for the ones it does not\n * have would be indistinguishable from asking it to resolve nothing.\n */\nfunction resolveWorkspace(\n client: AxiamClient,\n workspace: WebauthnWorkspace | undefined,\n): Record<string, string> {\n const merged: WebauthnWorkspace = {\n orgId: workspace?.orgId ?? client.session.orgId,\n orgSlug: workspace?.orgSlug ?? client.session.orgSlug,\n tenantId: workspace?.tenantId ?? client.session.tenantId,\n tenantSlug: workspace?.tenantSlug ?? client.session.tenantSlug,\n };\n\n const body: Record<string, string> = {};\n if (merged.orgId) body.org_id = merged.orgId;\n if (merged.orgSlug) body.org_slug = merged.orgSlug;\n if (merged.tenantId) body.tenant_id = merged.tenantId;\n if (merged.tenantSlug) body.tenant_slug = merged.tenantSlug;\n\n if (!body.org_id && !body.org_slug) {\n throw mapHttpStatusToError(\n 400,\n 'webauthnDiscoverableStart needs an organization: construct the client with an org, or pass ' +\n 'one in the workspace argument (CONTRACT.md §24.1).',\n );\n }\n if (!body.tenant_id && !body.tenant_slug) {\n throw mapHttpStatusToError(\n 400,\n 'webauthnDiscoverableStart needs a tenant: construct the client with one, or pass it in the ' +\n 'workspace argument (CONTRACT.md §24.1).',\n );\n }\n return body;\n}\n\nfunction expose(token: Sensitive<string> | string): string {\n return typeof token === 'string' ? token : token.expose();\n}\n\n/**\n * Accept either the typed response or the platform's own JSON string (§24.6a\n * rule 2).\n *\n * Android's Credential Manager hands back `registrationResponseJson` /\n * `authenticationResponseJson`, and a browser hands back `credential.toJSON()`.\n * Requiring a caller to destructure one of those into a typed value that this\n * SDK immediately re-serializes is three chances to corrupt a signed buffer in\n * service of nothing — so the string is taken directly.\n *\n * Parsing is value-preserving: every field in these messages is a string or a\n * plain object, so what reaches the server is what the authenticator produced.\n * Key order can differ, which JSON does not ascribe meaning to and the server\n * does not read.\n */\nfunction asResponse<T>(response: T | string, operation: string): T {\n if (typeof response !== 'string') return response;\n try {\n return JSON.parse(response) as T;\n } catch (err) {\n throw new TypeError(\n `${operation}: the authenticator response string is not valid JSON. Pass the platform's ` +\n 'response JSON verbatim (CONTRACT.md §24.6a).',\n { cause: err },\n );\n }\n}\n\n/**\n * The challenge in the JSON form every platform authenticator API takes\n * (§24.6a rule 1).\n *\n * This is the string an Android app passes to\n * `CreatePublicKeyCredentialRequest` or `GetPublicKeyCredentialOption`, and the\n * value a browser passes to `PublicKeyCredential.parseCreationOptionsFromJSON()`.\n * It is the inner options object — the `publicKey` wrapper is what the DOM's\n * `CredentialCreationOptions` adds, and the platform JSON APIs do not want it.\n *\n * Pure local computation, no I/O. Nothing is defaulted, dropped or reordered on\n * the way through (§24.0).\n */\nexport function webauthnRequestJson(\n challenge: WebauthnCreationChallenge | WebauthnRequestChallenge,\n): string {\n return JSON.stringify(challenge.publicKey);\n}\n\n/**\n * POST a JSON body and map failures through the §2 taxonomy.\n *\n * Not routed through §16's retry helper, and that is deliberate for the whole\n * section: five of the six operations are ceremony steps that consume\n * server-side state, and the sixth (`register/start`) has the `503` §24.4\n * rule 2 forbids retrying. There is nothing here a bounded retry could help.\n */\nasync function post<T>(\n client: AxiamClient,\n path: string,\n body: unknown,\n operation: string,\n): Promise<T> {\n try {\n const response = await client.session.axios.post<T>(path, body);\n return response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, serverMessage(err) ?? `${operation} failed`, { cause: err });\n }\n throw new NetworkError(`${operation} request failed`, sanitizeAxiosError(err));\n }\n}\n\nfunction axiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { status?: number } }).response?.status;\n }\n return undefined;\n}\n\n/**\n * The server's own message, kept verbatim.\n *\n * §24.4 rule 1 turns on this: a `403` from `register/finish` names which\n * attestation rule refused the authenticator, and replacing it with a generic\n * string throws away the only actionable part of the response.\n */\nfunction serverMessage(err: unknown): string | undefined {\n if (!err || typeof err !== 'object' || !('response' in err)) return undefined;\n const data = (err as { response?: { data?: unknown } }).response?.data;\n if (typeof data === 'string' && data.length > 0) return data;\n if (data && typeof data === 'object' && 'message' in data) {\n const message = (data as { message?: unknown }).message;\n if (typeof message === 'string' && message.length > 0) return message;\n }\n return undefined;\n}\n","// Account lifecycle and MFA enrolment (CONTRACT.md §25).\n//\n// §1 locked the middle of an account's life — login, verifyMfa, refresh,\n// logout all assume an account that already exists, is verified, and already\n// has its second factor. These nine operations are how an account gets into\n// that state. None of them is new server surface; all nine have been live and\n// unreachable-from-an-SDK since before §1 was written, which meant every\n// application hand-rolled a POST against a path this SDK also knew.\n\nimport { mapHttpStatusToError, NetworkError, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type { LoginResult, LoginSuccessResponseWire } from './types.js';\n\nconst MFA_ENROLL = '/api/v1/auth/mfa/enroll';\nconst MFA_CONFIRM = '/api/v1/auth/mfa/confirm';\nconst MFA_SETUP_ENROLL = '/api/v1/auth/mfa/setup/enroll';\nconst MFA_SETUP_CONFIRM = '/api/v1/auth/mfa/setup/confirm';\nconst VERIFY_EMAIL = '/api/v1/auth/verify-email';\nconst RESEND_VERIFICATION = '/api/v1/auth/resend-verification';\nconst RESET_REQUEST = '/api/v1/auth/reset';\nconst RESET_CONFIRM = '/api/v1/auth/reset/confirm';\nconst RESET_CONTEXT = '/api/v1/auth/reset/context';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A TOTP enrolment offer. **The factor is not active yet** — it becomes active\n * when `AxiamClient.mfaConfirm` accepts a code derived from this secret (§25.2\n * rule 4).\n *\n * Both fields are `Sensitive`, and `totpUri` is the one that matters: it is\n * `otpauth://totp/...?secret=<secretBase32>`, so it *contains* the secret. An\n * SDK that wrapped the secret and left the URI bare would have wrapped nothing\n * — the URI is the field that actually reaches a log, because it is the field\n * a caller passes to a QR renderer (§25.3).\n */\nexport interface MfaEnrollment {\n /** The shared TOTP secret, base32. Anyone holding it can generate valid codes indefinitely. */\n secretBase32: Sensitive<string>;\n /** `otpauth://totp/…?secret=…` — what a QR renderer takes. It *contains* `secretBase32`. */\n totpUri: Sensitive<string>;\n}\n\n/**\n * The effective OPAQUE policy for the account a reset token belongs to (§25.4).\n *\n * Discloses no identity. Contract 1.26 removed the username from this response\n * when OPAQUE replaced SRP — an unauthenticated endpoint that confirms which\n * account a token belongs to is an oracle worth not having.\n */\nexport interface PasswordResetContext {\n /** The tenant's OPAQUE parameters, when it has OPAQUE enabled. Absent means plaintext is accepted. */\n opaque?: Record<string, unknown>;\n}\n\n/** The workspace a password-reset request names. Slugs are accepted, as on `login`. */\nexport interface PasswordResetRequest {\n /** The address to send the reset mail to. */\n email: string;\n /** Organization slug. Defaults to the client's own configuration. */\n orgSlug?: string;\n /** Tenant UUID. Defaults to the client's own configuration. */\n tenantId?: string;\n /** Tenant slug. Defaults to the client's own configuration. */\n tenantSlug?: string;\n}\n\n/** Everything `confirmPasswordReset` needs. */\nexport interface PasswordResetConfirmation {\n /** The single-use token from the reset mail. */\n token: Sensitive<string> | string;\n /** The new password. */\n newPassword: Sensitive<string> | string;\n /** The tenant the account belongs to. A UUID — this is a body field, not a query parameter. */\n tenantId: string;\n /**\n * The §23 registration record, for a tenant whose `AxiamClient.passwordResetContext`\n * says it requires one. Sending a plaintext `newPassword` to a tenant in\n * `opaque_mode: required` is refused, and refused late (§25.4 rule 1).\n */\n opaque?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes\n// ---------------------------------------------------------------------------\n\ninterface MfaEnrollWire {\n secret_base32: string;\n totp_uri: string;\n}\ninterface MfaConfirmWire {\n mfa_enabled: boolean;\n}\ninterface ResetContextWire {\n opaque?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Voluntary MFA enrolment, by a signed-in user (§25.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/mfa/enroll` (§25.1) — start voluntary TOTP enrolment.\n *\n * Requires a session and changes nothing about it. In particular this does\n * **not** clear the §17 decision memo: the subject has not changed, and\n * discarding a warm memo on an unrelated profile action costs a round trip on\n * every check that follows (§25.2 rule 3).\n */\nexport async function mfaEnroll(client: AxiamClient): Promise<MfaEnrollment> {\n client.ensureOpen();\n const wire = await post<MfaEnrollWire>(client, MFA_ENROLL, {}, 'mfaEnroll');\n return {\n secretBase32: new Sensitive(wire.secret_base32),\n totpUri: new Sensitive(wire.totp_uri),\n };\n}\n\n/**\n * `POST /api/v1/auth/mfa/confirm` (§25.1) — activate the factor\n * {@link mfaEnroll} offered, by proving a code derived from its secret.\n */\nexport async function mfaConfirm(client: AxiamClient, totpCode: string): Promise<boolean> {\n client.ensureOpen();\n const wire = await post<MfaConfirmWire>(\n client,\n MFA_CONFIRM,\n { totp_code: totpCode },\n 'mfaConfirm',\n );\n return wire.mfa_enabled;\n}\n\n// ---------------------------------------------------------------------------\n// Forced MFA enrolment, during login (§25.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/mfa/setup/enroll` (§25.1) — start the enrolment a\n * `login()` demanded.\n *\n * Reached when `login()` returns the `mfa_setup_required` outcome: the tenant\n * requires MFA and this account has none. There is no session yet — the setup\n * token *is* the credential.\n */\nexport async function mfaSetupEnroll(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n): Promise<MfaEnrollment> {\n client.ensureOpen();\n const wire = await post<MfaEnrollWire>(\n client,\n MFA_SETUP_ENROLL,\n { setup_token: expose(setupToken) },\n 'mfaSetupEnroll',\n );\n return {\n secretBase32: new Sensitive(wire.secret_base32),\n totpUri: new Sensitive(wire.totp_uri),\n };\n}\n\n/**\n * `POST /api/v1/auth/mfa/setup/confirm` (§25.1) — finish forced enrolment and,\n * with it, the login that was interrupted.\n *\n * Adopts credentials exactly as `login()` does, because it *is* the completion\n * of a login (§25.2 rule 2).\n */\nexport async function mfaSetupConfirm(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n totpCode: string,\n): Promise<LoginResult> {\n client.ensureOpen();\n // §17.1 rule 9: the subject changes here, unlike on `mfaEnroll`.\n client.decisionMemo.clear();\n\n const wire = await post<LoginSuccessResponseWire>(\n client,\n MFA_SETUP_CONFIRM,\n { setup_token: expose(setupToken), totp_code: totpCode },\n 'mfaSetupConfirm',\n );\n\n client.session.authenticated = true;\n await client.session.onAuthenticated?.();\n\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\n// ---------------------------------------------------------------------------\n// Email verification (§25.1)\n// ---------------------------------------------------------------------------\n\n/** `POST /api/v1/auth/verify-email` (§25.1). Unauthenticated — the user may have no session yet. */\nexport async function verifyEmail(\n client: AxiamClient,\n token: Sensitive<string> | string,\n tenantId: string,\n): Promise<void> {\n client.ensureOpen();\n await post<void>(\n client,\n VERIFY_EMAIL,\n { token: expose(token), tenant_id: tenantId },\n 'verifyEmail',\n );\n}\n\n/** `POST /api/v1/auth/resend-verification` (§25.1). */\nexport async function resendVerification(\n client: AxiamClient,\n email: string,\n tenantId: string,\n): Promise<void> {\n client.ensureOpen();\n await post<void>(\n client,\n RESEND_VERIFICATION,\n { email, tenant_id: tenantId },\n 'resendVerification',\n );\n}\n\n// ---------------------------------------------------------------------------\n// Password reset (§25.4)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/reset` (§25.1) — ask for a reset mail.\n *\n * **Resolves whether or not the address exists**, and this SDK exposes no way\n * to tell the two apart. That is not an omission to improve on: a client that\n * surfaced a \"no such user\" state — even one inferred from timing — would turn\n * the endpoint into the enumeration oracle its uniform response exists to\n * prevent (§25.4).\n */\nexport async function requestPasswordReset(\n client: AxiamClient,\n request: PasswordResetRequest,\n): Promise<void> {\n client.ensureOpen();\n const body: Record<string, string> = { email: request.email };\n const orgSlug = request.orgSlug ?? client.session.orgSlug;\n const tenantId = request.tenantId ?? client.session.tenantId;\n const tenantSlug = request.tenantSlug ?? client.session.tenantSlug;\n if (orgSlug) body.org_slug = orgSlug;\n if (tenantId) body.tenant_id = tenantId;\n if (tenantSlug) body.tenant_slug = tenantSlug;\n\n await post<void>(client, RESET_REQUEST, body, 'requestPasswordReset');\n}\n\n/**\n * `GET /api/v1/auth/reset/context` (§25.1) — the OPAQUE policy for the account\n * a reset token belongs to.\n *\n * Call this before {@link confirmPasswordReset} on any tenant that might have\n * §23 enabled: the client has to build a registration record, and building one\n * needs parameters it cannot know before it has a token to ask with.\n *\n * `404` means unknown, expired **or** already-consumed, deliberately without\n * distinguishing them; this SDK does not distinguish them either (§25.4 rule 3).\n */\nexport async function passwordResetContext(\n client: AxiamClient,\n token: Sensitive<string> | string,\n): Promise<PasswordResetContext> {\n client.ensureOpen();\n const url = `${RESET_CONTEXT}?token=${encodeURIComponent(expose(token))}`;\n try {\n const response = await client.session.axios.get<ResetContextWire>(url);\n return response.data?.opaque ? { opaque: response.data.opaque } : {};\n } catch (err) {\n throw toTaxonomyError(err, 'passwordResetContext');\n }\n}\n\n/** `POST /api/v1/auth/reset/confirm` (§25.1) — set the new password. */\nexport async function confirmPasswordReset(\n client: AxiamClient,\n confirmation: PasswordResetConfirmation,\n): Promise<void> {\n client.ensureOpen();\n const body: Record<string, unknown> = {\n token: expose(confirmation.token),\n new_password: expose(confirmation.newPassword),\n tenant_id: confirmation.tenantId,\n };\n if (confirmation.opaque) body.opaque = confirmation.opaque;\n\n await post<void>(client, RESET_CONFIRM, body, 'confirmPasswordReset');\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction expose(value: Sensitive<string> | string): string {\n return typeof value === 'string' ? value : value.expose();\n}\n\nasync function post<T>(\n client: AxiamClient,\n path: string,\n body: unknown,\n operation: string,\n): Promise<T> {\n try {\n const response = await client.session.axios.post<T>(path, body);\n return response.data;\n } catch (err) {\n throw toTaxonomyError(err, operation);\n }\n}\n\nfunction toTaxonomyError(err: unknown, operation: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: unknown } }).response;\n if (response?.status !== undefined) {\n return mapHttpStatusToError(response.status, serverMessage(response.data) ?? `${operation} failed`, {\n cause: err,\n });\n }\n }\n return new NetworkError(`${operation} request failed`, sanitizeAxiosError(err));\n}\n\nfunction serverMessage(data: unknown): string | undefined {\n if (typeof data === 'string' && data.length > 0) return data;\n if (data && typeof data === 'object' && 'message' in data) {\n const message = (data as { message?: unknown }).message;\n if (typeof message === 'string' && message.length > 0) return message;\n }\n return undefined;\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 { NetworkError } from '../core/index.js';\nimport { DecisionMemo } from '../core/decisionMemo.js';\nimport { TelemetryDispatcher } from '../core/telemetry.js';\nimport { TelemetryReporter } from '../core/telemetryReporter.js';\nimport type { RetryOptions } from './retry.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as opaqueMethods from './opaque.js';\nimport * as authzMethods from './authz.js';\nimport * as webauthnMethods from './webauthn.js';\nimport * as accountMethods from './accountLifecycle.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\nimport type { Sensitive } from '../core/index.js';\nimport type {\n WebauthnAuthenticationResponse,\n WebauthnCredential,\n WebauthnRegistrationResponse,\n WebauthnWorkspace,\n} from './webauthnTypes.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 /** §17 decision memo. Disabled unless `decisionMemoTtlMs` was configured. */\n readonly decisionMemo: DecisionMemo;\n\n /** §19 telemetry dispatcher. Empty unless a hook was installed. */\n readonly telemetry: TelemetryReporter;\n\n /** §16.1 disable switch. Defaults to enabled. */\n private readonly retryEnabled: boolean;\n\n /** §18 shutdown flag. Set once by close(); read on every operation. */\n private closed = false;\n\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n // §17.1 rule 1: off unless the caller asked for it.\n this.decisionMemo = new DecisionMemo(options.decisionMemoTtlMs ?? 0);\n this.telemetry = new TelemetryReporter(new TelemetryDispatcher(options.telemetryHook));\n // §19.2 rule 6: a clamped setting is reported, not swallowed. Emitted once,\n // here, because construction is the only moment an operator can act on it.\n this.decisionMemo.reportClamp(options.decisionMemoTtlMs ?? 0, this.telemetry.dispatcher);\n this.retryEnabled = options.retryEnabled ?? true;\n }\n\n /**\n * Release this client's local resources (CONTRACT.md §18).\n *\n * Idempotent — calling it twice is not an error. Cleanup runs from error\n * paths, and an error path that itself throws hides the original failure.\n *\n * **This does not log out.** §18.1 rule 5: shutting down a client releases\n * *local* resources and never reaches the network. The server-side session\n * deliberately outlives the client object, which is what lets a process\n * restart and resume; a `close()` that logged out would silently end every\n * user's session on each deploy. Call {@link logout} first if ending the\n * session is what you want.\n *\n * After this returns, any operation on the client rejects rather than\n * silently reconnecting.\n */\n close(): void {\n this.closed = true;\n this.decisionMemo.clear();\n }\n\n /**\n * Throws if {@link close} has been called (§18.1 rule 4).\n *\n * @internal\n */\n ensureOpen(): void {\n if (this.closed) {\n throw new NetworkError('client is closed: this AxiamClient was shut down with close()');\n }\n }\n\n /**\n * §16 options for `operation`, bound to this client's switch and telemetry.\n *\n * @internal\n */\n retryOptions(operation: string): RetryOptions {\n return {\n idempotent: true,\n operation,\n enabled: this.retryEnabled,\n telemetry: this.telemetry.dispatcher,\n };\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 /**\n * OPAQUE login (§23) — the password never leaves this process.\n *\n * Returns the same `LoginResult` as {@link login}, including the\n * `mfa_required` branch, so one result handler serves both. Rejects with a\n * `NetworkError` naming OPAQUE when the tenant has it disabled, so a caller\n * can fall back to {@link login} rather than mistaking it for a bad password.\n *\n * **Only that case may fall back.** Any other rejection is a failed login,\n * and retrying it over {@link login} would hand the plaintext to a server\n * that just failed to prove it holds the record.\n */\n loginOpaque(usernameOrEmail: string, password: string): Promise<LoginResult> {\n return opaqueMethods.loginOpaque(this, usernameOrEmail, password);\n }\n\n /**\n * Build an OPAQUE registration record to send with any request that sets a\n * password (§23). The server cannot build one — it never sees the plaintext.\n *\n * Asynchronous because it performs a `register/start` round trip: the\n * envelope is sealed under the server's oblivious PRF, so unlike the SRP\n * verifier this replaces there is no offline computation that produces a\n * valid record.\n */\n opaqueEnrollment(password: string): Promise<opaqueMethods.OpaqueEnrollment> {\n return opaqueMethods.opaqueEnrollment(this, password);\n }\n\n /**\n * Whether this installation can perform OPAQUE (§23.2).\n *\n * Asynchronous, and genuinely able to answer `false`: `@axiam/opaque-wasm` is\n * an optional peer dependency, so an installation that skipped it reports\n * rather than throwing at login time.\n */\n opaqueAvailable(): Promise<boolean> {\n return opaqueMethods.opaqueAvailable();\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 // -------------------------------------------------------------------------\n // §24 WebAuthn / passkeys — the relying-party layer\n //\n // These six work in Node as well as the browser: a service completing a\n // ceremony its native client ran is the relying party, exactly as a browser\n // is. The ceremony itself — the half that needs an authenticator — is\n // `axiam-sdk/browser` (§24.6).\n // -------------------------------------------------------------------------\n\n /** `POST /api/v1/auth/webauthn/register/start` (§24.1). Requires a session. */\n webauthnRegisterStart(): Promise<webauthnMethods.WebauthnRegistrationChallenge> {\n return webauthnMethods.webauthnRegisterStart(this);\n }\n\n /** `POST /api/v1/auth/webauthn/register/finish` (§24.1). Requires a session. */\n webauthnRegisterFinish(\n stateToken: Sensitive<string> | string,\n credentialName: string,\n response: WebauthnRegistrationResponse | string,\n ): Promise<WebauthnCredential> {\n return webauthnMethods.webauthnRegisterFinish(this, stateToken, credentialName, response);\n }\n\n /** `POST /api/v1/auth/webauthn/authenticate/start` (§24.1) — passkey as a second factor. */\n webauthnAuthenticateStart(\n challengeToken: Sensitive<string> | string,\n ): Promise<webauthnMethods.WebauthnAuthenticationChallenge> {\n return webauthnMethods.webauthnAuthenticateStart(this, challengeToken);\n }\n\n /** `POST /api/v1/auth/webauthn/authenticate/finish` (§24.1). Leaves the client authenticated (§24.3). */\n webauthnAuthenticateFinish(\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n ): Promise<webauthnMethods.WebauthnLoginResult> {\n return webauthnMethods.webauthnAuthenticateFinish(this, stateToken, response);\n }\n\n /** `POST .../authenticate/discoverable/start` (§24.1) — usernameless sign-in. */\n webauthnDiscoverableStart(\n workspace?: WebauthnWorkspace,\n ): Promise<webauthnMethods.WebauthnAuthenticationChallenge> {\n return webauthnMethods.webauthnDiscoverableStart(this, workspace);\n }\n\n /** `POST .../authenticate/discoverable/finish` (§24.1). Leaves the client authenticated (§24.3). */\n webauthnDiscoverableFinish(\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n ): Promise<webauthnMethods.WebauthnLoginResult> {\n return webauthnMethods.webauthnDiscoverableFinish(this, stateToken, response);\n }\n\n // -------------------------------------------------------------------------\n // §25 Account lifecycle and MFA enrolment\n // -------------------------------------------------------------------------\n\n /** `POST /api/v1/auth/mfa/enroll` (§25.1) — voluntary TOTP enrolment, by a signed-in user. */\n mfaEnroll(): Promise<accountMethods.MfaEnrollment> {\n return accountMethods.mfaEnroll(this);\n }\n\n /** `POST /api/v1/auth/mfa/confirm` (§25.1) — activate the factor `mfaEnroll` offered. */\n mfaConfirm(totpCode: string): Promise<boolean> {\n return accountMethods.mfaConfirm(this, totpCode);\n }\n\n /** `POST /api/v1/auth/mfa/setup/enroll` (§25.1) — start the enrolment a `login()` demanded. */\n mfaSetupEnroll(setupToken: Sensitive<string> | string): Promise<accountMethods.MfaEnrollment> {\n return accountMethods.mfaSetupEnroll(this, setupToken);\n }\n\n /** `POST /api/v1/auth/mfa/setup/confirm` (§25.1) — finish it, completing the interrupted login. */\n mfaSetupConfirm(setupToken: Sensitive<string> | string, totpCode: string): Promise<LoginResult> {\n return accountMethods.mfaSetupConfirm(this, setupToken, totpCode);\n }\n\n /** `POST /api/v1/auth/verify-email` (§25.1). */\n verifyEmail(token: Sensitive<string> | string, tenantId: string): Promise<void> {\n return accountMethods.verifyEmail(this, token, tenantId);\n }\n\n /** `POST /api/v1/auth/resend-verification` (§25.1). */\n resendVerification(email: string, tenantId: string): Promise<void> {\n return accountMethods.resendVerification(this, email, tenantId);\n }\n\n /** `POST /api/v1/auth/reset` (§25.1). Resolves whether or not the address exists (§25.4). */\n requestPasswordReset(request: accountMethods.PasswordResetRequest): Promise<void> {\n return accountMethods.requestPasswordReset(this, request);\n }\n\n /** `GET /api/v1/auth/reset/context` (§25.1) — the OPAQUE policy for a reset token's account. */\n passwordResetContext(\n token: Sensitive<string> | string,\n ): Promise<accountMethods.PasswordResetContext> {\n return accountMethods.passwordResetContext(this, token);\n }\n\n /** `POST /api/v1/auth/reset/confirm` (§25.1). */\n confirmPasswordReset(confirmation: accountMethods.PasswordResetConfirmation): Promise<void> {\n return accountMethods.confirmPasswordReset(this, confirmation);\n }\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n"]}
1
+ {"version":3,"sources":["../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/core/decisionMemo.ts","../src/core/telemetry.ts","../src/core/telemetryReporter.ts","../src/rest/session.ts","../src/rest/interceptors.ts","../src/rest/auth.ts","../src/core/opaque.ts","../src/rest/opaque.ts","../src/rest/retry.ts","../src/rest/authz.ts","../src/rest/webauthn.ts","../src/rest/accountLifecycle.ts","../src/rest/client.ts","../src/rest/webauthnErrors.ts"],"names":["axios","response","wire","axiosStatus","post","expose","serverMessage"],"mappings":";;;;;;;;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU/B,MAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,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sBAAsB,GAAA,EAA+B;AACnE,EAAA,MAAM,IAAA,GAAO,UAAU,GAAG,CAAA;AAC1B,EAAA,QAAQ,IAAA;AAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAMZ,KAAK,iBAAA;AAAA,IACL,KAAK,UAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMT,KAAK,mBAAA;AACH,MAAA,OAAO,oBAAA;AAAA,IACT,KAAK,YAAA;AAAA,IACL,KAAK,SAAA;AACH,MAAA,OAAO,SAAA;AAAA,IACT,KAAK,mBAAA;AAAA,IACL,KAAK,eAAA;AACH,MAAA,OAAO,aAAA;AAAA,IACT;AACE,MAAA,OAAO,SAAA;AAAA;AAEb;AASO,SAAS,qBAAqB,OAAA,EAAkC;AACrE,EAAA,QAAQ,OAAA;AAAS,IACf,KAAK,WAAA;AACH,MAAA,OAAO,4DAAA;AAAA,IACT,KAAK,oBAAA;AACH,MAAA,OAAO,8GAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,8DAAA;AAAA,IACT,KAAK,aAAA;AACH,MAAA,OAAO,6GAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,yCAAA;AAAA;AAEb;AAGA,SAAS,UAAU,GAAA,EAAkC;AACnD,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,MAAA;AACpD,EAAA,MAAM,OAAQ,GAAA,CAA2B,IAAA;AACzC,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,MAAA;AAC3C","file":"index.js","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\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 {\n AuthError,\n AuthzError,\n NetworkError,\n OAuthProtocolError,\n type AxiamError,\n} 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 request URL (absolute or path-only) the error came from, when\n * available. Load-bearing for the two **endpoint-qualified** rows of §2's\n * HTTP table (added by contract 1.4): a `400`/`401` carrying an\n * `OAuth2ErrorResponse` body maps to `OAuthProtocolError` only when it came\n * from an `/oauth2/*` endpoint. Omitting it simply keeps the generic rows.\n */\n url?: string;\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 * The RFC 6749 error body shape (`OAuth2ErrorResponse` in `openapi.json`)\n * returned by AXIAM's `/oauth2/*` endpoints. Both fields are required by the\n * schema.\n */\nexport interface OAuth2ErrorResponseWire {\n /** RFC 6749 error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable description of the failure. */\n error_description: string;\n}\n\n/**\n * Path prefix identifying AXIAM's OAuth2 endpoint family (`/oauth2/token`,\n * `/oauth2/introspect`, `/oauth2/revoke`, …). The two endpoint-qualified §2\n * rows apply only to URLs whose path starts with it.\n */\nconst OAUTH2_PATH_PREFIX = '/oauth2/';\n\n/**\n * Whether `url` targets an `/oauth2/*` endpoint. Accepts both an absolute URL\n * (as taken from the discovery document) and a bare path (as axios request\n * configs carry), and never throws on a malformed value — an unparseable URL\n * simply falls back to a substring test, so a mis-shaped URL can only ever\n * *fail* to qualify for the OAuth2 rows, never wrongly qualify for them.\n */\nexport function isOAuth2EndpointUrl(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n // A relative path has no base here, so `URL` throws and we fall through.\n return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);\n } catch {\n return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);\n }\n}\n\n/**\n * Narrow a parsed response body to {@link OAuth2ErrorResponseWire}. Both\n * `error` and `error_description` must be present and string-typed — a body\n * that carries only one of them is NOT an `OAuth2ErrorResponse` and keeps the\n * generic §2 mapping (better a generic error than a fabricated\n * `error_description`).\n */\nexport function isOAuth2ErrorBody(body: unknown): body is OAuth2ErrorResponseWire {\n if (body === null || typeof body !== 'object') {\n return false;\n }\n const record = body as Record<string, unknown>;\n return typeof record.error === 'string' && typeof record.error_description === 'string';\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 * | 400 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 401 | AuthError |\n * | 401 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * Where two rows match the same response the more specific\n * (endpoint- and body-qualified) row wins, per §2 — so the two\n * `OAuthProtocolError` rows are evaluated first. They require BOTH an\n * `/oauth2/*` `ctx.url` AND an `OAuth2ErrorResponse`-shaped `ctx.body`;\n * anything else keeps the generic mapping.\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 // Endpoint-qualified rows first (§2 \"the more specific row wins\",\n // §12.3 rule 3). `message` is deliberately ignored here: the contract fixes\n // OAuthProtocolError's message to \"<error>: <error_description>\".\n if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {\n return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);\n }\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\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// 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/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\nimport type { TelemetryHook } from './telemetry.js';\n\n/**\n * Configuration for {@link AxiamClient}, passed as its constructor's first\n * argument.\n *\n * @remarks\n * Either `tenantSlug` or `tenantId` MUST be provided — AXIAM is\n * multi-tenant and has no default tenant, so construction throws when both\n * are omitted (CONTRACT.md §5). `customCa` is the sole TLS escape hatch\n * (CONTRACT.md §6); there is no option to disable certificate verification.\n */\nexport interface AxiamClientOptions {\n /** Base URL of the AXIAM server, e.g. \"https://iam.example.com\". */\n baseUrl: string;\n /** Human-readable tenant identifier. At least one of tenantSlug/tenantId is required at runtime. */\n tenantSlug?: string;\n /** Tenant UUID. At least one of tenantSlug/tenantId is required at runtime. */\n tenantId?: string;\n /**\n * Human-readable organization identifier (CONTRACT.md §5). Optional at\n * construction, but the server REQUIRES an org context on login — a tenant\n * slug is only unique *within* an organization — so a client that omits both\n * `orgSlug` and `orgId` will fail login with a 400/401. Forwarded as\n * `org_slug` in the login body. Mutually exclusive with {@link orgId}\n * (if both are given, `orgId` wins, mirroring how `tenantSlug`/`tenantId`\n * resolve).\n */\n orgSlug?: string;\n /**\n * Organization UUID (CONTRACT.md §5). Optional at construction (see\n * {@link orgSlug}). When supplied it is forwarded as `org_id` on login and\n * used to build the `refresh` body; otherwise the resolved organization UUID\n * is decoded from the authenticated session's access-token `org_id` claim\n * after the first successful login. Mutually exclusive with {@link orgSlug}.\n */\n orgId?: string;\n /** PEM-encoded custom CA certificate, for self-signed/dev environments (§6). */\n customCa?: string;\n /**\n * Enable the CONTRACT.md §16 bounded read-only retry policy. **Default:\n * `true`.**\n *\n * Set `false` to make every operation exactly one attempt. That is the right\n * choice for a caller who owns their own retry layer — they know their\n * deadline and this SDK does not — but it is not a way to make failures\n * quieter: a transient `NetworkError` simply surfaces immediately.\n *\n * §16.1 permits this switch but forbids raising the attempt cap, base delay\n * or delay cap above the contract's values, so there is no knob for those:\n * eleven SDKs agreeing on one table is the point.\n */\n retryEnabled?: boolean;\n /**\n * Enable the CONTRACT.md §17 client-side decision memo, in milliseconds.\n * **Default: `0`, which means disabled** — not \"cache for zero milliseconds\".\n *\n * ## What you are accepting\n *\n * The staleness bound is this TTL, **in both directions**. A grant revoked on\n * the server can still read as allowed for up to the TTL, and a grant just\n * added can still read as denied for up to the TTL.\n *\n * **Reads-your-own-writes is not guaranteed.** An admin UI that grants a role\n * and immediately re-checks is the case that breaks, and it breaks silently.\n * If that is your workload, leave this off.\n *\n * Clamped to 5000 ms rather than rejected, so asking for a minute gets you\n * five seconds. Allows and denies are memoized identically (asymmetric\n * caching leaks the outcome through latency), failures are never memoized,\n * and the memo is cleared on any credential change.\n */\n decisionMemoTtlMs?: number;\n /**\n * Install a CONTRACT.md §19 telemetry sink.\n *\n * Receives request start/end, §16 retry and §9 refresh events, so metrics can\n * be wired without this package depending on any metrics library. See\n * `examples/telemetry-hook.ts`.\n *\n * A hook that throws cannot fail the operation that fired it (§19.2 rule 2),\n * and no event payload can carry a token — {@link TelemetryEvent} is a closed\n * union with a fixed field set (§19.2 rule 3). Invoked on the calling path,\n * so it must not block; buffer on your side if you need async delivery.\n */\n telemetryHook?: TelemetryHook;\n /**\n * PEM-encoded client-certificate chain for mutual TLS (§6.1). Presented to\n * the server to authenticate an IoT device / service account. MUST be\n * provided together with {@link AxiamClientOptions.clientKey}. Node only —\n * ignored in the browser (browsers cannot present a client certificate from\n * JS). Presenting a client certificate NEVER relaxes server verification.\n */\n clientCert?: string;\n /**\n * PEM-encoded private key (PKCS#8 or PKCS#1) matching {@link\n * AxiamClientOptions.clientCert} (§6.1). Secret material: it is passed\n * straight to the Node TLS stack and is never retained on a public property,\n * logged, or serialized (§7). MUST be provided together with `clientCert`.\n * Node only — ignored in the browser.\n */\n clientKey?: string;\n /**\n * Expected `iss` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 5). Optional and unset by default — the rule is conditional on\n * configuration, and the SDK never hardcodes an issuer. When set, the §10\n * middleware rejects a token whose `iss` differs.\n */\n expectedIssuer?: string;\n /**\n * Expected `aud` claim for locally-verified access tokens (CONTRACT.md\n * §10.1 rule 6). Optional and unset by default. A resource server guarding\n * user-facing routes SHOULD set `\"axiam:user\"`; a machine-to-machine one\n * `\"axiam:m2m\"`. When set, the §10 middleware rejects a token whose `aud`\n * does not contain it.\n */\n expectedAudience?: string;\n /** Connection timeout in milliseconds. Defaults to DEFAULT_CONNECT_TIMEOUT_MS. */\n connectTimeoutMs?: number;\n /** Request timeout in milliseconds. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */\n requestTimeoutMs?: number;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** PEM header that must appear in a certificate chain (§6/§6.1). */\nexport const CERT_PEM_MARKER = '-----BEGIN CERTIFICATE-----';\n\n/**\n * PEM header for a private key — PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1\n * (`BEGIN RSA PRIVATE KEY`), or an EC key (`BEGIN EC PRIVATE KEY`) (§6.1).\n */\nconst PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;\n\n/**\n * A validated mTLS client identity (§6.1). The private key is held behind\n * {@link Sensitive} so it can never leak through a debug/log/serialize path\n * (§7); call `key.expose()` only at the point of handing it to the TLS stack.\n */\nexport interface ClientIdentity {\n /** PEM certificate chain (not secret). */\n cert: string;\n /** PEM private key, redaction-wrapped (§7). */\n key: Sensitive<string>;\n}\n\n/**\n * Validate the §6.1 client-certificate options and, when configured, return\n * the resolved identity. Throws at construction time (consistent with §6's\n * PEM-only rule) when:\n * - exactly one of clientCert/clientKey is present (they are all-or-nothing);\n * - clientCert is not a PEM certificate chain;\n * - clientKey is not a PEM private key.\n *\n * Returns `undefined` when neither is configured. This validation runs on\n * every persona (including the browser, which then ignores the identity) so\n * construction fails fast and identically everywhere.\n */\nexport function resolveClientIdentity(options: {\n clientCert?: string;\n clientKey?: string;\n}): ClientIdentity | undefined {\n const hasCert = options.clientCert !== undefined;\n const hasKey = options.clientKey !== undefined;\n if (hasCert !== hasKey) {\n throw new Error(\n 'clientCert and clientKey must be provided together for mutual TLS ' +\n '(one was given without the other) (CONTRACT.md §6.1).',\n );\n }\n if (!hasCert || !hasKey) {\n return undefined;\n }\n if (!options.clientCert!.includes(CERT_PEM_MARKER)) {\n throw new Error(\n 'clientCert must be a PEM-encoded certificate chain (expected to contain ' +\n '\"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6.1).',\n );\n }\n if (!PRIVATE_KEY_PEM_RE.test(options.clientKey!)) {\n throw new Error(\n 'clientKey must be a PEM-encoded private key (expected to contain ' +\n '\"-----BEGIN PRIVATE KEY-----\" or \"-----BEGIN RSA PRIVATE KEY-----\") ' +\n '(CONTRACT.md §6.1).',\n );\n }\n return { cert: options.clientCert!, key: new Sensitive(options.clientKey!) };\n}\n","// Client-side decision memo — CONTRACT.md §17.\n//\n// **Disabled by default.** §11.2 rule 6's ban on caching allow/deny decisions\n// is still the default behaviour; this is the single opt-in exception that\n// section carves out, and a caller has to switch it on having read the cost.\n//\n// # What it costs\n//\n// The staleness bound is the TTL, **in both directions**. A grant revoked on\n// the server can still read as allowed for up to the TTL, and a grant just\n// added can still read as denied for up to the TTL. That second direction is\n// the one that surprises people: **reads-your-own-writes is not guaranteed.**\n// An admin UI that grants a role and immediately re-checks is the case that\n// breaks, and it breaks silently.\n//\n// This mirrors the server's own bound rather than inventing a second staleness\n// story — AXIAM__AUTHZ__DECISION_CACHE_TTL_SECS (default 5 s) makes the same\n// trade server-side. One deliberate difference: the server's setting is an\n// unclamped integer, so an operator can configure a multi-hour staleness\n// window. MAX_TTL_MS clamps this one at 5 s, because the client has no reason\n// to repeat that.\n\nimport type { AccessDecision } from './authz.js';\nimport type { TelemetryDispatcher } from './telemetry.js';\n\n/**\n * The §17.1 rule 2 ceiling. A configured TTL above this is clamped, not\n * rejected: a caller who asked for 60 s wants caching, and silently giving them\n * the maximum safe value beats failing construction.\n */\nexport const MAX_TTL_MS = 5_000;\n\n/**\n * Entry cap before FIFO eviction (§17.1 rule 8). The memo is a latency\n * optimisation, so dropping an entry is always correct.\n */\nconst MAX_ENTRIES = 1024;\n\n/**\n * The §17.1 rule 3 key: all four components, with absent distinguished from\n * present.\n *\n * `\\u001f` (unit separator) joins the parts because it cannot appear in an\n * action, a UUID or a scope, so no combination of values can forge a\n * collision. `\\u0000` marks an *absent* optional, which is why an absent scope\n * can never collide with a present one — a memo that let them collide would\n * answer a narrower question with a broader answer.\n */\nexport function memoKey(check: {\n action: string;\n resourceId: string;\n scope?: string;\n subjectId?: string;\n}): string {\n const ABSENT = '\\u0000';\n return [\n check.subjectId ?? ABSENT,\n check.resourceId,\n check.action,\n check.scope ?? ABSENT,\n ].join('\\u001f');\n}\n\ninterface Entry {\n decision: AccessDecision;\n storedAt: number;\n}\n\n/**\n * A bounded, TTL-clamped decision memo.\n *\n * `ttlMs === 0` means **disabled** — not \"cache for zero milliseconds\". That is\n * the default, and both `get` and `set` become no-ops.\n */\nexport class DecisionMemo {\n private readonly ttlMs: number;\n private readonly entries = new Map<string, Entry>();\n\n /**\n * @param ttlMs requested TTL in milliseconds; `0` disables the memo and any\n * value above {@link MAX_TTL_MS} is clamped to it.\n * @param now injected clock, so the TTL can be tested without waiting.\n */\n constructor(\n ttlMs = 0,\n /** Injected so the TTL can be tested without waiting. */\n private readonly now: () => number = Date.now,\n ) {\n this.ttlMs = Math.min(Math.max(ttlMs, 0), MAX_TTL_MS);\n }\n\n /** Whether this memo does anything. `false` for the default configuration. */\n get enabled(): boolean {\n return this.ttlMs > 0;\n }\n\n /** The effective TTL after clamping. */\n get effectiveTtlMs(): number {\n return this.ttlMs;\n }\n\n /** A live decision for `key`, if one is memoized and unexpired. */\n get(key: string): AccessDecision | undefined {\n if (!this.enabled) return undefined;\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (this.now() - entry.storedAt >= this.ttlMs) {\n this.entries.delete(key);\n return undefined;\n }\n // Returned whole, including `reasonCode`: §17.1 rule 5 forbids returning\n // `allowed` while dropping the code, which would make the field\n // intermittently absent — worse than never having had it.\n return entry.decision;\n }\n\n /**\n * Memoize a decision the server actually returned.\n *\n * Callers must only reach here on success. §17.1 rule 7 forbids\n * negative-caching a failure: memoizing a transport error as a deny would\n * turn a blip into a TTL-long outage, and memoizing it as an allow is\n * unthinkable.\n */\n set(key: string, decision: AccessDecision): void {\n if (!this.enabled) return;\n // Re-inserting moves the key to the end of Map iteration order, which is\n // what makes the eviction below FIFO by insertion.\n this.entries.delete(key);\n this.entries.set(key, { decision, storedAt: this.now() });\n while (this.entries.size > MAX_ENTRIES) {\n const oldest = this.entries.keys().next().value;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n /**\n * Drop every entry (§17.1 rule 9).\n *\n * Called on login, verifyMfa, refresh and logout. Entries are keyed by\n * subject, not by session, so a re-authentication as a *different* principal\n * would otherwise read the previous principal's decisions.\n */\n clear(): void {\n this.entries.clear();\n }\n\n /**\n * Emit a {@link ConfigClampedEvent} if the requested TTL was clamped (§19.2\n * rule 6).\n *\n * This is the clamp that matters most to get right: an operator who set a\n * 60-second TTL believes their staleness bound is 60 seconds. It is five, and\n * without this event nothing anywhere says so.\n *\n * Nothing is emitted when the requested value was already inside the limit,\n * or when the memo is disabled — an event that fires when nothing happened\n * trains its reader to ignore it.\n */\n reportClamp(requestedMs: number, telemetry: TelemetryDispatcher): void {\n if (!telemetry.installed || requestedMs <= 0 || requestedMs === this.ttlMs) return;\n telemetry.emit({\n type: 'configClamped',\n setting: 'decisionMemoTtlMs',\n requested: String(requestedMs),\n effective: String(this.ttlMs),\n contractReference: '§17.1 rule 2',\n });\n }\n\n /** Entry count, for tests. */\n get size(): number {\n return this.entries.size;\n }\n}\n","// Telemetry hooks — CONTRACT.md §19.\n//\n// An optional callback surface so callers can wire OpenTelemetry, Prometheus,\n// or a log line **without this package depending on any of them**. No hook\n// installed costs one undefined check per request.\n//\n// Two rules from §19.2 are enforced here rather than left to documentation:\n//\n// * A hook cannot break the SDK. `TelemetryDispatcher.emit` swallows anything\n// a sink throws, so a broken hook cannot fail an authorization check.\n// * No secrets, ever. `TelemetryEvent` is a closed discriminated union with a\n// fixed field set and no index signature, so there is no way to put a token\n// into a payload bound for a metrics backend. The type system, not a review\n// comment, is what keeps them out.\n\n/** Why a request finished. */\nexport type Outcome = 'success' | 'failure';\n\n/** Whether this caller performed a §9 refresh or waited on another's. */\nexport type RefreshRole = 'leader' | 'follower';\n\n/** Emitted before an outbound call leaves the SDK. */\nexport interface RequestStartEvent {\n /** Discriminant. */\n type: 'requestStart';\n /** Canonical operation name, e.g. `checkAccess`. */\n operation: string;\n /** HTTP method. */\n method: string;\n /**\n * Path **template** — `/api/v1/authz/check`, never a URL with ids\n * substituted in. A metric label carrying a UUID is a cardinality bomb.\n */\n pathTemplate: string;\n /** 1 for the first attempt, incrementing per §16 retry. */\n attempt: number;\n}\n\n/** Emitted after a call completes, success or failure. */\nexport interface RequestEndEvent {\n /** Discriminant. */\n type: 'requestEnd';\n /** Canonical operation name. */\n operation: string;\n /** HTTP method. */\n method: string;\n /** Path template — see {@link RequestStartEvent.pathTemplate}. */\n pathTemplate: string;\n /** Attempt this event closes. */\n attempt: number;\n /** HTTP status, or `undefined` when the call never got a response. */\n status?: number;\n /** Wall-clock duration of this attempt, in milliseconds. */\n durationMs: number;\n /** Success or failure. */\n outcome: Outcome;\n}\n\n/**\n * Emitted before each §16 retry wait.\n *\n * §16.5 requires this: a retried-then-succeeded operation is otherwise\n * invisible — the caller sees a slow success and no signal that the server is\n * failing. That silence is the standing objection to automatic retry.\n */\nexport interface RetryEvent {\n /** Discriminant. */\n type: 'retry';\n /** Canonical operation name. */\n operation: string;\n /** The attempt that just failed. */\n attempt: number;\n /** The delay about to be taken, after jitter and any `Retry-After`. */\n delayMs: number;\n /** Redacted failure description. Never carries a token (§2 redaction rules). */\n reason: string;\n}\n\n/** Emitted around a §9 single-flight refresh. */\nexport interface RefreshEvent {\n /** Discriminant. */\n type: 'refresh';\n /** Whether this caller performed the refresh or waited on another's. */\n role: RefreshRole;\n /** How long the refresh (or the wait for one) took, in milliseconds. */\n durationMs: number;\n}\n\n/**\n * Emitted at construction, once per caller-supplied setting the SDK clamped\n * (§19.1, §19.2 rule 6).\n *\n * Two places in the contract require clamping rather than rejecting: §16.1's\n * attempt cap, base delay and delay cap, and §17.1 rule 2's memo TTL. Both\n * clamps are right — rejecting would break a caller whose configuration was\n * merely optimistic, and honoring would let one client become the herd §16\n * exists to prevent. Doing it *silently* is the part that is wrong.\n *\n * An operator who set a 60-second memo TTL believes they have one. They have\n * five seconds, and their staleness reasoning is off by a factor of twelve with\n * nothing anywhere to say so.\n *\n * Not emitted for a value already within its limit: an event that fires when\n * nothing happened trains its reader to ignore it.\n */\nexport interface ConfigClampedEvent {\n /** Discriminant. */\n type: 'configClamped';\n /** The setting's name, e.g. `decisionMemoTtlMs`. */\n setting: string;\n /** The value the caller asked for, rendered. */\n requested: string;\n /** The value actually in force, rendered. */\n effective: string;\n /** The §-reference for the limit, e.g. `§17.1 rule 2`. */\n contractReference: string;\n}\n\n/** A §19 telemetry event. Closed union — see the file header for why. */\nexport type TelemetryEvent =\n | RequestStartEvent\n | RequestEndEvent\n | RetryEvent\n | RefreshEvent\n | ConfigClampedEvent;\n\n/**\n * A caller-supplied telemetry sink (§19).\n *\n * Invoked on the calling path, so it must not block: §19.2 rule 4 makes\n * buffering the caller's job so they can pick the policy. Every mature metrics\n * library already buffers.\n */\nexport type TelemetryHook = (event: TelemetryEvent) => void;\n\n/**\n * Internal dispatcher. `undefined` is the overwhelmingly common case and costs\n * one check.\n */\nexport class TelemetryDispatcher {\n constructor(private readonly hook?: TelemetryHook) {}\n\n /**\n * Emit an event, swallowing anything the caller's hook throws.\n *\n * §19.2 rule 2: telemetry is not permitted to fail an authorization check.\n */\n emit(event: TelemetryEvent): void {\n if (!this.hook) return;\n try {\n this.hook(event);\n } catch {\n // Deliberately swallowed. A hook that throws is the caller's bug, and\n // surfacing it here would turn a metrics problem into an authorization\n // failure.\n }\n }\n\n /** Whether a hook is installed. */\n get installed(): boolean {\n return this.hook !== undefined;\n }\n}\n","// Request-pair helper for CONTRACT.md §19.\n//\n// Kept apart from `telemetry.ts` (which is pure event types + the dispatcher)\n// so the browser bundle can import the types without pulling timing code it\n// does not use.\n\nimport { TelemetryDispatcher, type Outcome } from './telemetry.js';\n\n/** Closes a §19 request pair. Call exactly once, on every exit path. */\nexport type FinishRequest = (status: number | undefined, outcome: Outcome) => void;\n\n/**\n * Emits the §19 `requestStart`/`requestEnd` pair around one **attempt**.\n *\n * Per attempt, not per logical call: §19.2 rule 5 requires a caller to be able\n * to count real wire calls from the events, which one pair per operation would\n * hide — a retried call would look like a single slow one.\n */\nexport class TelemetryReporter {\n /** @param dispatcher the sink these events are emitted to. */\n constructor(\n /** The underlying §19 dispatcher. */\n readonly dispatcher: TelemetryDispatcher,\n ) {}\n\n /**\n * Emit `requestStart` and return the function that emits its `requestEnd`.\n *\n * `pathTemplate` must be the route constant — `/api/v1/authz/check`, never a\n * path with ids substituted in. A metric label carrying a UUID is a\n * cardinality bomb.\n */\n startRequest(operation: string, method: string, pathTemplate: string, attempt = 1): FinishRequest {\n if (!this.dispatcher.installed) {\n // Fast path: no hook, no timing work at all.\n return () => {};\n }\n this.dispatcher.emit({ type: 'requestStart', operation, method, pathTemplate, attempt });\n const started = Date.now();\n return (status, outcome) => {\n this.dispatcher.emit({\n type: 'requestEnd',\n operation,\n method,\n pathTemplate,\n attempt,\n status,\n durationMs: Date.now() - started,\n outcome,\n });\n };\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, ClientIdentity, RefreshGuard } from '../core/index.js';\nimport {\n CERT_PEM_MARKER,\n createRefreshGuard,\n DEFAULT_CONNECT_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n resolveClientIdentity,\n} from '../core/index.js';\n\nconst PEM_MARKER = CERT_PEM_MARKER;\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 /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */\n readonly tenantId: string | undefined;\n /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */\n readonly tenantSlug: string | undefined;\n /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */\n readonly orgId: string | undefined;\n /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */\n readonly orgSlug: string | undefined;\n /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */\n readonly expectedIssuer: string | undefined;\n /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */\n readonly expectedAudience: string | undefined;\n /**\n * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`\n * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config\n * when the UUID was supplied, then updated from the access-token `tenant_id`\n * claim after each successful login/refresh (Node persona only — the browser\n * cannot read the httpOnly access-token cookie).\n */\n resolvedTenantId: string | undefined;\n /**\n * Resolved organization UUID used to build the `refresh` body. Seeded from\n * `orgId` config, then updated from the access-token `org_id` claim after a\n * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.\n */\n resolvedOrgId: string | undefined;\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.tenantId = options.tenantId;\n this.tenantSlug = options.tenantSlug;\n this.orgId = options.orgId;\n this.orgSlug = options.orgSlug;\n this.expectedIssuer = options.expectedIssuer;\n this.expectedAudience = options.expectedAudience;\n // Seed the resolved UUIDs from any UUID-form config so the browser persona\n // (which cannot decode the httpOnly access token) can still build a valid\n // refresh body. The Node persona later overwrites these from the\n // access-token claims (NodeSession#resolveIdentifiersFromToken).\n this.resolvedTenantId = options.tenantId;\n this.resolvedOrgId = options.orgId;\n this.refreshGuard = createRefreshGuard();\n }\n\n /**\n * Build the `POST /api/v1/auth/refresh` request body (§1). The server's\n * `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this\n * emits the resolved UUIDs — from the access-token claims after login, or\n * from UUID-form construction options as a fallback. Fields that could not\n * be resolved are omitted (the server then answers with a clear 400), rather\n * than sending a slug where a UUID is required.\n */\n buildRefreshBody(): Record<string, string> {\n const body: Record<string, string> = {};\n if (this.resolvedTenantId) {\n body.tenant_id = this.resolvedTenantId;\n }\n if (this.resolvedOrgId) {\n body.org_id = this.resolvedOrgId;\n }\n return body;\n }\n\n /**\n * Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the\n * configured tenant and organization identifiers (UUID or slug form) in\n * addition to the credentials — the server resolves the workspace from the\n * body, not the `X-Tenant-ID` header, and rejects a login that omits org\n * context. Undefined identifiers are omitted.\n */\n buildLoginBody(email: string, password: string): Record<string, string> {\n const body: Record<string, string> = { username_or_email: email, password };\n if (this.tenantId) {\n body.tenant_id = this.tenantId;\n }\n if (this.tenantSlug) {\n body.tenant_slug = this.tenantSlug;\n }\n if (this.orgId) {\n body.org_id = this.orgId;\n }\n if (this.orgSlug) {\n body.org_slug = this.orgSlug;\n }\n return body;\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` carrying the customCa server-trust PEM\n * (§6) and/or the mTLS client identity (§6.1). Guarded by\n * `typeof process !== 'undefined'` as a CAPABILITY guard (Node has node:https\n * available), NOT a persona-sniffing branch — browsers ignore both customCa\n * and the client certificate entirely since the platform manages TLS itself.\n *\n * The client cert/key (§6.1) is an ADDITIVE client credential: it is passed\n * as `{ cert, key }` alongside `{ ca }` and NEVER touches `rejectUnauthorized`\n * — strict server verification stays at its secure default. The private key is\n * exposed from its {@link ClientIdentity} `Sensitive` wrapper only here, at the\n * point of handing it to the TLS stack, and is not retained anywhere else.\n */\nfunction loadNodeHttps(): typeof import('node:https') {\n // Node >= 20.16 / >= 22.3: `process.getBuiltinModule` loads a builtin\n // SYNCHRONOUSLY with no module system involved — no `import`, no `require`,\n // nothing for a bundler to rewrite. That is the whole point here: this file\n // is shared with the browser-safe `.`/`/rest` entries, so it must never\n // statically reference a Node builtin, yet the Node persona needs one\n // synchronously (buildSession is called from a constructor).\n //\n // The previous `require('node:https')` satisfied the first constraint but\n // not the second: tsup rewrites a bare `require` in ESM output into a shim\n // that throws `Dynamic require of \"https\" is not supported`, so under\n // genuine Node ESM — which is what `axiam-sdk/node`'s `import` condition\n // resolves to — EVERY call needing customCa or a client certificate failed\n // before the TLS handshake. It is reached off `process`, which the caller\n // has already capability-guarded, so a browser bundle never evaluates it.\n const getBuiltinModule = (\n process as unknown as { getBuiltinModule?: (id: string) => unknown }\n ).getBuiltinModule;\n if (typeof getBuiltinModule === 'function') {\n return getBuiltinModule.call(process, 'node:https') as typeof import('node:https');\n }\n // Older Node (the package still declares engines.node >= 18). `require` is\n // real in the CJS build, so this keeps working there; in the ESM build it is\n // the throwing shim, and the catch turns that into an error that says what\n // to actually do instead of leaking a bundler implementation detail.\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require('node:https') as typeof import('node:https');\n } catch {\n throw new Error(\n `customCa and clientCert require Node's https module, which this ESM build cannot load on Node ${process.version}: ` +\n 'process.getBuiltinModule is unavailable (added in Node 20.16 / 22.3) and `require` does not exist in an ES module. ' +\n 'Upgrade Node to >= 20.16, or load the CommonJS build (CONTRACT.md §6 / §6.1).',\n );\n }\n}\n\nexport interface NodeTlsOptions {\n /** §6 server-trust PEM bundle. */\n ca?: string;\n /** §6.1 client-certificate chain (PEM). */\n cert?: string;\n /** §6.1 private key (PEM). Secret material — never logged or retained. */\n key?: string;\n}\n\n/**\n * The TLS material for a Node agent, or `undefined` when there is nothing to\n * configure. `rejectUnauthorized` is deliberately absent: strict server\n * verification stays at its secure default and this object never carries a\n * TLS-bypass switch (§6).\n *\n * Split out from {@link maybeBuildHttpsAgent} because the Node persona cannot\n * use a plain `https.Agent` at all — see {@link resolveNodeTlsOptions}.\n */\nfunction tlsOptionsFrom(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): NodeTlsOptions | undefined {\n if (!customCa) {\n // Still short-circuit only when there is nothing to configure at all.\n if (!identity) {\n return undefined;\n }\n } else 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 return {\n ...(customCa ? { ca: customCa } : {}),\n ...(identity ? { cert: identity.cert, key: identity.key.expose() } : {}),\n };\n}\n\n/**\n * Re-derive the Node TLS options from client options, for a persona that must\n * build its own agent rather than use the one {@link createSession} attaches.\n *\n * The Node persona is exactly that case. `axios-cookiejar-support`'s request\n * interceptor THROWS (\"does not support for use with other http(s).Agent\")\n * when it finds an `httpsAgent` it did not create, and otherwise overwrites\n * the agent with a bare `HttpsCookieAgent` — so under `createNodeClient` a\n * customCa or client certificate was either fatal or silently discarded,\n * independently of the ESM/require problem in {@link loadNodeHttps}. The Node\n * persona therefore constructs ONE agent that is both jar-aware and\n * TLS-configured (see `src/node/cookieJar.ts`), using these options.\n *\n * Not exported from the package barrel: the returned object holds the private\n * key (§6.1 rule 3 / §7), and its only legitimate consumer is the agent\n * construction inside this SDK.\n */\nexport function resolveNodeTlsOptions(options: AxiamClientOptions): NodeTlsOptions | undefined {\n return tlsOptionsFrom(options.customCa, resolveClientIdentity(options));\n}\n\nfunction maybeBuildHttpsAgent(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): unknown {\n const tls = tlsOptionsFrom(customCa, identity);\n if (!tls) {\n return undefined;\n }\n if (typeof process === 'undefined') {\n // Browser: platform manages TLS; customCa and the client cert have no\n // effect there (a browser cannot present a client certificate from JS).\n return undefined;\n }\n // Node capability guard — resolved lazily (see loadNodeHttps) so this\n // branch never executes, and never needs to resolve, in a browser bundle.\n const https = loadNodeHttps();\n return new https.Agent(tls);\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 // The mTLS client identity (§6.1) is likewise validated on every persona so\n // a one-of/bad-PEM misconfiguration throws identically in browser and Node,\n // even though only Node presents the certificate.\n const clientIdentity = resolveClientIdentity(options);\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);\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 (§9.3, §12.3 rule 3).\n *\n * Two groups:\n * - the refresh endpoint itself plus login/logout — not\n * authenticated-session-continuation calls, so refreshing would only build\n * an infinite loop;\n * - the `/oauth2/*` endpoints — they authenticate the *client* with\n * `client_id`/`client_secret`, not the user session. A `401` there is a\n * client-credential failure, not a session expiry, so retrying after a\n * session refresh cannot help and MUST NOT enter the §9 guard\n * (CONTRACT.md §12.3 rule 3). `oidcRefresh` reaches the §9 guard through\n * its own explicit call path instead (`OidcClient.oidcRefresh`).\n */\nexport const SKIP_REFRESH = [\n '/api/v1/auth/refresh',\n '/api/v1/auth/login',\n '/api/v1/auth/logout',\n '/oauth2/token',\n '/oauth2/introspect',\n '/oauth2/revoke',\n];\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', session.buildRefreshBody());\n // H8 fix: resync the Node persona's cached access token + CSRF\n // token after a reactive refresh too — see the matching fix\n // and comment on rest/auth.ts's explicit refresh(). Without\n // this the replayed request below (and every request after it)\n // echoes a stale X-CSRF-Token and 403s.\n await session.onAuthenticated?.();\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 // url + body are forwarded so the mapper can apply the\n // endpoint-qualified §2 row: a 401 from /oauth2/introspect or\n // /oauth2/revoke carrying an OAuth2ErrorResponse body becomes an\n // OAuthProtocolError rather than a bare AuthError (§12.3 rule 3).\n return Promise.reject(\n mapHttpStatusToError(401, 'authentication failed', {\n url,\n body: error.response.data,\n cause: error,\n }),\n );\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 { AxiamError, mapHttpStatusToError, NetworkError, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n MfaSetupRequiredResponseWire,\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 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\n/**\n * CONTRACT.md §25.2 rule 1 — the `403 mfa_setup_required` branch of `login`.\n *\n * The server answers `403` when the tenant requires MFA and the account has\n * none, and hands back the token to fix it. Mapping that through §2 to\n * `AuthzError` told the caller they lacked permission to log in, when what the\n * server said was recoverable and came with the means to recover. It is an\n * outcome, so it is returned rather than thrown.\n *\n * Matched on the body's own discriminant, not on the status alone: a genuine\n * authorization refusal is also a `403`, and only one of the two carries a\n * `setup_token`.\n *\n * Exported so `loginOpaque` shares it — that endpoint answers the identical\n * `403`, and a second copy of this check is a second place for the two to\n * disagree about what a setup branch looks like.\n *\n * @internal\n */\nexport function mfaSetupRequired(err: unknown): LoginResult | undefined {\n if (extractAxiosStatus(err) !== 403) return undefined;\n const body = extractAxiosData<Partial<MfaSetupRequiredResponseWire>>(err);\n if (body?.mfa_setup_required !== true || typeof body.setup_token !== 'string') {\n return undefined;\n }\n return { status: 'mfa_setup_required', setupToken: new Sensitive(body.setup_token) };\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\n // The server resolves the workspace from the login body (org + tenant), not\n // the X-Tenant-ID header, so tenant/org context must travel here (§5).\n const body = client.session.buildLoginBody(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 // §25.2 rule 1: a recoverable, guided state, not a refusal. Checked\n // before the guard below because a 403 is never pre-mapped: the response\n // interceptor pre-maps only 401 on a SKIP_REFRESH url, so an\n // `mfa_setup_required` 403 still arrives here as a raw AxiosError.\n const setup = mfaSetupRequired(err);\n if (setup) return setup;\n\n // Already an SDK error: the response interceptor mapped it. LOGIN_PATH is\n // a SKIP_REFRESH url, so a 401 here has ALREADY become an AuthError\n // before this catch runs. Such an error carries no axios `.response`, so\n // `extractAxiosStatus` below reports undefined and the final line used to\n // bury the AuthError inside a NetworkError — reporting wrong credentials\n // as a transport failure, and inconsistently with verifyMfa(), whose path\n // is not SKIP_REFRESH and so maps the identical 401 straight to AuthError.\n // Rethrowing unchanged is also what §23.4 rule 7's OPAQUE fallback needs:\n // it delegates to login() and returns that call's outcome verbatim.\n if (err instanceof AxiamError) throw err;\n\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\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 // Already mapped by the response interceptor — rethrow rather than bury\n // it in a NetworkError. MFA_VERIFY_PATH is not a SKIP_REFRESH url, so\n // nothing pre-maps a 401 here today; the guard keeps this path correct if\n // that list ever grows, and identical to its three siblings.\n if (err instanceof AxiamError) throw err;\n\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, client.session.buildRefreshBody());\n // H8 fix (SDK bench harness validation): a successful refresh rotates\n // the `axiam_csrf` cookie (new random token, CONTRACT.md §3) the same\n // way login does, but — unlike login/verifyMfa just below, which both\n // call `onAuthenticated?.()` — this path never resynced the Node\n // persona's in-memory `session.csrfToken` (only NodeSession.doRefresh\n // did that, and doRefresh is wired to gRPC's callWithRefresh only, never\n // to this REST path). Every REST call after the FIRST refresh() then\n // echoed a now-stale X-CSRF-Token and failed with 403 \"CSRF validation\n // failed\" — refresh() effectively broke the session after one use.\n // `onAuthenticated` is exactly the right hook to reuse: same\n // access/csrf resync as login, it's a no-op on the browser persona\n // (undefined there), and Node's implementation is idempotent.\n await client.session.onAuthenticated?.();\n } catch (err) {\n // REFRESH_PATH is a SKIP_REFRESH url, so a 401 here is already an\n // AuthError by the time this catch runs. §9.3 wants exactly that error\n // surfaced, not a NetworkError wrapping it.\n if (err instanceof AxiamError) throw err;\n\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 // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, not session, so any credential\n // change must drop them — otherwise a re-authentication as a different\n // principal inherits the previous one's decisions.\n client.decisionMemo.clear();\n try {\n await client.session.axios.post(LOGOUT_PATH, {});\n } catch (err) {\n // LOGOUT_PATH is a SKIP_REFRESH url — same pre-mapping as login/refresh.\n // The `finally` below still clears session state either way.\n if (err instanceof AxiamError) throw err;\n\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","/**\n * OPAQUE (RFC 9807) — the protocol half.\n *\n * This file contains **no cryptography**. Its predecessor, `core/srp.ts`, was\n * 419 lines of modular exponentiation, `PAD()` and SHA-256 transcript hashing,\n * because SRP is arithmetic every language can express and so every AXIAM\n * client wrote its own. OPAQUE is not — it needs an oblivious PRF,\n * `hash_to_curve`, `expand_message_xmd`, an envelope construction and a\n * three-message AKE — so CONTRACT.md §23.1 forbids an SDK from implementing\n * it, and this module is a loader around the one implementation the server and\n * every other SDK also use.\n *\n * # Loading\n *\n * `@axiam/opaque-wasm` is an **optional peer dependency**, resolved at runtime.\n * An installation that never touches the OPAQUE path should not be made to\n * carry a WebAssembly module, and a checkout without it must still build. When\n * it is absent, {@link opaqueAvailable} reports `false` and callers fall back\n * to password login — the posture §23.1 requires of an SDK whose native\n * artifact failed to load, and the reason it must *report* rather than throw at\n * login time.\n */\n\nimport { NetworkError } from './errors.js';\n\ntype OpaqueModule = typeof import('@axiam/opaque-wasm');\n\nlet modulePromise: Promise<OpaqueModule | null> | null = null;\n\n/**\n * The package specifier, held in a variable so bundlers do not try to resolve\n * it statically.\n *\n * This is the mechanism behind the graceful degradation above: a static\n * `import('@axiam/opaque-wasm')` is a hard resolution failure in an\n * installation that skipped the optional peer, which would make the whole SDK\n * unloadable for consumers who never wanted OPAQUE.\n */\nconst WASM_PACKAGE = '@axiam/opaque-wasm';\n\n/**\n * Load the WASM module once per process.\n *\n * Memoized on the *promise*, not the result, so two concurrent logins do not\n * instantiate the module twice. A failure is memoized too: retrying a package\n * that is not installed on every login would be a per-request cost for a file\n * that is not going to appear.\n */\nasync function loadModule(): Promise<OpaqueModule | null> {\n modulePromise ??= (async () => {\n try {\n const mod = (await import(/* @vite-ignore */ WASM_PACKAGE)) as OpaqueModule;\n await mod.default();\n return mod;\n } catch {\n return null;\n }\n })();\n return modulePromise;\n}\n\n/** Reset the memoized module. Test-only. */\nexport function __resetOpaqueModuleForTests(): void {\n modulePromise = null;\n}\n\n/**\n * Inject a module, bypassing the loader. Test-only.\n *\n * Exists because the dynamic specifier above is deliberately unresolvable at\n * build time, which also puts it out of reach of `vi.mock`.\n */\nexport function __setOpaqueModuleForTests(mod: unknown): void {\n modulePromise = Promise.resolve(mod as OpaqueModule);\n}\n\n/**\n * Whether this installation can perform OPAQUE at all (CONTRACT §23.2).\n *\n * Reports rather than throws, so a caller can decide to use the password path\n * before attempting a login rather than discovering it mid-exchange.\n */\nexport async function opaqueAvailable(): Promise<boolean> {\n const mod = await loadModule();\n return mod !== null && mod.opaqueAvailable();\n}\n\n/**\n * The key-stretching fields a `register/start` or `login/start` response\n * carries.\n *\n * Flat and optional, matching the wire format: the fields that do not apply to\n * the named function are **absent, not zero**. Reading an absent field as `0`\n * would stretch with the wrong cost and fail against a record that is\n * perfectly good — CONTRACT §23.4 rule 5.\n */\nexport interface OpaqueKsfFields {\n ksf: string;\n memory_kib?: number;\n iterations?: number;\n parallelism?: number;\n log_n?: number;\n r?: number;\n p?: number;\n}\n\n/** Accepted cost bands, matching `axiam_opaque::AxiamKsf` (§23.4 rule 4). */\nconst BOUNDS = {\n memory_kib: [8192, 1_048_576],\n iterations: [1, 10],\n parallelism: [1, 16],\n log_n: [14, 20],\n r: [1, 16],\n p: [1, 16],\n} as const;\n\nfunction requireInBand(name: keyof typeof BOUNDS, value: number | undefined, ksf: string): number {\n if (value === undefined) {\n throw new NetworkError(`OPAQUE: the server named ksf \\`${ksf}\\` without \\`${name}\\``);\n }\n const [min, max] = BOUNDS[name];\n if (!Number.isInteger(value) || value < min || value > max) {\n throw new NetworkError(\n `OPAQUE: the server named ${name}=${value} for \\`${ksf}\\`, outside the accepted ${min}..${max}`,\n );\n }\n return value;\n}\n\n/**\n * Build the stretching function from what the **server** named.\n *\n * Never from local defaults, and never cached across exchanges: a credential\n * enrolled under one cost keeps working after a tenant raises its policy, so a\n * client that guessed would derive a different randomized password and fail\n * against a record that is perfectly good (§23.4 rule 2).\n *\n * An unrecognised function is refused, never substituted — substituting\n * produces a well-formed randomized password that no AXIAM server agrees with,\n * surfacing to the user as a wrong password (§23.4 rule 3). The refusal is a\n * `NetworkError`, deliberately not an `AuthError`, so it cannot be mistaken for\n * bad credentials.\n */\nfunction buildKsf(mod: OpaqueModule, fields: OpaqueKsfFields) {\n switch (fields.ksf) {\n case 'argon2id':\n return mod.OpaqueKsf.argon2id(\n requireInBand('memory_kib', fields.memory_kib, fields.ksf),\n requireInBand('iterations', fields.iterations, fields.ksf),\n requireInBand('parallelism', fields.parallelism, fields.ksf),\n );\n case 'scrypt':\n return mod.OpaqueKsf.scrypt(\n requireInBand('log_n', fields.log_n, fields.ksf),\n requireInBand('r', fields.r, fields.ksf),\n requireInBand('p', fields.p, fields.ksf),\n );\n default:\n throw new NetworkError(\n `OPAQUE: this SDK cannot perform the key-stretching function the server named (\\`${fields.ksf}\\`)`,\n );\n }\n}\n\n/**\n * Raised when `@axiam/opaque-wasm` is not installed.\n *\n * A `NetworkError` subclass on purpose: §2 puts \"this client cannot do the\n * thing\" in the network/configuration bucket, never the credential one, so a\n * caller catching `NetworkError` falls back to password login without a special\n * case — while a caller that wants to tell \"not installed\" from \"tenant has it\n * disabled\" still can.\n */\nexport class OpaqueUnavailableError extends NetworkError {\n constructor() {\n super('OPAQUE is not available: install the optional peer dependency `@axiam/opaque-wasm`');\n this.name = 'OpaqueUnavailableError';\n // Re-set AFTER `super`, which pins the prototype to `NetworkError.prototype`\n // to survive transpilation to ES5. That is correct for `NetworkError` and\n // wrong for anything extending it: without this line\n // `err instanceof OpaqueUnavailableError` is false for an error that\n // demonstrably is one, and the distinction this class exists to draw\n // silently disappears.\n Object.setPrototypeOf(this, OpaqueUnavailableError.prototype);\n }\n}\n\nasync function requireModule(): Promise<OpaqueModule> {\n const mod = await loadModule();\n if (mod === null) throw new OpaqueUnavailableError();\n return mod;\n}\n\n/** One in-flight registration. */\nexport interface RegistrationExchange {\n readonly request: string;\n finish(registrationResponse: string, ksf: OpaqueKsfFields): string;\n}\n\n/** Begin an enrolment. The returned `request` goes to `register/start`. */\nexport async function startRegistration(password: string): Promise<RegistrationExchange> {\n const mod = await requireModule();\n const state = new mod.OpaqueRegistration(password);\n return {\n request: state.request,\n finish(registrationResponse, ksfFields) {\n return state.finish(password, registrationResponse, buildKsf(mod, ksfFields)).record;\n },\n };\n}\n\n/** One in-flight login. */\nexport interface LoginExchange {\n readonly ke1: string;\n finish(ke2: string, ksf: OpaqueKsfFields): string;\n}\n\n/** Begin a login. The returned `ke1` goes to `login/start`. */\nexport async function startLogin(password: string): Promise<LoginExchange> {\n const mod = await requireModule();\n const state = new mod.OpaqueLogin(password);\n return {\n ke1: state.ke1,\n finish(ke2, ksfFields) {\n return state.finish(password, ke2, buildKsf(mod, ksfFields)).ke3;\n },\n };\n}\n","// loginOpaque / opaqueEnrollment — the OPAQUE (RFC 9807) login path\n// (CONTRACT.md §23).\n//\n// A sibling of `login`, not a replacement. It establishes the same fact — this\n// principal knows the password — by a route that never puts the password on the\n// wire, and returns the **same** `LoginResult`, so an application can switch a\n// tenant to OPAQUE without touching its own code.\n//\n// The protocol lives in `core/opaque.ts`, which is a loader around the one\n// shared implementation and performs no I/O; this module is the HTTP calls and\n// the policy around them.\n\nimport { NetworkError, mapHttpStatusToError, sanitizeAxiosError } from '../core/index.js';\nimport {\n OpaqueUnavailableError,\n startLogin,\n startRegistration,\n type OpaqueKsfFields,\n} from '../core/opaque.js';\nimport { login, mfaSetupRequired } from './auth.js';\nimport type { AxiamClient } from './client.js';\nimport type { LoginResult, LoginSuccessResponseWire, MfaRequiredResponseWire } from './types.js';\n\nconst OPAQUE_REGISTER_START_PATH = '/api/v1/auth/opaque/register/start';\nconst OPAQUE_LOGIN_START_PATH = '/api/v1/auth/opaque/login/start';\nconst OPAQUE_LOGIN_FINISH_PATH = '/api/v1/auth/opaque/login/finish';\n\ninterface LoginStartWire extends OpaqueKsfFields {\n opaque_session: string;\n ke2: string;\n suite: string;\n /**\n * The tenant's `opaque_mode` — `\"optional\"` or `\"required\"`, never\n * `\"disabled\"` (that path answers `404`). Absent from a server older than\n * the field, and read only by §23.4 rule 7's failure branch.\n *\n * It is **not** downgrade protection and must not be presented as such: a\n * hostile server that wanted the plaintext could answer `404` and get the\n * fallback whatever it put here. `required` is what closes that, server-side,\n * by refusing `/auth/login` before examining any credential.\n */\n mode?: string | null;\n}\n\ninterface RegisterStartWire extends OpaqueKsfFields {\n opaque_session: string;\n registration_response: string;\n suite: string;\n}\n\n/**\n * A completed enrolment, to send with any request that sets a password.\n *\n * Two fields, where the SRP verifier it replaces had seven. The server chose\n * the credential identifier, the ciphersuite and the costs and sealed them into\n * `opaque_session` — which is why a client cannot name any of them, and why it\n * cannot enrol a record against somebody else's account.\n */\nexport interface OpaqueEnrollment {\n /**\n * The `opaque_session` from `register/start`, echoed **verbatim**.\n *\n * Opaque sealed server state carrying the credential identifier, the\n * ciphersuite and the costs. Do not parse, cache, or reuse it across\n * exchanges (§23.4 rule 8) — it is valid for 120 seconds.\n */\n opaque_session: string;\n /** Lowercase-hex serialized RFC 9807 `RegistrationRecord`. */\n registration_record: string;\n}\n\nfunction axiosStatus(err: unknown): number | undefined {\n return (err as { response?: { status?: number } })?.response?.status;\n}\n\nfunction axiosMessage(err: unknown): string {\n return (err as { message?: string })?.message ?? 'request failed';\n}\n\n/**\n * Perform a full OPAQUE login (CONTRACT.md §23).\n *\n * Returns the same `LoginResult` as `login`, including the MFA-challenge case,\n * so a caller needs one result handler for both.\n *\n * ## What this does that `login` does not\n *\n * The password never leaves this process. What crosses the wire is a blinded\n * group element and a MAC, neither useful without the account's record **and**\n * the tenant's OPRF seed — so a TLS-terminating proxy, an accidentally verbose\n * request log or a heap dump on the server cannot capture a plaintext password,\n * because the server never has one. It also means a stolen record database is\n * not offline-crackable on its own, which is the property SRP could not offer.\n *\n * It does **not** protect against a compromised AXIAM server, and in a browser\n * it does not protect against AXIAM serving malicious JavaScript.\n *\n * ## What a caller no longer has to do\n *\n * Under SRP this returned only after verifying the server's `M2`, and §23.3\n * rule 6 had to mandate that in capitals because skipping it kept only the half\n * of the protocol that authenticates the client. RFC 9807's AKE authenticates\n * the server during the handshake — opening `KE2` *is* the proof that the\n * server holds the record — so there is no separate check and no way to omit\n * one.\n *\n * ## Errors\n *\n * - `NetworkError` when the tenant has OPAQUE disabled (`404` — a property of\n * the tenant, not of any user), when `@axiam/opaque-wasm` is not installed,\n * and when the server names a KSF this SDK cannot perform. These are\n * configuration or client-side faults, deliberately **not** `AuthError`:\n * reporting them as a credential failure would send a user off to reset a\n * password that works, and would stop a caller falling back to `login()`.\n * - `AuthError` for a wrong password, an account that does not exist, and a\n * server that does not hold the record — indistinguishable by design.\n * **Nothing is sent to `login/finish` in that case** (§23.4 rule 7), and a\n * caller must not retry it over `login()`: under `mode: \"optional\"` this call\n * has already done so (see below), and in every other case that would hand\n * the plaintext to a server that just failed to prove itself.\n *\n * ## The one case that is not a failure — §23.4 rule 7\n *\n * When the tenant's `login/start` response says `mode: \"optional\"`, a failed\n * exchange is not yet a verdict on the credentials: under `optional` every\n * account starts with no registration record and acquires one only when its\n * password is next set, so this call retries over `POST /api/v1/auth/login`\n * with the same credentials and returns that call's outcome — its success on\n * success, its error on failure. Without that, enabling `optional` would lock\n * out every user of a tenant mid-migration.\n *\n * `required`, a response with no `mode` field (a server older than it), and\n * any unrecognised value all fail closed: `AuthError`, no retry, no plaintext\n * password on the wire.\n *\n * `mode` is **not** downgrade protection and is not treated as such — a\n * hostile server that wanted the plaintext could simply answer `404` and get\n * the caller's own fallback. `required` is what closes that, server-side, by\n * refusing `/auth/login` for every principal before examining any credential.\n *\n * ## Cost\n *\n * Runs the tenant's key-stretching function: Argon2id at 19 MiB by default,\n * tens to hundreds of milliseconds of synchronous work. That cost is the point\n * — it is what makes a stolen record expensive to attack even by someone\n * holding the OPRF seed. In a browser, consider a Web Worker.\n */\nexport async function loginOpaque(\n client: AxiamClient,\n usernameOrEmail: string,\n password: string,\n): Promise<LoginResult> {\n // §18.1 rule 4: use-after-close is an error, not a reconnect.\n client.ensureOpen();\n // §17.1 rule 9: entries are keyed by subject, so any credential change must\n // drop them, or a re-authentication as a different principal inherits the\n // previous one's decisions.\n client.decisionMemo.clear();\n\n const exchange = await startLogin(password);\n\n // Reuses the login body builder so tenant/org resolution cannot drift between\n // the two login paths. The password field is deleted rather than sent — it\n // has no business on this request, and this is the assertion the tests make.\n const body: Record<string, string> = {\n ...client.session.buildLoginBody(usernameOrEmail, ''),\n ke1: exchange.ke1,\n };\n delete body.password;\n\n let started: LoginStartWire;\n try {\n const response = await client.session.axios.post<LoginStartWire>(\n OPAQUE_LOGIN_START_PATH,\n body,\n );\n started = response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status === 404) {\n throw new NetworkError(\n 'this tenant does not offer OPAQUE (opaque_mode is disabled); use login() instead',\n );\n }\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE login/start request failed', sanitizeAxiosError(err));\n }\n\n // The whole of the client's authentication check. A failure covers both\n // halves of the mutual authentication — the envelope only opens under the\n // right password, and KE2's MAC only verifies if the server holds the record\n // — and nothing further may be sent.\n //\n // A KSF the SDK cannot perform throws `NetworkError` from `buildKsf` and is\n // deliberately allowed to propagate rather than being flattened into an\n // authentication failure.\n let ke3: string;\n try {\n ke3 = exchange.finish(started.ke2, started);\n } catch (err) {\n if (err instanceof NetworkError) throw err;\n // §23.4 rule 7: what happens next depends on `mode`, and only on that.\n //\n // Under `optional` an account with no record is the ordinary case rather\n // than an error — every account has none the moment an operator enables\n // OPAQUE, and they acquire one only as they next set a password — so the\n // failed exchange is not yet a verdict on the credentials. Treating it as\n // final would lock out every user of a tenant mid-migration, which is the\n // state `optional` exists to serve. The retry goes through `login` itself,\n // so the two paths cannot drift on body building, MFA branches or errors.\n //\n // Anything else — `required`, no `mode` at all (a server older than the\n // field), or a value this SDK does not recognise — fails closed: the\n // exchange is over, and no plaintext password goes on the wire.\n if (started.mode === 'optional') {\n return await login(client, usernameOrEmail, password);\n }\n throw mapHttpStatusToError(401, 'invalid credentials', { cause: err });\n }\n\n let response;\n try {\n response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n OPAQUE_LOGIN_FINISH_PATH,\n { opaque_session: started.opaque_session, ke3 },\n );\n } catch (err) {\n // §25.2 rule 1 — this endpoint answers the same `403 mfa_setup_required`\n // as `POST /api/v1/auth/login`, and it is the same outcome here.\n const setup = mfaSetupRequired(err);\n if (setup) return setup;\n\n const status = axiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE login/finish request failed', sanitizeAxiosError(err));\n }\n\n if (response.status === 202) {\n const wire = response.data as MfaRequiredResponseWire;\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n }\n\n const wire = response.data as LoginSuccessResponseWire;\n client.session.authenticated = true;\n await client.session.onAuthenticated?.();\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\n/**\n * Build a registration record for `password`, to send with any request that\n * sets one (user creation, change-password, reset completion).\n *\n * This performs a `register/start` round trip, which the SRP verifier it\n * replaces did not need: OPAQUE's envelope is sealed under the server's\n * oblivious PRF, so there is no offline computation that produces a valid\n * record.\n *\n * Note the absence of an `identity` argument. The SRP version required the\n * account's canonical username, and passing an email produced a verifier no\n * login could ever satisfy. A record binds to a credential identifier the\n * server chooses, so there is nothing here to get wrong — and a later rename\n * cannot invalidate it.\n */\nexport async function opaqueEnrollment(\n client: AxiamClient,\n password: string,\n): Promise<OpaqueEnrollment> {\n client.ensureOpen();\n\n const exchange = await startRegistration(password);\n\n const body: Record<string, string> = {\n ...client.session.buildLoginBody('', ''),\n registration_request: exchange.request,\n };\n delete body.password;\n delete body.username_or_email;\n\n let started: RegisterStartWire;\n try {\n const response = await client.session.axios.post<RegisterStartWire>(\n OPAQUE_REGISTER_START_PATH,\n body,\n );\n started = response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status === 404) {\n throw new NetworkError('this tenant does not offer OPAQUE (opaque_mode is disabled)');\n }\n if (status !== undefined) {\n throw mapHttpStatusToError(status, axiosMessage(err), { cause: err });\n }\n throw new NetworkError('OPAQUE register/start request failed', sanitizeAxiosError(err));\n }\n\n return {\n opaque_session: started.opaque_session,\n registration_record: exchange.finish(started.registration_response, started),\n };\n}\n\nexport { OpaqueUnavailableError };\nexport { opaqueAvailable } from '../core/opaque.js';\n","// Bounded read-only retry policy — CONTRACT.md §16.\n//\n// This file previously held a policy of its own invention: 1000 ms base, 8 s\n// cap, partial jitter (`base + 0–20%`), and `Retry-After` *replacing* the\n// computed backoff rather than flooring it. Two problems with that, both now\n// fixed:\n//\n// * `retryAfterMs ?? backoffDelayMs(attempt)` meant a `Retry-After: 0`\n// retried immediately, defeating the backoff entirely — exactly what\n// §16.1's \"floor, never a ceiling\" forbids.\n// * It was exported and unit-tested but **never called by any production\n// path**. `checkAccess` did not route through it, so this SDK performed no\n// read-only retries at all while appearing to. A tested helper nobody calls\n// is worse than an absent one: the green tests are what stop anyone from\n// looking.\n//\n// §16 is the normative table all eleven SDKs now share. `withRetry` is wired\n// into the authz surface in `authz.ts`; the §16.7 tests assert the policy\n// through the public `checkAccess` API, not just against this helper.\n\nimport { NetworkError } from '../core/index.js';\nimport type { TelemetryDispatcher } from '../core/telemetry.js';\n\n/** Attempt cap: 1 initial + 2 retries (§16.1). */\nexport const MAX_ATTEMPTS = 3;\n/** First backoff step, in milliseconds (§16.1). */\nexport const BASE_DELAY_MS = 200;\n/** Ceiling on any single computed backoff, in milliseconds (§16.1). */\nexport const MAX_DELAY_MS = 5_000;\n\n/** Options controlling {@link withRetry}. */\nexport interface RetryOptions {\n /**\n * Only operations that change **no server state** may be retried (§16.2).\n *\n * Note this means side-effect-free, **not** \"is an HTTP GET\": AXIAM's\n * authorization check is a `POST` with a request body and is the single most\n * important operation covered by this policy.\n */\n idempotent: boolean;\n /** Canonical operation name, for the §19 `retry` event. */\n operation?: string;\n /** Set `false` to disable retrying entirely (§16.1 disable switch). */\n enabled?: boolean;\n /** §19 sink, notified before each retry wait. */\n telemetry?: TelemetryDispatcher;\n /** Injected for tests — see §16.7 (\"a test that really waits 200 ms is a test nobody runs\"). */\n sleepFn?: (ms: number) => Promise<void>;\n /** Injected for tests: returns the jitter fraction in [0, 1]. */\n randomFn?: () => number;\n}\n\ninterface RetryAfterCarrier {\n retryAfterMs?: number;\n}\n\nfunction isRetryAfterCarrier(err: unknown): err is RetryAfterCarrier {\n return typeof err === 'object' && err !== null && 'retryAfterMs' in err;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The un-jittered backoff for a 1-based attempt: `min(cap, base * 2^(n-1))`.\n * Attempt 1 → 200 ms, attempt 2 → 400 ms.\n */\nexport function backoffMs(attempt: number): number {\n return Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attempt - 1));\n}\n\n/**\n * The actual wait: **full jitter** over `[0, backoff]`, then raised to any\n * server-supplied `Retry-After` (§16.1).\n *\n * Full jitter, not `backoff ± 10%`. Partial jitter keeps every client's retries\n * clustered around the same instant, which is the thundering herd retries are\n * supposed to prevent rather than cause.\n *\n * `Retry-After` is a **floor, never a ceiling**: the server is saying when it\n * will be ready, so retrying sooner is not permitted — and a `Retry-After: 0`\n * cannot shorten the wait below what jitter chose.\n */\nexport function delayMs(attempt: number, retryAfterMs: number | undefined, fraction: number): number {\n const jittered = backoffMs(attempt) * Math.min(Math.max(fraction, 0), 1);\n return retryAfterMs === undefined ? jittered : Math.max(jittered, retryAfterMs);\n}\n\n/**\n * Runs `fn` under the §16 policy.\n *\n * `fn` receives the 1-based attempt number so it can label its §19\n * `requestStart`/`requestEnd` pair. That is not cosmetic: §19.2 rule 5 requires\n * one pair **per attempt** with the attempt distinguishing them, so a caller\n * can count real wire calls. Emitting every pair as attempt 1 would make a\n * retried call indistinguishable from a single slow one — the exact blindness\n * §16.5 exists to remove.\n *\n * `fn` MUST be side-effect-free. This helper — like every retry helper — cannot\n * tell the difference, so routing a mutation through it would silently\n * duplicate a side effect, or replay a single-use credential (an authorization\n * code, a device code at redemption, a rotating refresh token) into a hard\n * `invalid_grant`.\n *\n * Only `NetworkError` is retried. The §2 taxonomy folds `408`/`429`/`5xx`/\n * transport into that one type, so this implements the whole §16.3 table:\n * `AuthError` and `AuthzError` are decisive answers, not transport failures.\n */\nexport async function withRetry<T>(\n fn: (attempt: number) => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const retryable = options.idempotent && options.enabled !== false;\n const maxAttempts = retryable ? MAX_ATTEMPTS : 1;\n const sleep = options.sleepFn ?? defaultSleep;\n const random = options.randomFn ?? Math.random;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n return await fn(attempt);\n } catch (err) {\n const isLastAttempt = attempt === maxAttempts;\n if (!retryable || !(err instanceof NetworkError) || isLastAttempt) {\n throw err;\n }\n const retryAfterMs = isRetryAfterCarrier(err) ? err.retryAfterMs : undefined;\n const delay = delayMs(attempt, retryAfterMs, random());\n // §16.5 — without this event a retried-then-succeeded call is invisible:\n // a slow success with no signal that the server is failing.\n options.telemetry?.emit({\n type: 'retry',\n operation: options.operation ?? 'unknown',\n attempt,\n delayMs: delay,\n reason: err instanceof Error ? err.message : String(err),\n });\n await sleep(delay);\n }\n }\n\n // Unreachable: the loop above always returns or throws.\n throw new NetworkError('retry loop exhausted without a result');\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 { memoKey } from '../core/decisionMemo.js';\nimport { withRetry } from './retry.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 // §11 rule 9: `reason_code` is surfaced verbatim, including a value this\n // SDK has never heard of — the outcome is carried by `allowed` alone, so an\n // unknown code can never change it.\n return { allowed: wire.allowed, reason: wire.reason, reasonCode: wire.reason_code };\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 client.ensureOpen();\n\n // §17: consult the decision memo first. Disabled by default, in which case\n // this is one map lookup that always misses.\n const key = memoKey(check);\n const memoized = client.decisionMemo.get(key);\n if (memoized) return memoized;\n\n // §16: a `POST`, but side-effect-free, so it is retry-eligible. Eligibility\n // is \"changes no server state\", NOT \"is a GET\" — gating on the verb would\n // exclude the single most important operation this policy covers.\n const decision = await withRetry(\n (attempt) => attemptCheck(client, check, attempt),\n client.retryOptions('checkAccess'),\n );\n\n // Only a decision the server actually returned is memoized: reaching here\n // means success, so §17.1 rule 7's ban on negative-caching a failure is\n // structural rather than a check that could be forgotten.\n client.decisionMemo.set(key, decision);\n return decision;\n}\n\n/** One attempt at the single-check call, with its §19 event pair. */\nasync function attemptCheck(\n client: AxiamClient,\n check: AccessCheck,\n attempt: number,\n): Promise<AccessDecision> {\n const done = client.telemetry.startRequest('checkAccess', 'POST', CHECK_PATH, attempt);\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n done(response.status, 'success');\n return fromWireDecision(response.data);\n } catch (err) {\n done(statusOf(err), 'failure');\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 client.ensureOpen();\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n return withRetry(async (attempt) => {\n const done = client.telemetry.startRequest('batchCheck', 'POST', BATCH_CHECK_PATH, attempt);\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n done(response.status, 'success');\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n done(statusOf(err), 'failure');\n throw mapAuthzError(err);\n }\n }, client.retryOptions('batchCheck'));\n}\n\n/** The HTTP status an axios-shaped error carries, if any. */\nfunction statusOf(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { status?: number } }).response?.status;\n }\n return undefined;\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","// WebAuthn / passkeys — the relying-party layer (CONTRACT.md §24.1–§24.5).\n//\n// Six wire operations. None of them touches an authenticator: that is §24.6,\n// which lives in `axiam-sdk/browser` because it needs a DOM. These six are the\n// half of a ceremony that talks to AXIAM, and they work identically in Node —\n// a service completing a ceremony its native client ran is the relying party\n// here, exactly as a browser is.\n//\n// The rule everything below obeys is §24.0: the server chooses every option\n// and verifies every response, so this module carries both through untouched.\n// It does not default a field, does not normalize one, and does not re-encode\n// a buffer.\n\nimport { mapHttpStatusToError, NetworkError, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCredential,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnWorkspace,\n} from './webauthnTypes.js';\n\nconst REGISTER_START = '/api/v1/auth/webauthn/register/start';\nconst REGISTER_FINISH = '/api/v1/auth/webauthn/register/finish';\nconst AUTH_START = '/api/v1/auth/webauthn/authenticate/start';\nconst AUTH_FINISH = '/api/v1/auth/webauthn/authenticate/finish';\nconst DISCOVERABLE_START = '/api/v1/auth/webauthn/authenticate/discoverable/start';\nconst DISCOVERABLE_FINISH = '/api/v1/auth/webauthn/authenticate/discoverable/finish';\n\n// ---------------------------------------------------------------------------\n// Public result types\n// ---------------------------------------------------------------------------\n\n/**\n * A started ceremony: the server's challenge, plus the state token that binds\n * a response to it.\n *\n * `stateToken` is `Sensitive` (§24.5) — it is a bearer credential for the\n * length of the ceremony, and one that leaks inside that window is a ceremony\n * an attacker can try to complete. Pass it straight back to the matching\n * `*Finish` call; the SDK never decodes it and neither should a caller.\n */\nexport interface WebauthnRegistrationChallenge {\n /** The server's options. Hand them to the authenticator unchanged (§24.0). */\n challenge: WebauthnCreationChallenge;\n /** Binds the authenticator's answer to this challenge. Pass it back to `webauthnRegisterFinish`. */\n stateToken: Sensitive<string>;\n}\n\n/** A started authentication ceremony (both the second-factor and discoverable forms). */\nexport interface WebauthnAuthenticationChallenge {\n /** The server's options. Hand them to the authenticator unchanged (§24.0). */\n challenge: WebauthnRequestChallenge;\n /** Binds the authenticator's answer to this challenge. Pass it back to the matching `*Finish`. */\n stateToken: Sensitive<string>;\n}\n\n/**\n * The outcome of a completed passkey sign-in.\n *\n * The client is **already authenticated** when this resolves (§24.3 rule 1) —\n * the tokens are returned as well because a caller may want to hand them\n * onward, not because adoption is optional.\n */\nexport interface WebauthnLoginResult {\n /** The new access token. Already adopted by this client (§24.3 rule 1). */\n accessToken: Sensitive<string>;\n /** The session refresh token — refreshed through `refresh()`, not `oidcRefresh` (§24.3 rule 5). */\n refreshToken: Sensitive<string>;\n /** Opaque identifier for the session just created. */\n sessionId: string;\n /** Access-token lifetime in seconds, from the time of this response. */\n expiresIn: number;\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes\n// ---------------------------------------------------------------------------\n\ninterface StartRegistrationWire {\n challenge: WebauthnCreationChallenge;\n state_token: string;\n}\ninterface StartAuthenticationWire {\n challenge: WebauthnRequestChallenge;\n state_token: string;\n}\ninterface CredentialWire {\n id: string;\n credential_id: string;\n name: string;\n credential_type: string;\n created_at: string;\n last_used_at?: string | null;\n}\ninterface WebauthnLoginWire {\n access_token: string;\n refresh_token: string;\n session_id: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// Registration — requires an authenticated session (§24.1)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/register/start` (§24.1).\n *\n * Enrolling a passkey is something a signed-in user does to their own account,\n * so this requires a session and fails **client-side with no wire call** when\n * there is none.\n *\n * A `503` here means the tenant's attestation policy requires attestation and\n * the FIDO metadata service has no usable snapshot. That is a server\n * configuration state, not a transient failure, so it is surfaced as a\n * `AxiamError` and — per §24.4 rule 2 — deliberately **not** retried.\n */\nexport async function webauthnRegisterStart(\n client: AxiamClient,\n): Promise<WebauthnRegistrationChallenge> {\n client.ensureOpen();\n requireSession(client, 'webauthnRegisterStart');\n\n const wire = await post<StartRegistrationWire>(client, REGISTER_START, {}, 'webauthnRegisterStart');\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/**\n * `POST /api/v1/auth/webauthn/register/finish` (§24.1).\n *\n * `response` goes to the server exactly as the authenticator produced it\n * (§24.0 rule 3).\n *\n * A `403` is the tenant's attestation policy refusing **this authenticator** —\n * an AAGUID that is not allow-listed, a missing FIDO certification, a revoked\n * status. It is not a permission problem with the user, and the server's\n * message is surfaced verbatim (§24.4 rule 1) because it is the only way the\n * person holding the key learns that a different one would work.\n */\nexport async function webauthnRegisterFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n credentialName: string,\n response: WebauthnRegistrationResponse | string,\n): Promise<WebauthnCredential> {\n client.ensureOpen();\n requireSession(client, 'webauthnRegisterFinish');\n\n const wire = await post<CredentialWire>(\n client,\n REGISTER_FINISH,\n {\n state_token: expose(stateToken),\n credential_name: credentialName,\n response: asResponse(response, 'webauthnRegisterFinish'),\n },\n 'webauthnRegisterFinish',\n );\n\n return {\n id: wire.id,\n credentialId: wire.credential_id,\n name: wire.name,\n credentialType: wire.credential_type,\n createdAt: wire.created_at,\n ...(wire.last_used_at ? { lastUsedAt: wire.last_used_at } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Authentication as a second factor (§24.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/start` (§24.1).\n *\n * The **second-factor** ceremony: it continues a `login()` that answered\n * `mfa_required` and listed `\"webauthn\"` among its methods. `challengeToken`\n * is that result's `mfaToken`.\n *\n * This is a different flow from {@link webauthnDiscoverableStart}, not the\n * same one with an optional argument — see §24.2 for why they cannot be\n * merged.\n */\nexport async function webauthnAuthenticateStart(\n client: AxiamClient,\n challengeToken: Sensitive<string> | string,\n): Promise<WebauthnAuthenticationChallenge> {\n client.ensureOpen();\n const wire = await post<StartAuthenticationWire>(\n client,\n AUTH_START,\n { challenge_token: expose(challengeToken) },\n 'webauthnAuthenticateStart',\n );\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/** `POST /api/v1/auth/webauthn/authenticate/finish` (§24.1). Adopts the session (§24.3). */\nexport async function webauthnAuthenticateFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n): Promise<WebauthnLoginResult> {\n return finishSignIn(client, AUTH_FINISH, stateToken, response, 'webauthnAuthenticateFinish');\n}\n\n// ---------------------------------------------------------------------------\n// Usernameless (discoverable) authentication (§24.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/discoverable/start` (§24.1).\n *\n * The **primary-factor** ceremony: nothing precedes it, the server sends an\n * empty `allowCredentials`, and the assertion itself identifies the user.\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant's isolation boundary — but the SDK fills it from its own\n * configured identity, and this endpoint accepts slugs, so a slug-only client\n * can run the ceremony.\n */\nexport async function webauthnDiscoverableStart(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n): Promise<WebauthnAuthenticationChallenge> {\n client.ensureOpen();\n\n const body = resolveWorkspace(client, workspace);\n const wire = await post<StartAuthenticationWire>(\n client,\n DISCOVERABLE_START,\n body,\n 'webauthnDiscoverableStart',\n );\n return { challenge: wire.challenge, stateToken: new Sensitive(wire.state_token) };\n}\n\n/**\n * `POST /api/v1/auth/webauthn/authenticate/discoverable/finish` (§24.1).\n * Adopts the session (§24.3).\n *\n * Unlike its username-bound twin this fires the server's `login.post_auth`\n * reactor hook (§22.5): there was no password step for the event to have been\n * fired at.\n */\nexport async function webauthnDiscoverableFinish(\n client: AxiamClient,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n): Promise<WebauthnLoginResult> {\n return finishSignIn(\n client,\n DISCOVERABLE_FINISH,\n stateToken,\n response,\n 'webauthnDiscoverableFinish',\n );\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/**\n * The shared tail of both authentication ceremonies.\n *\n * §24.3 rule 1: a completed passkey sign-in leaves the client authenticated,\n * in exactly the state `login()` leaves it. This is not §14.3's \"MAY adopt\"\n * posture — `deviceLogin` mints tokens a caller may want to route elsewhere,\n * and this is the SDK's own primary authentication. Returning a token set\n * without adopting it would make `webauthnLogin()` the one way to log in that\n * does not log you in.\n */\nasync function finishSignIn(\n client: AxiamClient,\n path: string,\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n operation: string,\n): Promise<WebauthnLoginResult> {\n client.ensureOpen();\n // §17.1 rule 9 / §24.3 rule 4: memo entries are keyed by subject, and this\n // call changes the subject.\n client.decisionMemo.clear();\n\n const wire = await post<WebauthnLoginWire>(\n client,\n path,\n { state_token: expose(stateToken), response: asResponse(response, operation) },\n operation,\n );\n\n client.session.authenticated = true;\n // Syncs the Node persona's csrfToken (and cached access token) out of the\n // jar. Load-bearing since the server started setting the cookie triple on\n // these two endpoints: without it the first state-changing call after a\n // passkey sign-in echoes no `X-CSRF-Token` and is refused (§24.3 rule 2).\n await client.session.onAuthenticated?.();\n\n return {\n accessToken: new Sensitive(wire.access_token),\n refreshToken: new Sensitive(wire.refresh_token),\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\n/**\n * §24.1: `register/*` needs a session, and the failure is raised client-side\n * with no wire call — the same shape §1.1 rule 3 requires of `getUserInfo`.\n */\nfunction requireSession(client: AxiamClient, operation: string): void {\n if (!client.session.authenticated) {\n throw mapHttpStatusToError(\n 401,\n `${operation} requires an authenticated session: enrol a passkey while signed in ` +\n '(CONTRACT.md §24.1).',\n );\n }\n}\n\n/**\n * Fill the discoverable ceremony's workspace from the client's own configured\n * identity when the caller passed none.\n *\n * Only the fields that actually have a value are emitted: the server takes\n * either form for either level, and sending `null` for the ones it does not\n * have would be indistinguishable from asking it to resolve nothing.\n */\nfunction resolveWorkspace(\n client: AxiamClient,\n workspace: WebauthnWorkspace | undefined,\n): Record<string, string> {\n const merged: WebauthnWorkspace = {\n orgId: workspace?.orgId ?? client.session.orgId,\n orgSlug: workspace?.orgSlug ?? client.session.orgSlug,\n tenantId: workspace?.tenantId ?? client.session.tenantId,\n tenantSlug: workspace?.tenantSlug ?? client.session.tenantSlug,\n };\n\n const body: Record<string, string> = {};\n if (merged.orgId) body.org_id = merged.orgId;\n if (merged.orgSlug) body.org_slug = merged.orgSlug;\n if (merged.tenantId) body.tenant_id = merged.tenantId;\n if (merged.tenantSlug) body.tenant_slug = merged.tenantSlug;\n\n if (!body.org_id && !body.org_slug) {\n throw mapHttpStatusToError(\n 400,\n 'webauthnDiscoverableStart needs an organization: construct the client with an org, or pass ' +\n 'one in the workspace argument (CONTRACT.md §24.1).',\n );\n }\n if (!body.tenant_id && !body.tenant_slug) {\n throw mapHttpStatusToError(\n 400,\n 'webauthnDiscoverableStart needs a tenant: construct the client with one, or pass it in the ' +\n 'workspace argument (CONTRACT.md §24.1).',\n );\n }\n return body;\n}\n\nfunction expose(token: Sensitive<string> | string): string {\n return typeof token === 'string' ? token : token.expose();\n}\n\n/**\n * Accept either the typed response or the platform's own JSON string (§24.6a\n * rule 2).\n *\n * Android's Credential Manager hands back `registrationResponseJson` /\n * `authenticationResponseJson`, and a browser hands back `credential.toJSON()`.\n * Requiring a caller to destructure one of those into a typed value that this\n * SDK immediately re-serializes is three chances to corrupt a signed buffer in\n * service of nothing — so the string is taken directly.\n *\n * Parsing is value-preserving: every field in these messages is a string or a\n * plain object, so what reaches the server is what the authenticator produced.\n * Key order can differ, which JSON does not ascribe meaning to and the server\n * does not read.\n */\nfunction asResponse<T>(response: T | string, operation: string): T {\n if (typeof response !== 'string') return response;\n try {\n return JSON.parse(response) as T;\n } catch (err) {\n throw new TypeError(\n `${operation}: the authenticator response string is not valid JSON. Pass the platform's ` +\n 'response JSON verbatim (CONTRACT.md §24.6a).',\n { cause: err },\n );\n }\n}\n\n/**\n * The challenge in the JSON form every platform authenticator API takes\n * (§24.6a rule 1).\n *\n * This is the string an Android app passes to\n * `CreatePublicKeyCredentialRequest` or `GetPublicKeyCredentialOption`, and the\n * value a browser passes to `PublicKeyCredential.parseCreationOptionsFromJSON()`.\n * It is the inner options object — the `publicKey` wrapper is what the DOM's\n * `CredentialCreationOptions` adds, and the platform JSON APIs do not want it.\n *\n * Pure local computation, no I/O. Nothing is defaulted, dropped or reordered on\n * the way through (§24.0).\n */\nexport function webauthnRequestJson(\n challenge: WebauthnCreationChallenge | WebauthnRequestChallenge,\n): string {\n return JSON.stringify(challenge.publicKey);\n}\n\n/**\n * POST a JSON body and map failures through the §2 taxonomy.\n *\n * Not routed through §16's retry helper, and that is deliberate for the whole\n * section: five of the six operations are ceremony steps that consume\n * server-side state, and the sixth (`register/start`) has the `503` §24.4\n * rule 2 forbids retrying. There is nothing here a bounded retry could help.\n */\nasync function post<T>(\n client: AxiamClient,\n path: string,\n body: unknown,\n operation: string,\n): Promise<T> {\n try {\n const response = await client.session.axios.post<T>(path, body);\n return response.data;\n } catch (err) {\n const status = axiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, serverMessage(err) ?? `${operation} failed`, { cause: err });\n }\n throw new NetworkError(`${operation} request failed`, sanitizeAxiosError(err));\n }\n}\n\nfunction axiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { status?: number } }).response?.status;\n }\n return undefined;\n}\n\n/**\n * The server's own message, kept verbatim.\n *\n * §24.4 rule 1 turns on this: a `403` from `register/finish` names which\n * attestation rule refused the authenticator, and replacing it with a generic\n * string throws away the only actionable part of the response.\n */\nfunction serverMessage(err: unknown): string | undefined {\n if (!err || typeof err !== 'object' || !('response' in err)) return undefined;\n const data = (err as { response?: { data?: unknown } }).response?.data;\n if (typeof data === 'string' && data.length > 0) return data;\n if (data && typeof data === 'object' && 'message' in data) {\n const message = (data as { message?: unknown }).message;\n if (typeof message === 'string' && message.length > 0) return message;\n }\n return undefined;\n}\n","// Account lifecycle and MFA enrolment (CONTRACT.md §25).\n//\n// §1 locked the middle of an account's life — login, verifyMfa, refresh,\n// logout all assume an account that already exists, is verified, and already\n// has its second factor. These nine operations are how an account gets into\n// that state. None of them is new server surface; all nine have been live and\n// unreachable-from-an-SDK since before §1 was written, which meant every\n// application hand-rolled a POST against a path this SDK also knew.\n\nimport { mapHttpStatusToError, NetworkError, Sensitive, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type { LoginResult, LoginSuccessResponseWire } from './types.js';\n\nconst MFA_ENROLL = '/api/v1/auth/mfa/enroll';\nconst MFA_CONFIRM = '/api/v1/auth/mfa/confirm';\nconst MFA_SETUP_ENROLL = '/api/v1/auth/mfa/setup/enroll';\nconst MFA_SETUP_CONFIRM = '/api/v1/auth/mfa/setup/confirm';\nconst VERIFY_EMAIL = '/api/v1/auth/verify-email';\nconst RESEND_VERIFICATION = '/api/v1/auth/resend-verification';\nconst RESET_REQUEST = '/api/v1/auth/reset';\nconst RESET_CONFIRM = '/api/v1/auth/reset/confirm';\nconst RESET_CONTEXT = '/api/v1/auth/reset/context';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A TOTP enrolment offer. **The factor is not active yet** — it becomes active\n * when `AxiamClient.mfaConfirm` accepts a code derived from this secret (§25.2\n * rule 4).\n *\n * Both fields are `Sensitive`, and `totpUri` is the one that matters: it is\n * `otpauth://totp/...?secret=<secretBase32>`, so it *contains* the secret. An\n * SDK that wrapped the secret and left the URI bare would have wrapped nothing\n * — the URI is the field that actually reaches a log, because it is the field\n * a caller passes to a QR renderer (§25.3).\n */\nexport interface MfaEnrollment {\n /** The shared TOTP secret, base32. Anyone holding it can generate valid codes indefinitely. */\n secretBase32: Sensitive<string>;\n /** `otpauth://totp/…?secret=…` — what a QR renderer takes. It *contains* `secretBase32`. */\n totpUri: Sensitive<string>;\n}\n\n/**\n * The effective OPAQUE policy for the account a reset token belongs to (§25.4).\n *\n * Discloses no identity. Contract 1.26 removed the username from this response\n * when OPAQUE replaced SRP — an unauthenticated endpoint that confirms which\n * account a token belongs to is an oracle worth not having.\n */\nexport interface PasswordResetContext {\n /** The tenant's OPAQUE parameters, when it has OPAQUE enabled. Absent means plaintext is accepted. */\n opaque?: Record<string, unknown>;\n}\n\n/** The workspace a password-reset request names. Slugs are accepted, as on `login`. */\nexport interface PasswordResetRequest {\n /** The address to send the reset mail to. */\n email: string;\n /** Organization slug. Defaults to the client's own configuration. */\n orgSlug?: string;\n /** Tenant UUID. Defaults to the client's own configuration. */\n tenantId?: string;\n /** Tenant slug. Defaults to the client's own configuration. */\n tenantSlug?: string;\n}\n\n/** Everything `confirmPasswordReset` needs. */\nexport interface PasswordResetConfirmation {\n /** The single-use token from the reset mail. */\n token: Sensitive<string> | string;\n /** The new password. */\n newPassword: Sensitive<string> | string;\n /** The tenant the account belongs to. A UUID — this is a body field, not a query parameter. */\n tenantId: string;\n /**\n * The §23 registration record, for a tenant whose `AxiamClient.passwordResetContext`\n * says it requires one. Sending a plaintext `newPassword` to a tenant in\n * `opaque_mode: required` is refused, and refused late (§25.4 rule 1).\n */\n opaque?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes\n// ---------------------------------------------------------------------------\n\ninterface MfaEnrollWire {\n secret_base32: string;\n totp_uri: string;\n}\ninterface MfaConfirmWire {\n mfa_enabled: boolean;\n}\ninterface ResetContextWire {\n opaque?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Voluntary MFA enrolment, by a signed-in user (§25.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/mfa/enroll` (§25.1) — start voluntary TOTP enrolment.\n *\n * Requires a session and changes nothing about it. In particular this does\n * **not** clear the §17 decision memo: the subject has not changed, and\n * discarding a warm memo on an unrelated profile action costs a round trip on\n * every check that follows (§25.2 rule 3).\n */\nexport async function mfaEnroll(client: AxiamClient): Promise<MfaEnrollment> {\n client.ensureOpen();\n const wire = await post<MfaEnrollWire>(client, MFA_ENROLL, {}, 'mfaEnroll');\n return {\n secretBase32: new Sensitive(wire.secret_base32),\n totpUri: new Sensitive(wire.totp_uri),\n };\n}\n\n/**\n * `POST /api/v1/auth/mfa/confirm` (§25.1) — activate the factor\n * {@link mfaEnroll} offered, by proving a code derived from its secret.\n */\nexport async function mfaConfirm(client: AxiamClient, totpCode: string): Promise<boolean> {\n client.ensureOpen();\n const wire = await post<MfaConfirmWire>(\n client,\n MFA_CONFIRM,\n { totp_code: totpCode },\n 'mfaConfirm',\n );\n return wire.mfa_enabled;\n}\n\n// ---------------------------------------------------------------------------\n// Forced MFA enrolment, during login (§25.2)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/mfa/setup/enroll` (§25.1) — start the enrolment a\n * `login()` demanded.\n *\n * Reached when `login()` returns the `mfa_setup_required` outcome: the tenant\n * requires MFA and this account has none. There is no session yet — the setup\n * token *is* the credential.\n */\nexport async function mfaSetupEnroll(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n): Promise<MfaEnrollment> {\n client.ensureOpen();\n const wire = await post<MfaEnrollWire>(\n client,\n MFA_SETUP_ENROLL,\n { setup_token: expose(setupToken) },\n 'mfaSetupEnroll',\n );\n return {\n secretBase32: new Sensitive(wire.secret_base32),\n totpUri: new Sensitive(wire.totp_uri),\n };\n}\n\n/**\n * `POST /api/v1/auth/mfa/setup/confirm` (§25.1) — finish forced enrolment and,\n * with it, the login that was interrupted.\n *\n * Adopts credentials exactly as `login()` does, because it *is* the completion\n * of a login (§25.2 rule 2).\n */\nexport async function mfaSetupConfirm(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n totpCode: string,\n): Promise<LoginResult> {\n client.ensureOpen();\n // §17.1 rule 9: the subject changes here, unlike on `mfaEnroll`.\n client.decisionMemo.clear();\n\n const wire = await post<LoginSuccessResponseWire>(\n client,\n MFA_SETUP_CONFIRM,\n { setup_token: expose(setupToken), totp_code: totpCode },\n 'mfaSetupConfirm',\n );\n\n client.session.authenticated = true;\n await client.session.onAuthenticated?.();\n\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\n// ---------------------------------------------------------------------------\n// Email verification (§25.1)\n// ---------------------------------------------------------------------------\n\n/** `POST /api/v1/auth/verify-email` (§25.1). Unauthenticated — the user may have no session yet. */\nexport async function verifyEmail(\n client: AxiamClient,\n token: Sensitive<string> | string,\n tenantId: string,\n): Promise<void> {\n client.ensureOpen();\n await post<void>(\n client,\n VERIFY_EMAIL,\n { token: expose(token), tenant_id: tenantId },\n 'verifyEmail',\n );\n}\n\n/** `POST /api/v1/auth/resend-verification` (§25.1). */\nexport async function resendVerification(\n client: AxiamClient,\n email: string,\n tenantId: string,\n): Promise<void> {\n client.ensureOpen();\n await post<void>(\n client,\n RESEND_VERIFICATION,\n { email, tenant_id: tenantId },\n 'resendVerification',\n );\n}\n\n// ---------------------------------------------------------------------------\n// Password reset (§25.4)\n// ---------------------------------------------------------------------------\n\n/**\n * `POST /api/v1/auth/reset` (§25.1) — ask for a reset mail.\n *\n * **Resolves whether or not the address exists**, and this SDK exposes no way\n * to tell the two apart. That is not an omission to improve on: a client that\n * surfaced a \"no such user\" state — even one inferred from timing — would turn\n * the endpoint into the enumeration oracle its uniform response exists to\n * prevent (§25.4).\n */\nexport async function requestPasswordReset(\n client: AxiamClient,\n request: PasswordResetRequest,\n): Promise<void> {\n client.ensureOpen();\n const body: Record<string, string> = { email: request.email };\n const orgSlug = request.orgSlug ?? client.session.orgSlug;\n const tenantId = request.tenantId ?? client.session.tenantId;\n const tenantSlug = request.tenantSlug ?? client.session.tenantSlug;\n if (orgSlug) body.org_slug = orgSlug;\n if (tenantId) body.tenant_id = tenantId;\n if (tenantSlug) body.tenant_slug = tenantSlug;\n\n await post<void>(client, RESET_REQUEST, body, 'requestPasswordReset');\n}\n\n/**\n * `GET /api/v1/auth/reset/context` (§25.1) — the OPAQUE policy for the account\n * a reset token belongs to.\n *\n * Call this before {@link confirmPasswordReset} on any tenant that might have\n * §23 enabled: the client has to build a registration record, and building one\n * needs parameters it cannot know before it has a token to ask with.\n *\n * `404` means unknown, expired **or** already-consumed, deliberately without\n * distinguishing them; this SDK does not distinguish them either (§25.4 rule 3).\n */\nexport async function passwordResetContext(\n client: AxiamClient,\n token: Sensitive<string> | string,\n): Promise<PasswordResetContext> {\n client.ensureOpen();\n const url = `${RESET_CONTEXT}?token=${encodeURIComponent(expose(token))}`;\n try {\n const response = await client.session.axios.get<ResetContextWire>(url);\n return response.data?.opaque ? { opaque: response.data.opaque } : {};\n } catch (err) {\n throw toTaxonomyError(err, 'passwordResetContext');\n }\n}\n\n/** `POST /api/v1/auth/reset/confirm` (§25.1) — set the new password. */\nexport async function confirmPasswordReset(\n client: AxiamClient,\n confirmation: PasswordResetConfirmation,\n): Promise<void> {\n client.ensureOpen();\n const body: Record<string, unknown> = {\n token: expose(confirmation.token),\n new_password: expose(confirmation.newPassword),\n tenant_id: confirmation.tenantId,\n };\n if (confirmation.opaque) body.opaque = confirmation.opaque;\n\n await post<void>(client, RESET_CONFIRM, body, 'confirmPasswordReset');\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction expose(value: Sensitive<string> | string): string {\n return typeof value === 'string' ? value : value.expose();\n}\n\nasync function post<T>(\n client: AxiamClient,\n path: string,\n body: unknown,\n operation: string,\n): Promise<T> {\n try {\n const response = await client.session.axios.post<T>(path, body);\n return response.data;\n } catch (err) {\n throw toTaxonomyError(err, operation);\n }\n}\n\nfunction toTaxonomyError(err: unknown, operation: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: unknown } }).response;\n if (response?.status !== undefined) {\n return mapHttpStatusToError(response.status, serverMessage(response.data) ?? `${operation} failed`, {\n cause: err,\n });\n }\n }\n return new NetworkError(`${operation} request failed`, sanitizeAxiosError(err));\n}\n\nfunction serverMessage(data: unknown): string | undefined {\n if (typeof data === 'string' && data.length > 0) return data;\n if (data && typeof data === 'object' && 'message' in data) {\n const message = (data as { message?: unknown }).message;\n if (typeof message === 'string' && message.length > 0) return message;\n }\n return undefined;\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 { NetworkError } from '../core/index.js';\nimport { DecisionMemo } from '../core/decisionMemo.js';\nimport { TelemetryDispatcher } from '../core/telemetry.js';\nimport { TelemetryReporter } from '../core/telemetryReporter.js';\nimport type { RetryOptions } from './retry.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as opaqueMethods from './opaque.js';\nimport * as authzMethods from './authz.js';\nimport * as webauthnMethods from './webauthn.js';\nimport * as accountMethods from './accountLifecycle.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\nimport type { Sensitive } from '../core/index.js';\nimport type {\n WebauthnAuthenticationResponse,\n WebauthnCredential,\n WebauthnRegistrationResponse,\n WebauthnWorkspace,\n} from './webauthnTypes.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 /** §17 decision memo. Disabled unless `decisionMemoTtlMs` was configured. */\n readonly decisionMemo: DecisionMemo;\n\n /** §19 telemetry dispatcher. Empty unless a hook was installed. */\n readonly telemetry: TelemetryReporter;\n\n /** §16.1 disable switch. Defaults to enabled. */\n private readonly retryEnabled: boolean;\n\n /** §18 shutdown flag. Set once by close(); read on every operation. */\n private closed = false;\n\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n // §17.1 rule 1: off unless the caller asked for it.\n this.decisionMemo = new DecisionMemo(options.decisionMemoTtlMs ?? 0);\n this.telemetry = new TelemetryReporter(new TelemetryDispatcher(options.telemetryHook));\n // §19.2 rule 6: a clamped setting is reported, not swallowed. Emitted once,\n // here, because construction is the only moment an operator can act on it.\n this.decisionMemo.reportClamp(options.decisionMemoTtlMs ?? 0, this.telemetry.dispatcher);\n this.retryEnabled = options.retryEnabled ?? true;\n }\n\n /**\n * Release this client's local resources (CONTRACT.md §18).\n *\n * Idempotent — calling it twice is not an error. Cleanup runs from error\n * paths, and an error path that itself throws hides the original failure.\n *\n * **This does not log out.** §18.1 rule 5: shutting down a client releases\n * *local* resources and never reaches the network. The server-side session\n * deliberately outlives the client object, which is what lets a process\n * restart and resume; a `close()` that logged out would silently end every\n * user's session on each deploy. Call {@link logout} first if ending the\n * session is what you want.\n *\n * After this returns, any operation on the client rejects rather than\n * silently reconnecting.\n */\n close(): void {\n this.closed = true;\n this.decisionMemo.clear();\n }\n\n /**\n * Throws if {@link close} has been called (§18.1 rule 4).\n *\n * @internal\n */\n ensureOpen(): void {\n if (this.closed) {\n throw new NetworkError('client is closed: this AxiamClient was shut down with close()');\n }\n }\n\n /**\n * §16 options for `operation`, bound to this client's switch and telemetry.\n *\n * @internal\n */\n retryOptions(operation: string): RetryOptions {\n return {\n idempotent: true,\n operation,\n enabled: this.retryEnabled,\n telemetry: this.telemetry.dispatcher,\n };\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 /**\n * OPAQUE login (§23) — the password never leaves this process.\n *\n * Returns the same `LoginResult` as {@link login}, including the\n * `mfa_required` branch, so one result handler serves both. Rejects with a\n * `NetworkError` naming OPAQUE when the tenant has it disabled, so a caller\n * can fall back to {@link login} rather than mistaking it for a bad password.\n *\n * **Only that case may fall back.** Any other rejection is a failed login,\n * and retrying it over {@link login} would hand the plaintext to a server\n * that just failed to prove it holds the record.\n */\n loginOpaque(usernameOrEmail: string, password: string): Promise<LoginResult> {\n return opaqueMethods.loginOpaque(this, usernameOrEmail, password);\n }\n\n /**\n * Build an OPAQUE registration record to send with any request that sets a\n * password (§23). The server cannot build one — it never sees the plaintext.\n *\n * Asynchronous because it performs a `register/start` round trip: the\n * envelope is sealed under the server's oblivious PRF, so unlike the SRP\n * verifier this replaces there is no offline computation that produces a\n * valid record.\n */\n opaqueEnrollment(password: string): Promise<opaqueMethods.OpaqueEnrollment> {\n return opaqueMethods.opaqueEnrollment(this, password);\n }\n\n /**\n * Whether this installation can perform OPAQUE (§23.2).\n *\n * Asynchronous, and genuinely able to answer `false`: `@axiam/opaque-wasm` is\n * an optional peer dependency, so an installation that skipped it reports\n * rather than throwing at login time.\n */\n opaqueAvailable(): Promise<boolean> {\n return opaqueMethods.opaqueAvailable();\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 // -------------------------------------------------------------------------\n // §24 WebAuthn / passkeys — the relying-party layer\n //\n // These six work in Node as well as the browser: a service completing a\n // ceremony its native client ran is the relying party, exactly as a browser\n // is. The ceremony itself — the half that needs an authenticator — is\n // `axiam-sdk/browser` (§24.6).\n // -------------------------------------------------------------------------\n\n /** `POST /api/v1/auth/webauthn/register/start` (§24.1). Requires a session. */\n webauthnRegisterStart(): Promise<webauthnMethods.WebauthnRegistrationChallenge> {\n return webauthnMethods.webauthnRegisterStart(this);\n }\n\n /** `POST /api/v1/auth/webauthn/register/finish` (§24.1). Requires a session. */\n webauthnRegisterFinish(\n stateToken: Sensitive<string> | string,\n credentialName: string,\n response: WebauthnRegistrationResponse | string,\n ): Promise<WebauthnCredential> {\n return webauthnMethods.webauthnRegisterFinish(this, stateToken, credentialName, response);\n }\n\n /** `POST /api/v1/auth/webauthn/authenticate/start` (§24.1) — passkey as a second factor. */\n webauthnAuthenticateStart(\n challengeToken: Sensitive<string> | string,\n ): Promise<webauthnMethods.WebauthnAuthenticationChallenge> {\n return webauthnMethods.webauthnAuthenticateStart(this, challengeToken);\n }\n\n /** `POST /api/v1/auth/webauthn/authenticate/finish` (§24.1). Leaves the client authenticated (§24.3). */\n webauthnAuthenticateFinish(\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n ): Promise<webauthnMethods.WebauthnLoginResult> {\n return webauthnMethods.webauthnAuthenticateFinish(this, stateToken, response);\n }\n\n /** `POST .../authenticate/discoverable/start` (§24.1) — usernameless sign-in. */\n webauthnDiscoverableStart(\n workspace?: WebauthnWorkspace,\n ): Promise<webauthnMethods.WebauthnAuthenticationChallenge> {\n return webauthnMethods.webauthnDiscoverableStart(this, workspace);\n }\n\n /** `POST .../authenticate/discoverable/finish` (§24.1). Leaves the client authenticated (§24.3). */\n webauthnDiscoverableFinish(\n stateToken: Sensitive<string> | string,\n response: WebauthnAuthenticationResponse | string,\n ): Promise<webauthnMethods.WebauthnLoginResult> {\n return webauthnMethods.webauthnDiscoverableFinish(this, stateToken, response);\n }\n\n // -------------------------------------------------------------------------\n // §25 Account lifecycle and MFA enrolment\n // -------------------------------------------------------------------------\n\n /** `POST /api/v1/auth/mfa/enroll` (§25.1) — voluntary TOTP enrolment, by a signed-in user. */\n mfaEnroll(): Promise<accountMethods.MfaEnrollment> {\n return accountMethods.mfaEnroll(this);\n }\n\n /** `POST /api/v1/auth/mfa/confirm` (§25.1) — activate the factor `mfaEnroll` offered. */\n mfaConfirm(totpCode: string): Promise<boolean> {\n return accountMethods.mfaConfirm(this, totpCode);\n }\n\n /** `POST /api/v1/auth/mfa/setup/enroll` (§25.1) — start the enrolment a `login()` demanded. */\n mfaSetupEnroll(setupToken: Sensitive<string> | string): Promise<accountMethods.MfaEnrollment> {\n return accountMethods.mfaSetupEnroll(this, setupToken);\n }\n\n /** `POST /api/v1/auth/mfa/setup/confirm` (§25.1) — finish it, completing the interrupted login. */\n mfaSetupConfirm(setupToken: Sensitive<string> | string, totpCode: string): Promise<LoginResult> {\n return accountMethods.mfaSetupConfirm(this, setupToken, totpCode);\n }\n\n /** `POST /api/v1/auth/verify-email` (§25.1). */\n verifyEmail(token: Sensitive<string> | string, tenantId: string): Promise<void> {\n return accountMethods.verifyEmail(this, token, tenantId);\n }\n\n /** `POST /api/v1/auth/resend-verification` (§25.1). */\n resendVerification(email: string, tenantId: string): Promise<void> {\n return accountMethods.resendVerification(this, email, tenantId);\n }\n\n /** `POST /api/v1/auth/reset` (§25.1). Resolves whether or not the address exists (§25.4). */\n requestPasswordReset(request: accountMethods.PasswordResetRequest): Promise<void> {\n return accountMethods.requestPasswordReset(this, request);\n }\n\n /** `GET /api/v1/auth/reset/context` (§25.1) — the OPAQUE policy for a reset token's account. */\n passwordResetContext(\n token: Sensitive<string> | string,\n ): Promise<accountMethods.PasswordResetContext> {\n return accountMethods.passwordResetContext(this, token);\n }\n\n /** `POST /api/v1/auth/reset/confirm` (§25.1). */\n confirmPasswordReset(confirmation: accountMethods.PasswordResetConfirmation): Promise<void> {\n return accountMethods.confirmPasswordReset(this, confirmation);\n }\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n"]}