axiam-sdk 1.0.0-beta13 → 1.0.0-beta14

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.
Files changed (44) hide show
  1. package/README.md +55 -0
  2. package/dist/{authzCore-CrrzL1vM.d.cts → authzCore-BZahGkBf.d.cts} +13 -0
  3. package/dist/{authzCore-IhJd8o4F.d.ts → authzCore-Biyca_Rm.d.ts} +13 -0
  4. package/dist/browser/index.d.cts +1 -1
  5. package/dist/browser/index.d.ts +1 -1
  6. package/dist/{client-Bf4p7wD5.d.ts → client-BXXwSvBI.d.ts} +46 -1
  7. package/dist/{client-CPZ5WCob.d.cts → client-JWANinYZ.d.cts} +46 -1
  8. package/dist/{cookieJar-rwTCSTkI.d.cts → cookieJar-DXyJgm8n.d.cts} +1 -1
  9. package/dist/{cookieJar--3J1ZLYS.d.ts → cookieJar-DZSc_d8H.d.ts} +1 -1
  10. package/dist/grpc/index.d.cts +3 -3
  11. package/dist/grpc/index.d.ts +3 -3
  12. package/dist/grpc/index.js +10 -0
  13. package/dist/grpc/index.js.map +1 -1
  14. package/dist/grpc/index.mjs +10 -0
  15. package/dist/grpc/index.mjs.map +1 -1
  16. package/dist/index.d.cts +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +10 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +10 -0
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/middleware/index.d.cts +3 -2
  23. package/dist/middleware/index.d.ts +3 -2
  24. package/dist/middleware/index.js +150 -6
  25. package/dist/middleware/index.js.map +1 -1
  26. package/dist/middleware/index.mjs +148 -8
  27. package/dist/middleware/index.mjs.map +1 -1
  28. package/dist/nestjs/index.d.cts +2 -1
  29. package/dist/nestjs/index.d.ts +2 -1
  30. package/dist/node/index.d.cts +3 -2
  31. package/dist/node/index.d.ts +3 -2
  32. package/dist/node/index.js +152 -6
  33. package/dist/node/index.js.map +1 -1
  34. package/dist/node/index.mjs +149 -7
  35. package/dist/node/index.mjs.map +1 -1
  36. package/dist/rest/index.d.cts +2 -2
  37. package/dist/rest/index.d.ts +2 -2
  38. package/dist/rest/index.js +10 -0
  39. package/dist/rest/index.js.map +1 -1
  40. package/dist/rest/index.mjs +10 -0
  41. package/dist/rest/index.mjs.map +1 -1
  42. package/dist/revocationFeed-CDoD7Twr.d.cts +59 -0
  43. package/dist/revocationFeed-CDoD7Twr.d.ts +59 -0
  44. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/grpc/interceptor.ts","../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/core/decisionMemo.ts","../../src/core/telemetry.ts","../../src/core/telemetryReporter.ts","../../src/grpc/callWithRefresh.ts","../../src/grpc/client.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/management/manifest/plan.ts","../../src/management/manifest/engine.ts","../../src/management/page.ts","../../src/management/errors.ts","../../src/management/request.ts","../../src/management/scope.ts","../../src/management/ops/organizations.ts","../../src/management/ops/tenants.ts","../../src/management/models.ts","../../src/management/ops/users.ts","../../src/management/ops/groups.ts","../../src/management/ops/roles.ts","../../src/management/ops/permissions.ts","../../src/management/ops/resources.ts","../../src/management/ops/scopes.ts","../../src/management/ops/service_accounts.ts","../../src/management/ops/certificates.ts","../../src/management/ops/ca_certificates.ts","../../src/management/ops/pgp_keys.ts","../../src/management/ops/webhooks.ts","../../src/management/ops/oauth2_clients.ts","../../src/management/ops/federation.ts","../../src/management/ops/notification_rules.ts","../../src/management/ops/email_config.ts","../../src/management/ops/settings.ts","../../src/management/ops/scim_tokens.ts","../../src/management/ops/reactors.ts","../../src/management/ops/webauthn_policy.ts","../../src/management/ops/audit.ts","../../src/management/ops/privacy.ts","../../src/management/ops/platform.ts","../../src/management/ops/index.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../../src/node/tokenManager.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/node/session.ts"],"names":["grpc","grpc2","axios","response","wire","axiosStatus","post","expose","serverMessage","statusOf","CookieJar","HttpCookieAgent","HttpsCookieAgent","timingSafeEqual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,CAAC,SAAS,QAAA,KAAa;AAC5B,IAAA,OAAO,IAASA,gBAAA,CAAA,gBAAA,CAAiB,QAAA,CAAS,OAAO,CAAA,EAAG;AAAA,MAClD,KAAA,CAAM,QAAA,EAAU,QAAA,EAAU,IAAA,EAAM;AAE9B,QAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,YAAA,CAAa,iBAAA,EAAkB;AACrD,QAAA,IAAI,KAAA,EAAO;AACT,UAAA,QAAA,CAAS,IAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,KAAA,CAAM,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,QAC1D;AACA,QAAA,QAAA,CAAS,GAAA,CAAI,aAAA,EAAe,OAAA,CAAQ,iBAAiB,CAAA;AACrD,QAAA,IAAA,CAAK,UAAU,QAAQ,CAAA;AAAA,MACzB;AAAA,KACD,CAAA;AAAA,EACH,CAAA;AACF;;;ACbO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AA,CAAK,aAAa,qBAAA,EAAsB;AACpE,IAAA,IAAI,QAAA,EAAU;AACZ,MAAA,IAAA,CAAK,gBAAA,GAAmB,QAAA;AACxB,MAAA,IAAA,CAAK,YAAA,CAAa,YAAY,QAAQ,CAAA;AAAA,IACxC;AACA,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,IAAA,CAAK,aAAA,GAAgB,KAAA;AAAA,IACvB;AAAA,EACF;AAAA,EAEA,MAAM,gBAAA,GAAkC;AACtC,IAAA,IAAA,CAAK,YAAY,MAAM,kBAAA,CAAmB,KAAK,IAAA,EAAM,IAAA,CAAK,SAAS,WAAW,CAAA;AAAA,EAChF;AACF;AAGO,SAAS,kBAAkB,OAAA,EAA0C;AAC1E,EAAA,MAAM,IAAA,GAAO,cAAc,OAAO,CAAA;AAClC,EAAA,MAAM,MAAM,SAAA,EAAU;AAKtB,EAAA,SAAA,CAAU,IAAA,CAAK,KAAA,EAAO,GAAA,EAAK,qBAAA,CAAsB,OAAO,CAAC,CAAA;AAEzD,EAAA,MAAM,eAAe,IAAI,YAAA,CAAa,KAAK,OAAA,CAAQ,OAAA,EAAS,KAAK,iBAAiB,CAAA;AAClF,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,CAAQ,OAAO,CAAA;AAEnD,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,IAAA,EAAM,YAAA,EAAc,cAAc,GAAG,CAAA;AACvE;AAiBO,SAAS,iBAAiB,OAAA,EAA0C;AACzE,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,iBAAA,CAAkB,OAAO,CAAC,CAAA;AAC5D","file":"index.js","sourcesContent":["// Synchronous auth/tenant grpc-js interceptor (D-10, Pitfall 3).\n//\n// grpc-js's `start(metadata, listener, next)` callback is SYNCHRONOUS —\n// unlike tonic's async-native interceptor trait, it must call\n// `next(metadata, listener)` without ever awaiting. This interceptor\n// therefore only reads the TokenManager's non-blocking, in-memory cached\n// access token (populated by `syncFromJar()` after REST calls/refresh) —\n// it NEVER triggers a refresh itself. UNAUTHENTICATED handling belongs to\n// the async call-wrapper (callWithRefresh.ts), never here.\n//\n// Mirrors the Rust SDK's src/grpc/interceptor.rs exactly, adapted to grpc-js's\n// structurally different (non-tower) interceptor API\n// (RESEARCH.md Area 3 / grpc/proposal L5-node-client-interceptors.md).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { Interceptor } from '@grpc/grpc-js';\nimport type { NodeSession } from '../node/session.js';\n\n/**\n * Injects `authorization: Bearer <token>` (when a cached token is present)\n * and `x-tenant-id` metadata on every outgoing RPC (CONTRACT.md §5). Never\n * logs the token — `expose()` is only called at this metadata-insertion\n * boundary.\n */\nexport function authInterceptor(session: NodeSession): Interceptor {\n return (options, nextCall) => {\n return new grpc.InterceptingCall(nextCall(options), {\n start(metadata, listener, next) {\n // Non-blocking cached-token read — NEVER await here (Pitfall 3).\n const token = session.tokenManager.cachedAccessToken();\n if (token) {\n metadata.add('authorization', `Bearer ${token.expose()}`);\n }\n metadata.add('x-tenant-id', session.tenantHeaderValue);\n next(metadata, listener);\n },\n });\n };\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// 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","// UNAUTHENTICATED single-flight-retry wrapper (D-10/D-13, CONTRACT.md §9).\n//\n// The interceptor (interceptor.ts) is synchronous and never triggers a\n// refresh (Pitfall 3). This ASYNC call-site wrapper is where\n// UNAUTHENTICATED handling actually lives: on a caught error whose\n// `.code === GrpcStatus.UNAUTHENTICATED`, it awaits the session's\n// per-instance single-flight refresh guard (`session.refreshGuard` — the\n// SAME guard instance the REST transport for this session uses, D-13, but\n// NEVER shared with a different session, CR-02), resyncs the interceptor's\n// cached-token fast-path via `syncFromJar()`, then retries the call exactly\n// once. A second UNAUTHENTICATED (or any other error) maps through\n// `mapGrpcStatusToError` and rethrows — no further retry (§9.3).\n\nimport { GrpcStatus, mapGrpcStatusToError, type AxiamError } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\n\ninterface GrpcServiceErrorLike {\n code?: number;\n message?: string;\n}\n\nfunction isGrpcServiceError(err: unknown): err is GrpcServiceErrorLike {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n/**\n * Await `fn()`. On a gRPC UNAUTHENTICATED (16) error, drive the shared\n * single-flight refresh, sync the token cache from the jar, and retry `fn()`\n * exactly once. Any other error (or a second UNAUTHENTICATED) is mapped to\n * an AxiamError via `mapGrpcStatusToError` and rethrown.\n */\nexport async function callWithRefresh<T>(session: NodeSession, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (isGrpcServiceError(err) && err.code === GrpcStatus.UNAUTHENTICATED) {\n await session.refreshGuard(session.doRefresh);\n await session.tokenManager.syncFromJar();\n try {\n return await fn();\n } catch (retryErr) {\n throw toAxiamError(retryErr);\n }\n }\n throw toAxiamError(err);\n }\n}\n\nfunction toAxiamError(err: unknown): AxiamError | unknown {\n if (isGrpcServiceError(err) && typeof err.code === 'number') {\n return mapGrpcStatusToError(err.code, err.message ?? 'gRPC call failed');\n }\n return err;\n}\n","// gRPC AuthorizationService client — reused channel, checkAccess/batchCheck\n// (D-10/D-13, SC#2 Node half).\n//\n// The generated ts-proto stubs (`src/gen`, produced by `buf generate` at\n// build time — Phase 15 D-01/D-20) are NOT committed and are unavailable in\n// this sandbox (no `buf` CLI). Rather than importing from a path that does\n// not exist here, this module (a) defines local wire-shape interfaces that\n// exactly mirror `proto/axiam/v1/authorization.proto`, and (b) builds the\n// gRPC client dynamically via grpc-js's own `makeClientConstructor` (the\n// same primitive ts-proto's `outputServices=grpc-js` stubs are built on top\n// of) rather than importing a generated class. A buf-enabled build can swap\n// `buildAuthorizationServiceClient` below for the real ts-proto-generated\n// `AuthorizationServiceClient` from `../gen/...` with NO change to the\n// public `AuthzGrpcClient` surface, since both satisfy the same\n// `WireAuthorizationServiceClient` shape by construction (same .proto).\n// End-to-end wiring against real generated stubs is deferred to a\n// buf-enabled CI run (RESEARCH.md D-20; environment note in this plan).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { AccessDecision, ClientIdentity } from '../core/index.js';\nimport { AuthError, resolveClientIdentity } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\nimport { authInterceptor } from './interceptor.js';\nimport { callWithRefresh } from './callWithRefresh.js';\n\n// Re-exported (not re-declared) so `grpc/index.ts` can still export\n// `AccessDecision` from `./client.js` — see `core/authz.ts` for the single\n// shared definition (SDK-Q10, C2).\nexport type { AccessDecision };\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/authorization.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\nexport interface WireCheckAccessRequest {\n tenant_id: string;\n // `subject_id` is a plain (non-`optional`) proto3 string\n // (`proto/axiam/v1/authorization.proto`), unlike `scope` below. As of\n // contract 1.19 (SDK-Q10) an **empty** value means \"the subject carried by\n // the verified token\" — proto3 cannot express that as absence, so empty\n // carries the meaning. It stays required on this mirrored wire shape and on\n // the public `CheckAccessRequest` below; see that type for why.\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n}\n\nexport interface WireCheckAccessResponse {\n allowed: boolean;\n /**\n * @deprecated SDK-Q10 (contract 1.19) — superseded by {@link reason} (proto\n * field 4), which is what the REST decision body has always called this.\n * Both fields carry the byte-identical string until AXIAM **2.0**, where\n * proto field 2 is removed. Read `reason` instead; see `fromWireResponse`.\n */\n deny_reason: string;\n /** B1 deny-override decision reason (proto field 3). */\n reason_code?: string;\n /**\n * SDK-Q10 (contract 1.19) — the human-readable reason under the name REST\n * already uses. Proto field 4, explicit presence: absent on an allow,\n * present on every refusal. Absent on a *refusal* means a pre-SDK-Q10\n * server, which is exactly when {@link deny_reason} is still consulted.\n */\n reason?: string;\n}\n\nexport interface WireBatchCheckAccessRequest {\n requests: WireCheckAccessRequest[];\n}\n\nexport interface WireBatchCheckAccessResponse {\n results: WireCheckAccessResponse[];\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/userinfo.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\n/**\n * `axiam.v1.GetUserInfoRequest` — an empty message. Identity is derived\n * entirely server-side from the `authorization: Bearer <token>` metadata\n * (CONTRACT.md §1.1), so the request carries no fields.\n */\nexport type WireGetUserInfoRequest = Record<string, never>;\n\nexport interface WireGetUserInfoResponse {\n sub: string;\n tenant_id: string;\n org_id: string;\n // proto3 `optional` fields — absent on the wire unless the access token\n // carried the gating scope (\"email\" / \"profile\" respectively).\n email?: string;\n preferred_username?: string;\n}\n\ntype UnaryCallback<T> = (error: grpc.ServiceError | null, response?: T) => void;\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `AuthorizationServiceClient` this module needs. The real generated client\n * satisfies this shape exactly (unary Node-callback methods), so a\n * buf-enabled build's generated client is a drop-in replacement here.\n */\nexport interface WireAuthorizationServiceClient {\n checkAccess(\n request: WireCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n batchCheckAccess(\n request: WireBatchCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireBatchCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `UserInfoServiceClient` this module needs. As with\n * {@link WireAuthorizationServiceClient}, the real generated client satisfies\n * this shape exactly (single unary Node-callback method), so a buf-enabled\n * build's generated `UserInfoServiceClient` from `../gen/...` is a drop-in\n * replacement.\n */\nexport interface WireUserInfoServiceClient {\n getUserInfo(\n request: WireGetUserInfoRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireGetUserInfoResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * Public (camelCase, §1) single access-check request shape.\n *\n * `subjectId` is required here, unlike REST's optional `AccessCheck.subjectId`.\n * gRPC calls typically originate from a service-mesh caller with no\n * request-scoped JWT to derive a subject from, so passing it explicitly is the\n * normal case; REST, by contrast, derives the subject from the caller's JWT\n * when `subjectId` is omitted (§5).\n *\n * As of contract 1.19 (SDK-Q10) the *wire* field is optional in the same\n * sense — an empty `subject_id` means \"the subject in the verified token\" —\n * but this public type has not been relaxed to an optional `subjectId` to\n * match. That is a breaking signature move and is tracked separately from the\n * artifact re-vendor that brought the proto in.\n */\nexport interface CheckAccessRequest {\n tenantId: string;\n subjectId: string;\n action: string;\n resourceId: string;\n scope?: string;\n}\n\nfunction toWireRequest(req: CheckAccessRequest): WireCheckAccessRequest {\n return {\n tenant_id: req.tenantId,\n subject_id: req.subjectId,\n action: req.action,\n resource_id: req.resourceId,\n scope: req.scope,\n };\n}\n\nfunction fromWireResponse(resp: WireCheckAccessResponse): AccessDecision {\n // SDK-Q10 / CONTRACT.md §11.2 rule 9 (contract 1.19): read `reason`, fall\n // back to the deprecated `deny_reason` only when `reason` is absent on a\n // refusal — that is exactly a pre-SDK-Q10 server, and it is why proto field\n // 4 has explicit presence rather than being a plain `string`. One reason\n // accessor is exposed to callers, never two. `deny_reason` disappears at\n // AXIAM 2.0 and this fallback goes with it.\n const reason = resp.reason !== undefined ? resp.reason : resp.deny_reason;\n\n return {\n allowed: resp.allowed,\n reason: reason ? reason : undefined,\n // proto3 renders an unset `string` as `\"\"`, so an older server that never\n // set field 3 is indistinguishable from one that set it empty. Both mean\n // \"no reason code\", and both map to `undefined` rather than to `\"\"`,\n // which would be a value callers could accidentally branch on.\n reasonCode: resp.reason_code ? resp.reason_code : undefined,\n };\n}\n\n/**\n * The authenticated caller's OIDC-style identity claims, returned by\n * {@link UserInfoGrpcClient.getUserInfo} (CONTRACT.md §1.1). Public (camelCase,\n * §1) counterpart of the `axiam.v1.GetUserInfoResponse` wire message.\n *\n * `sub`, `tenantId`, and `orgId` are always present. `email` is populated only\n * when the access token carries the `email` scope, and `preferredUsername` only\n * with the `profile` scope — the server gates these exactly as the REST\n * `/oauth2/userinfo` endpoint does.\n */\nexport interface UserInfo {\n /** Subject (user) UUID. Always present. */\n sub: string;\n /** Tenant UUID. Always present. */\n tenantId: string;\n /** Organization UUID. Always present. */\n orgId: string;\n /** User email — present only with the `email` scope. */\n email?: string;\n /** Preferred username — present only with the `profile` scope. */\n preferredUsername?: string;\n}\n\nfunction fromWireUserInfo(resp: WireGetUserInfoResponse): UserInfo {\n return {\n sub: resp.sub,\n tenantId: resp.tenant_id,\n orgId: resp.org_id,\n // Preserve absence: a missing (scope-gated) claim stays `undefined` rather\n // than becoming an empty string.\n email: resp.email ? resp.email : undefined,\n preferredUsername: resp.preferred_username ? resp.preferred_username : undefined,\n };\n}\n\nfunction promisifyUnary<TReq, TResp>(\n call: (req: TReq, metadata: grpc.Metadata, callback: UnaryCallback<TResp>) => grpc.ClientUnaryCall,\n request: TReq,\n): Promise<TResp> {\n return new Promise((resolve, reject) => {\n call(request, new grpc.Metadata(), (error, response) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(response as TResp);\n });\n });\n}\n\n/**\n * Build the gRPC channel credentials for `baseUrl` (§6 — TLS is always\n * strict by default; `customCa` is the ONLY certificate escape hatch, never\n * an insecure/skip-verification surface).\n *\n * A plaintext target (`http://`/`grpc://`) is REFUSED by default (X-2): it\n * would silently drop the channel to `createInsecure()`, sending bearer tokens\n * and tenant metadata in cleartext. Callers who genuinely need a local dev\n * plaintext channel must opt in explicitly with `allowInsecure: true`, which\n * emits a `console.warn`. As a convenience the opt-in is required for ANY host\n * (including loopback) — there is no silent path to an insecure channel.\n *\n * When a §6.1 mTLS client identity is configured it is applied to the secure\n * channel via `createSsl(rootCerts, privateKey, certChain)` — the SAME strict\n * verification as the default `createSsl()`, just additionally presenting a\n * client certificate. The identity never affects the plaintext-refusal path.\n */\nfunction buildCredentials(\n baseUrl: string,\n customCa: string | undefined,\n allowInsecure: boolean,\n identity: ClientIdentity | undefined,\n): grpc.ChannelCredentials {\n const isSecure = baseUrl.startsWith('https://') || baseUrl.startsWith('grpcs://');\n if (!isSecure) {\n if (!allowInsecure) {\n throw new Error(\n `AXIAM gRPC refuses to open an insecure (plaintext) channel to \"${baseUrl}\": ` +\n 'bearer tokens and tenant metadata would be sent in cleartext. Use an ' +\n 'https:// or grpcs:// target, or pass { allowInsecure: true } to opt in ' +\n 'explicitly for a trusted local/dev channel (CONTRACT.md §6).',\n );\n }\n // Explicit opt-in only — never reached without allowInsecure.\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM gRPC: opening an INSECURE (plaintext) channel to \"${baseUrl}\" because ` +\n 'allowInsecure was set. Bearer tokens and tenant metadata are transmitted in ' +\n 'cleartext — never use this outside a trusted local/dev environment.',\n );\n return grpc.ChannelCredentials.createInsecure();\n }\n const rootCerts = customCa ? Buffer.from(customCa, 'utf8') : null;\n if (identity) {\n // mTLS (§6.1): present the client cert+key. `rootCerts ?? null` keeps the\n // platform trust store (null = default roots) when no customCa is given;\n // strict server verification is unchanged.\n return grpc.ChannelCredentials.createSsl(\n rootCerts,\n Buffer.from(identity.key.expose(), 'utf8'),\n Buffer.from(identity.cert, 'utf8'),\n );\n }\n if (customCa) {\n return grpc.ChannelCredentials.createSsl(rootCerts);\n }\n // Default: verify against the platform's native trust store.\n return grpc.ChannelCredentials.createSsl();\n}\n\nfunction grpcTarget(baseUrl: string): string {\n const url = new URL(baseUrl);\n return url.port ? `${url.hostname}:${url.port}` : url.hostname;\n}\n\nconst jsonCodec = <T>() => ({\n serialize: (value: T): Buffer => Buffer.from(JSON.stringify(value)),\n deserialize: (bytes: Buffer): T => JSON.parse(bytes.toString('utf8')) as T,\n});\n\n/**\n * Construct a real `AuthorizationServiceClient` over grpc-js's own\n * `makeClientConstructor` primitive (the same primitive ts-proto's\n * `outputServices=grpc-js` codegen target uses under the hood). This\n * transport-level client encodes/decodes with JSON as a build-independent\n * stand-in for the protobuf binary codec a buf-enabled build's generated\n * serializers would use — swap this factory for the generated\n * `AuthorizationServiceClient` once `src/gen` exists (D-20).\n */\nexport function buildAuthorizationServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireAuthorizationServiceClient {\n const checkAccessCodec = jsonCodec<WireCheckAccessRequest>();\n const checkAccessRespCodec = jsonCodec<WireCheckAccessResponse>();\n const batchCodec = jsonCodec<WireBatchCheckAccessRequest>();\n const batchRespCodec = jsonCodec<WireBatchCheckAccessResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n checkAccess: {\n path: '/axiam.v1.AuthorizationService/CheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: checkAccessCodec.serialize,\n requestDeserialize: checkAccessCodec.deserialize,\n responseSerialize: checkAccessRespCodec.serialize,\n responseDeserialize: checkAccessRespCodec.deserialize,\n },\n batchCheckAccess: {\n path: '/axiam.v1.AuthorizationService/BatchCheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: batchCodec.serialize,\n requestDeserialize: batchCodec.deserialize,\n responseSerialize: batchRespCodec.serialize,\n responseDeserialize: batchRespCodec.deserialize,\n },\n },\n 'axiam.v1.AuthorizationService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireAuthorizationServiceClient;\n}\n\nexport type AuthorizationServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireAuthorizationServiceClient;\n\n/**\n * Construct a real `UserInfoServiceClient` the same way\n * {@link buildAuthorizationServiceClient} builds the AuthorizationService\n * client — grpc-js's own `makeClientConstructor` primitive (the primitive\n * ts-proto's `outputServices=grpc-js` codegen sits on top of), with a JSON\n * codec as a build-independent stand-in for the protobuf binary serializers a\n * buf-enabled build would generate. Swap this factory for the generated\n * `UserInfoServiceClient` from `../gen/...` once `src/gen` exists (D-20); it\n * satisfies {@link WireUserInfoServiceClient} by construction (same .proto).\n *\n * grpc-js pools subchannels by target + credentials, so a UserInfoService\n * client built against the same `baseUrl`/credentials as the co-located\n * {@link AuthzGrpcClient} shares the underlying connection rather than opening a\n * redundant one (CONTRACT.md §1.1: reuse the existing channel machinery).\n */\nexport function buildUserInfoServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireUserInfoServiceClient {\n const reqCodec = jsonCodec<WireGetUserInfoRequest>();\n const respCodec = jsonCodec<WireGetUserInfoResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n getUserInfo: {\n path: '/axiam.v1.UserInfoService/GetUserInfo',\n requestStream: false,\n responseStream: false,\n requestSerialize: reqCodec.serialize,\n requestDeserialize: reqCodec.deserialize,\n responseSerialize: respCodec.serialize,\n responseDeserialize: respCodec.deserialize,\n },\n },\n 'axiam.v1.UserInfoService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireUserInfoServiceClient;\n}\n\nexport type UserInfoServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireUserInfoServiceClient;\n\n/**\n * gRPC transport for `AuthorizationService` (`checkAccess`/`batchCheck`,\n * SC#2 Node half), reusing one long-lived client/channel per instance (D-10\n * — never reconstructed per-call) and injecting auth + tenant metadata via\n * the synchronous interceptor on every RPC.\n */\nexport class AuthzGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireAuthorizationServiceClient;\n\n constructor(\n session: NodeSession,\n options: {\n baseUrl: string;\n customCa?: string;\n allowInsecure?: boolean;\n /** PEM client-certificate chain for mutual TLS (§6.1); pair with `clientKey`. */\n clientCert?: string;\n /** PEM private key for mutual TLS (§6.1); pair with `clientCert`. Secret (§7). */\n clientKey?: string;\n },\n clientFactory: AuthorizationServiceClientFactory = buildAuthorizationServiceClient,\n ) {\n this.#session = session;\n // Validate + resolve the §6.1 identity (throws on one-of/bad-PEM, §6.1) and\n // apply it to the gRPC channel — the SAME identity the REST transport uses.\n const identity = resolveClientIdentity(options);\n const credentials = buildCredentials(\n options.baseUrl,\n options.customCa,\n options.allowInsecure ?? false,\n identity,\n );\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */\n async checkAccess(request: CheckAccessRequest): Promise<AccessDecision> {\n const wireRequest = toWireRequest(request);\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.checkAccess.bind(this.#inner), wireRequest),\n );\n return fromWireResponse(response);\n }\n\n /** `BatchCheckAccess` over gRPC — results preserve input order (§1). */\n async batchCheck(requests: CheckAccessRequest[]): Promise<AccessDecision[]> {\n const wireRequest: WireBatchCheckAccessRequest = { requests: requests.map(toWireRequest) };\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.batchCheckAccess.bind(this.#inner), wireRequest),\n );\n return response.results.map(fromWireResponse);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n\n/**\n * gRPC transport for `axiam.v1.UserInfoService` (`getUserInfo`, CONTRACT.md\n * §1.1) — the low-latency counterpart of the server's REST\n * `GET /oauth2/userinfo` endpoint.\n *\n * Reuses the SAME channel/interceptor/refresh machinery as {@link\n * AuthzGrpcClient}: one long-lived client/channel per instance (D-10 — never\n * reconstructed per-call), the shared auth + `x-tenant-id` interceptor\n * (`authInterceptor(session)`), and this session's single-flight refresh guard\n * via `callWithRefresh`. Built from the same {@link NodeSession}, it shares the\n * pooled subchannel with a co-located `AuthzGrpcClient` (no second connection).\n */\nexport class UserInfoGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireUserInfoServiceClient;\n\n constructor(\n session: NodeSession,\n options: {\n baseUrl: string;\n customCa?: string;\n allowInsecure?: boolean;\n /** PEM client-certificate chain for mutual TLS (§6.1); pair with `clientKey`. */\n clientCert?: string;\n /** PEM private key for mutual TLS (§6.1); pair with `clientCert`. Secret (§7). */\n clientKey?: string;\n },\n clientFactory: UserInfoServiceClientFactory = buildUserInfoServiceClient,\n ) {\n this.#session = session;\n // Validate + resolve the §6.1 identity (throws on one-of/bad-PEM) and apply\n // it to the gRPC channel — the SAME identity the REST/authz transports use.\n const identity = resolveClientIdentity(options);\n const credentials = buildCredentials(\n options.baseUrl,\n options.customCa,\n options.allowInsecure ?? false,\n identity,\n );\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /**\n * `GetUserInfo` over gRPC (CONTRACT.md §1.1). Returns the authenticated\n * caller's identity claims; the request is empty (identity comes from the\n * bearer token in the interceptor-injected metadata).\n *\n * Pre-flight (§1.1.3): with no cached access token this raises `AuthError`\n * client-side, WITHOUT a wire call — the same synchronous cached-token view\n * the auth interceptor reads. A gRPC `UNAUTHENTICATED` response otherwise\n * drives exactly one shared-guard refresh + one retry (§9.3), identical to\n * {@link AuthzGrpcClient.checkAccess}.\n */\n async getUserInfo(): Promise<UserInfo> {\n if (this.#session.tokenManager.cachedAccessToken() === null) {\n throw new AuthError('getUserInfo requires a prior successful login() (no access token present)');\n }\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.getUserInfo.bind(this.#inner), {} as WireGetUserInfoRequest),\n );\n return fromWireUserInfo(response);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n","// SharedSession — the object other transports (Node persona 17-03, middleware\n// 17-05) attach gRPC/JWKS/middleware state to (D-13).\n//\n// Holds: the axios instance, the tenant header value (computed once at\n// construction), a mutable csrfToken store, the base URL, and a per-instance\n// single-flight refresh guard (CR-02: NOT the module-level default guard —\n// each SharedSession gets its own via createRefreshGuard(), so two\n// independent AxiamClient/NodeSession instances never cross-wire refreshes).\n// One login() drives all transports for a given session.\n\nimport axios, { type AxiosInstance } from 'axios';\nimport type { AxiamClientOptions, 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 * True when this session was constructed with a §6.1 mTLS client identity\n * (`clientCert` + `clientKey`), and therefore presents a client certificate\n * on every request it makes.\n *\n * Read by the §12 OIDC helpers to decide whether CONTRACT.md §21.3 rule 2\n * applies: an `mtls_endpoint_aliases` entry is preferred only on a call that\n * is actually going over mutual TLS, and a session without an identity must\n * keep using the top-level endpoints.\n */\n readonly presentsClientCertificate: boolean;\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 /**\n * The tenant the signed-in principal's record *lives* in — CONTRACT.md\n * §5.2.2 — as reported by the login response.\n *\n * Distinct from `resolvedTenantId`, which is the tenant being acted on: the\n * two diverge for an organization-level principal that has selected another\n * one. Read by `opaqueEnrollmentForSelf`, which must seal a §23 record\n * against the account's own tenant rather than whichever one this client is\n * currently pointed at. `undefined` until a login completes.\n */\n resolvedPrincipalTenantId: 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 // Both halves, because §6.1 is all-or-nothing: `resolveClientIdentity`\n // rejects one without the other before this line is reached.\n this.presentsClientCertificate =\n options.clientCert !== undefined && options.clientKey !== undefined;\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 AxiamUserInfo,\n LoginResult,\n LoginSuccessResponseWire,\n LoginUserInfoWire,\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\n/**\n * Map the wire user object onto {@link AxiamUserInfo}.\n *\n * Shared by the three response paths that complete a login — password,\n * OPAQUE, and the account-lifecycle flows — which previously each carried\n * their own copy of this mapping and a comment saying \"same reading as\n * `auth.ts`\". Contract 1.34 turned that duplication into a hazard: five more\n * fields, and a copy that forwards three of them is a bug nothing catches.\n */\nexport function userInfoFromWire(user: LoginUserInfoWire): AxiamUserInfo {\n return {\n id: user.id,\n username: user.username,\n email: user.email,\n // §5.2: derived server-side and response-only. `?? false` is what makes a\n // pre-1.31 server's silence mean \"no cross-tenant action\", rather than\n // `undefined` leaking into a truthiness check somewhere downstream.\n organizationLevel: user.organization_level ?? false,\n tenantId: user.tenant_id,\n // §5.2.2 rule 1: absent means equal. A server older than contract 1.34\n // omits this and cannot switch the acting tenant either, so falling back\n // to `tenant_id` is not a guess — it is the only value it could have had.\n principalTenantId: user.principal_tenant_id ?? user.tenant_id,\n principalTenantSlug: user.principal_tenant_slug ?? undefined,\n orgId: user.org_id ?? undefined,\n // §5.2.3: absent means unrestricted, and `null` from the server means the\n // same thing — neither should surface as an empty list, which would read\n // as \"reaches nothing\".\n reachableTenantIds: user.reachable_tenant_ids ?? undefined,\n };\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire, client?: AxiamClient): LoginResult {\n const user = userInfoFromWire(wire.user);\n // §5.2.2: remember where this principal lives, so a later\n // `opaqueEnrollmentForSelf` seals against the account's own tenant without\n // a second round trip.\n if (client && user.principalTenantId) {\n client.session.resolvedPrincipalTenantId = user.principalTenantId;\n }\n return {\n status: 'authenticated',\n user,\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, client);\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, client);\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 { userInfoFromWire } from './auth.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: userInfoFromWire(wire.user),\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\n/**\n * Build a registration record for `password`, sealed against the tenant this\n * client is **acting on**.\n *\n * That is the right tenant when the record is for an account being created in\n * it — §27 `users.create`, and the reset-completion flow, which names its own\n * tenant. It is the **wrong** tenant for the caller's own password change\n * once an organization-level principal has selected another one to act on:\n * the account's credentials live where the account does. Use\n * {@link opaqueEnrollmentForSelf} there — CONTRACT.md §5.2.2 rule 2.\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 return enroll(client, password, undefined);\n}\n\n/**\n * Build a registration record for the **caller's own** new password, sealed\n * against the tenant the caller's account lives in.\n *\n * CONTRACT.md §5.2.2 rule 2. `POST /auth/password/change` and the record that\n * accompanies it are about the account, not about whatever tenant the client\n * is currently pointed at, and a record sealed against the acting tenant is\n * refused with *\"the OPAQUE session was issued for a different tenant\"*.\n *\n * The distinction only bites for an organization-level principal that has\n * selected another tenant to act on; for everyone else the two tenants are the\n * same value and this behaves identically to {@link opaqueEnrollment}. It is\n * still the function to call for a self-service password change, because which\n * principal is signed in is not something the call site usually knows.\n *\n * @throws NetworkError when no login has completed on this client yet — the\n * principal tenant is reported by the login response, so there is nothing to\n * seal against before then.\n */\nexport async function opaqueEnrollmentForSelf(\n client: AxiamClient,\n password: string,\n): Promise<OpaqueEnrollment> {\n const principalTenantId = client.session.resolvedPrincipalTenantId;\n if (!principalTenantId) {\n throw new NetworkError(\n 'OPAQUE: no principal tenant is known yet — sign in before building a '\n + 'registration record for your own password',\n );\n }\n return enroll(client, password, principalTenantId);\n}\n\n/**\n * The shared body of the two enrolment functions; they differ only in the\n * tenant the record is sealed against.\n */\nasync function enroll(\n client: AxiamClient,\n password: string,\n principalTenantId: string | undefined,\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 if (principalTenantId !== undefined) {\n // Name the principal tenant by id and drop the slug: a slug that named the\n // acting tenant would otherwise out-vote the id server-side, which is the\n // exact confusion this path exists to avoid.\n body.tenant_id = principalTenantId;\n delete body.tenant_slug;\n }\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 { userInfoFromWire } from './auth.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 RESEND_OWN_VERIFICATION = '/api/v1/users/me/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: userInfoFromWire(wire.user),\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/**\n * `POST /api/v1/auth/resend-verification` (§25.1) — the **unauthenticated**\n * resend, for a caller with no session.\n *\n * **Resolves whatever the outcome.** The address may not exist, may already be\n * verified, or may be over the daily limit, and this answers identically in all\n * of them, because it takes an address from an anonymous caller and anything\n * else is an oracle for which addresses have accounts (§25.7).\n *\n * A caller that *is* signed in wants {@link resendOwnVerification}, which says\n * which of those happened. Do not reach for this one because it is the name you\n * already knew.\n */\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 * `POST /api/v1/users/me/resend-verification` (§25.1, §25.7) — resend the\n * **signed-in caller's own** verification mail, and say what happened.\n *\n * Takes no address. The server reads it off the caller's own record, and this\n * signature deliberately offers no way to name a different one: a parameter\n * here would let an authenticated session mail an arbitrary address.\n *\n * Unlike {@link resendVerification} this reports the outcome, because the\n * caller is signed in to the account it is asking about and none of the\n * outcomes tells it anything it did not already know:\n *\n * - resolves — a token was minted and the mail **enqueued**. Delivery is\n * asynchronous and can still fail at the provider; a queue that accepts\n * everything in front of one that rejects it looks exactly like this working.\n * - `ConflictError` (from `409`) — already verified, or the account is in a\n * state that must not be sent a live token.\n * - `NetworkError` (from `429`) — the daily resend limit.\n *\n * §25.7 rule 2 forbids falling back to the unauthenticated endpoint on either\n * of those, and this SDK does not: the fallback would turn both failures back\n * into a resolved promise and restore the bug this operation exists to fix,\n * with an extra round-trip.\n */\nexport async function resendOwnVerification(client: AxiamClient): Promise<void> {\n client.ensureOpen();\n await post<void>(client, RESEND_OWN_VERIFICATION, {}, 'resendOwnVerification');\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","/**\n * The plan a manifest reconciles to — CONTRACT.md §27.6.\n */\n\nimport { NetworkError } from '../../core/errors.js';\nimport type { ManagementManifest } from './spec.js';\n\n/** What reconciling one spec would do. */\nexport type Change = 'create' | 'update' | 'no-change';\n\n/** Which part of the manifest an action came from. */\nexport type Target =\n | 'resource'\n | 'scope'\n | 'permission'\n | 'role'\n | 'role-grant'\n | 'group'\n | 'group-role'\n | 'user'\n | 'user-role'\n | 'group-member';\n\n/** One step of a plan. */\nexport interface PlannedAction {\n /** Whether this step creates, updates, or does nothing. */\n change: Change;\n /** What kind of thing it acts on. */\n target: Target;\n /** The manifest key it came from, for a human reading the plan. */\n key: string;\n /** A one-line description, stable across runs so plans can be diffed. */\n summary: string;\n}\n\n/**\n * The ordered set of actions that would reconcile a manifest.\n *\n * Ordering is derived, not incidental: resources (parents before children),\n * then scopes, permissions, roles, role grants, groups, group bindings, users,\n * and finally the user bindings that need all of the above to exist. Two plans\n * over unchanged state are equal, in the same order (§27.6 rule 8) — a plan\n * that reorders between runs cannot be diffed, and diffing it is most of the\n * reason it exists.\n */\nexport interface ManagementPlan {\n /** Every step, including the no-ops. */\n actions: PlannedAction[];\n}\n\n/** The steps of `plan` that would actually change something. */\nexport function changes(plan: ManagementPlan): PlannedAction[] {\n return plan.actions.filter((a) => a.change !== 'no-change');\n}\n\n/**\n * Whether applying `plan` would change nothing.\n *\n * This is the §27.6 rule 6 acceptance test: `apply` then `plan` must land\n * here, or the SDK has a drift-detection bug.\n */\nexport function isConverged(plan: ManagementPlan): boolean {\n return changes(plan).length === 0;\n}\n\n/**\n * What actually happened to one planned step.\n *\n * Named `StepOutcome` rather than `Outcome` because `core/telemetry` already\n * exports an `Outcome` — the success/failure of a single request — and two\n * exported types of that name in one package is one too many.\n */\nexport type StepOutcome =\n | {\n /** The step ran and the thing now exists. */\n status: 'created';\n }\n | {\n /** The step ran and the thing was updated. */\n status: 'updated';\n }\n | {\n /** A no-op step; nothing was sent. */\n status: 'unchanged';\n }\n | {\n /** The step failed. Everything before it has already happened. */\n status: 'failed';\n /** The error the server or transport gave. */\n message: string;\n }\n | {\n /** Never attempted, because an earlier step failed. */\n status: 'not-attempted';\n };\n\n/** One planned step paired with what became of it. */\nexport interface AppliedStep {\n /** The step, exactly as `plan` reported it. */\n action: PlannedAction;\n /** What actually happened when it ran — or did not. */\n outcome: StepOutcome;\n}\n\n/** The step that stopped an apply, and why. */\nexport interface ManifestFailure {\n /** The step that failed. Everything before it has already happened. */\n action: PlannedAction;\n /** The error the server or transport gave. */\n message: string;\n}\n\n/**\n * The result of applying a manifest.\n *\n * **There is no transaction here and this type does not pretend there is**\n * (§27.6 rule 7). These are independent HTTP endpoints; nothing spans them. If\n * step 12 of 30 fails, steps 1–11 have happened and will not be undone — so\n * every step's outcome is reported, execution stops at the first failure\n * rather than continuing blindly, and there is no `rollback` because this SDK\n * could not honour one. Fix the cause and re-apply: rule 6's idempotence is\n * what makes that safe.\n */\nexport interface ApplyReport {\n /** Each planned step paired with what became of it, in plan order. */\n steps: AppliedStep[];\n}\n\n/** The failing step, if the apply stopped early. */\nexport function failure(report: ApplyReport): ManifestFailure | undefined {\n const found = report.steps.find((s) => s.outcome.status === 'failed');\n return found ? { action: found.action, message: (found.outcome as { message: string }).message } : undefined;\n}\n\n/** Whether every step that was meant to run did. */\nexport function isComplete(report: ApplyReport): boolean {\n return failure(report) === undefined;\n}\n\n/** How many steps actually changed something. */\nexport function changedCount(report: ApplyReport): number {\n return report.steps.filter(\n (s) => s.outcome.status === 'created' || s.outcome.status === 'updated',\n ).length;\n}\n\n/**\n * Reject a manifest that cannot be reconciled, before any request is made.\n *\n * §27.6 rules 2 and 5 both land here. Every failure this catches would\n * otherwise surface halfway through an apply, with part of the tenant already\n * changed — which is the expensive moment to learn that a role refers to a\n * permission nobody declared.\n *\n * @internal\n */\nexport function validate(manifest: ManagementManifest): void {\n const problems: string[] = [];\n const resources = manifest.resources ?? [];\n const permissions = manifest.permissions ?? [];\n const roles = manifest.roles ?? [];\n const groups = manifest.groups ?? [];\n const users = manifest.users ?? [];\n\n const resourceKeys = new Set(resources.map((r) => r.key));\n const scopeKeys = new Set(resources.flatMap((r) => (r.scopes ?? []).map((s) => s.key)));\n const permissionKeys = new Set(permissions.map((p) => p.key));\n const roleKeys = new Set(roles.map((r) => r.key));\n const groupKeys = new Set(groups.map((g) => g.key));\n\n duplicates('resource', resources.map((r) => r.key), problems);\n duplicates('scope', resources.flatMap((r) => (r.scopes ?? []).map((s) => s.key)), problems);\n duplicates('permission', permissions.map((p) => p.key), problems);\n duplicates('role', roles.map((r) => r.key), problems);\n duplicates('group', groups.map((g) => g.key), problems);\n duplicates('user', users.map((u) => u.key), problems);\n\n for (const resource of resources) {\n if (resource.parent && !resourceKeys.has(resource.parent)) {\n problems.push(\n `resource ${q(resource.key)} names parent ${q(resource.parent)}, which no resource declares`,\n );\n }\n }\n for (const role of roles) {\n for (const grant of role.grants ?? []) {\n if (!permissionKeys.has(grant.permission)) {\n problems.push(\n `role ${q(role.key)} grants permission ${q(grant.permission)}, which no permission declares`,\n );\n }\n for (const scope of grant.scopes ?? []) {\n if (!scopeKeys.has(scope)) {\n problems.push(`role ${q(role.key)} scopes a grant to ${q(scope)}, which no scope declares`);\n }\n }\n }\n }\n for (const group of groups) {\n for (const role of group.roles ?? []) {\n if (!roleKeys.has(role)) {\n problems.push(`group ${q(group.key)} is assigned role ${q(role)}, which no role declares`);\n }\n }\n }\n for (const user of users) {\n for (const role of user.roles ?? []) {\n if (!roleKeys.has(role)) {\n problems.push(`user ${q(user.key)} is assigned role ${q(role)}, which no role declares`);\n }\n }\n for (const group of user.groups ?? []) {\n if (!groupKeys.has(group)) {\n problems.push(`user ${q(user.key)} is in group ${q(group)}, which no group declares`);\n }\n }\n }\n\n try {\n topologicalOrder(manifest);\n } catch (err) {\n problems.push((err as Error).message);\n }\n\n if (problems.length) {\n throw new NetworkError(\n `manifest is not reconcilable (${problems.length} problem(s)): ${problems.join('; ')}`,\n );\n }\n}\n\nconst q = (s: string) => JSON.stringify(s);\n\nfunction duplicates(kind: string, keys: string[], problems: string[]): void {\n const seen = new Set<string>();\n for (const key of keys) {\n if (seen.has(key)) problems.push(`${kind} key ${q(key)} is declared more than once`);\n seen.add(key);\n }\n}\n\n/**\n * Resource keys ordered so a parent always precedes its children.\n *\n * Throws on a cycle rather than looping: a resource graph with a cycle has no\n * valid creation order, and discovering that by hanging is worse than\n * discovering it by message.\n *\n * @internal\n */\nexport function topologicalOrder(manifest: ManagementManifest): string[] {\n const resources = manifest.resources ?? [];\n const parents = new Map(resources.map((r) => [r.key, r.parent]));\n const order: string[] = [];\n const placed = new Set<string>();\n\n // Iterate the manifest's own order so the result is stable run to run\n // (§27.6 rule 8), rather than a map traversal order that is not.\n for (const resource of resources) {\n const chain: string[] = [];\n const guard = new Set<string>();\n let cursor: string | undefined = resource.key;\n while (cursor !== undefined && !placed.has(cursor)) {\n if (guard.has(cursor)) {\n throw new NetworkError(\n `resource parent graph has a cycle through ${q(cursor)}; there is no order in which ` +\n `these can be created`,\n );\n }\n guard.add(cursor);\n chain.push(cursor);\n cursor = parents.get(cursor);\n }\n for (const key of chain.reverse()) {\n if (!placed.has(key)) {\n placed.add(key);\n order.push(key);\n }\n }\n }\n return order;\n}\n","/**\n * Reconciling a manifest against a live tenant — CONTRACT.md §27.6.\n */\n\nimport { NetworkError } from '../../core/errors.js';\nimport type { AxiamClient } from '../../rest/client.js';\nimport type * as models from '../models.js';\nimport type {\n ApplyReport,\n ManagementPlan,\n StepOutcome,\n PlannedAction,\n Target,\n} from './plan.js';\nimport { topologicalOrder, validate } from './plan.js';\nimport type { ManagementManifest, ResourceSpec } from './spec.js';\n\n/** How many items a planning read asks for per page. */\nconst PLAN_PAGE = 200;\n\n/** Manifest keys resolved to server ids, built during planning. */\ninterface Resolved {\n resources: Map<string, string>;\n scopes: Map<string, string>;\n permissions: Map<string, string>;\n roles: Map<string, string>;\n groups: Map<string, string>;\n users: Map<string, string>;\n}\n\nconst emptyResolved = (): Resolved => ({\n resources: new Map(),\n scopes: new Map(),\n permissions: new Map(),\n roles: new Map(),\n groups: new Map(),\n users: new Map(),\n});\n\n/** One executable step, carrying manifest keys rather than ids. */\ntype Step =\n | { kind: 'noop' }\n | { kind: 'create-resource'; key: string; name: string; resourceType: string; parent?: string }\n | { kind: 'update-resource'; key: string; resourceType: string }\n | { kind: 'create-scope'; resource: string; key: string; name: string; description: string }\n | { kind: 'create-permission'; key: string; action: string; description: string }\n | { kind: 'update-permission'; key: string; description: string }\n | { kind: 'create-role'; key: string; name: string; description: string; isGlobal: boolean }\n | { kind: 'update-role'; key: string; description: string; isGlobal: boolean }\n | {\n kind: 'grant-permission';\n role: string;\n permission: string;\n effect?: models.PermissionEffect;\n scopes: string[];\n }\n | { kind: 'create-group'; key: string; name: string; description: string }\n | { kind: 'update-group'; key: string; description: string }\n | { kind: 'assign-role-to-group'; role: string; group: string }\n | {\n kind: 'create-user';\n key: string;\n username: string;\n email: string;\n password: models.CreateUserRequest['password'];\n }\n | { kind: 'update-user'; key: string; email: string }\n | { kind: 'assign-role-to-user'; role: string; user: string }\n | { kind: 'add-group-member'; group: string; user: string };\n\n/** The current state a plan is computed against. */\ninterface Snapshot {\n resources: models.Resource[];\n scopes: Map<string, models.Scope[]>;\n permissions: models.Permission[];\n roles: models.Role[];\n groups: models.Group[];\n users: models.UserResponse[];\n roleGrants: Map<string, string[]>;\n roleUsers: Map<string, string[]>;\n roleGroups: Map<string, string[]>;\n groupMembers: Map<string, string[]>;\n}\n\n/** The declarative-management handle, reached as `client.manifest`. */\nexport class ManifestApi {\n readonly #client: AxiamClient;\n\n /** @internal — reached through `client.manifest`, never constructed directly. */\n constructor(client: AxiamClient) {\n this.#client = client;\n }\n\n /** What reconciling `manifest` would do. **Issues no writes.** */\n async plan(manifest: ManagementManifest): Promise<ManagementPlan> {\n validate(manifest);\n const snapshot = await this.#read(manifest);\n return { actions: this.#compute(manifest, snapshot).map((s) => s.action) };\n }\n\n /**\n * Reconcile `manifest`, stopping at the first failure.\n *\n * Re-running after fixing the cause is the recovery path, and is safe:\n * applying twice converges (§27.6 rule 6).\n */\n async apply(manifest: ManagementManifest): Promise<ApplyReport> {\n validate(manifest);\n const snapshot = await this.#read(manifest);\n const steps = this.#compute(manifest, snapshot);\n const resolved = this.#resolvedFrom(manifest, snapshot);\n return this.#execute(steps, resolved);\n }\n\n // -------------------------------------------------------------------\n // Read\n // -------------------------------------------------------------------\n\n async #read(manifest: ManagementManifest): Promise<Snapshot> {\n const c = this.#client;\n const start = { limit: PLAN_PAGE };\n const resources = await c.resources.listAll(start);\n const permissions = await c.permissions.listAll(start);\n const roles = await c.roles.listAll(start);\n const groups = await c.groups.listAll(start);\n const users = await c.users.listAll(start);\n\n // Only the resources, roles and groups the manifest could match: a tenant\n // with a thousand resources should not cost a thousand scope reads to plan\n // five.\n const scopes = new Map<string, models.Scope[]>();\n for (const resource of resources) {\n if ((manifest.resources ?? []).some((s) => s.name === resource.name)) {\n scopes.set(resource.id, await c.scopes.list(resource.id));\n }\n }\n const roleGrants = new Map<string, string[]>();\n const roleUsers = new Map<string, string[]>();\n const roleGroups = new Map<string, string[]>();\n for (const role of roles) {\n if (!(manifest.roles ?? []).some((s) => s.name === role.name)) continue;\n roleGrants.set(role.id, (await c.roles.listPermissions(role.id)).map((g) => g.permission.id));\n roleUsers.set(role.id, (await c.roles.listUsers(role.id)).map((a) => a.user.id));\n roleGroups.set(role.id, (await c.roles.listGroups(role.id)).map((a) => a.group.id));\n }\n const groupMembers = new Map<string, string[]>();\n for (const group of groups) {\n if (!(manifest.groups ?? []).some((s) => s.name === group.name)) continue;\n groupMembers.set(group.id, (await c.groups.listMembersAll(group.id, start)).map((u) => u.id));\n }\n\n return {\n resources,\n scopes,\n permissions,\n roles,\n groups,\n users,\n roleGrants,\n roleUsers,\n roleGroups,\n groupMembers,\n };\n }\n\n // -------------------------------------------------------------------\n // Plan\n // -------------------------------------------------------------------\n\n #resolvedFrom(manifest: ManagementManifest, snapshot: Snapshot): Resolved {\n const resolved = emptyResolved();\n this.#compute(manifest, snapshot, resolved);\n return resolved;\n }\n\n #compute(\n manifest: ManagementManifest,\n snapshot: Snapshot,\n into: Resolved = emptyResolved(),\n ): Array<{ action: PlannedAction; step: Step }> {\n const resolved = into;\n const out: Array<{ action: PlannedAction; step: Step }> = [];\n const push = (change: PlannedAction['change'], target: Target, key: string, summary: string, step: Step) =>\n out.push({ action: { change, target, key, summary }, step });\n\n const specs = new Map((manifest.resources ?? []).map((r) => [r.key, r] as const));\n // `topologicalOrder` already rejected a cycle during validation.\n for (const key of topologicalOrder(manifest)) {\n const spec = specs.get(key) as ResourceSpec;\n const parentPending = spec.parent !== undefined && !resolved.resources.has(spec.parent);\n const parentId = spec.parent ? resolved.resources.get(spec.parent) : undefined;\n // A child whose parent is itself pending cannot already exist, so\n // matching it against a root of the same name would be wrong.\n const existing = parentPending\n ? undefined\n : snapshot.resources.find(\n (r) => r.name === spec.name && (r.parent_id ?? undefined) === parentId,\n );\n const summary = `resource ${JSON.stringify(spec.name)} (${spec.resourceType})`;\n if (existing) {\n resolved.resources.set(spec.key, existing.id);\n const drifted = existing.resource_type !== spec.resourceType;\n push(\n drifted ? 'update' : 'no-change',\n 'resource',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-resource', key: spec.key, resourceType: spec.resourceType }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'resource', spec.key, summary, {\n kind: 'create-resource',\n key: spec.key,\n name: spec.name,\n resourceType: spec.resourceType,\n parent: spec.parent,\n });\n }\n }\n\n for (const key of topologicalOrder(manifest)) {\n const spec = specs.get(key) as ResourceSpec;\n const resourceId = resolved.resources.get(spec.key);\n const existingScopes = (resourceId && snapshot.scopes.get(resourceId)) || [];\n for (const scope of spec.scopes ?? []) {\n const found = existingScopes.find((s) => s.name === scope.name);\n const summary = `scope ${JSON.stringify(scope.name)} on ${JSON.stringify(spec.name)}`;\n if (found) {\n resolved.scopes.set(scope.key, found.id);\n push('no-change', 'scope', scope.key, summary, { kind: 'noop' });\n } else {\n push('create', 'scope', scope.key, summary, {\n kind: 'create-scope',\n resource: spec.key,\n key: scope.key,\n name: scope.name,\n description: scope.description,\n });\n }\n }\n }\n\n for (const spec of manifest.permissions ?? []) {\n const found = snapshot.permissions.find((p) => p.action === spec.action);\n const summary = `permission ${JSON.stringify(spec.action)}`;\n if (found) {\n resolved.permissions.set(spec.key, found.id);\n const drifted = found.description !== spec.description;\n push(\n drifted ? 'update' : 'no-change',\n 'permission',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-permission', key: spec.key, description: spec.description }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'permission', spec.key, summary, {\n kind: 'create-permission',\n key: spec.key,\n action: spec.action,\n description: spec.description,\n });\n }\n }\n\n for (const spec of manifest.roles ?? []) {\n const found = snapshot.roles.find((r) => r.name === spec.name);\n const summary = `role ${JSON.stringify(spec.name)}`;\n const isGlobal = spec.isGlobal ?? false;\n if (found) {\n resolved.roles.set(spec.key, found.id);\n const drifted = found.description !== spec.description || found.is_global !== isGlobal;\n push(\n drifted ? 'update' : 'no-change',\n 'role',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-role', key: spec.key, description: spec.description, isGlobal }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'role', spec.key, summary, {\n kind: 'create-role',\n key: spec.key,\n name: spec.name,\n description: spec.description,\n isGlobal,\n });\n }\n }\n\n // Role grants. Present-or-absent only: a grant this manifest does not\n // mention is left alone (§27.6 rule 3), which is why there is no revoke.\n for (const spec of manifest.roles ?? []) {\n const roleId = resolved.roles.get(spec.key);\n const held = roleId ? snapshot.roleGrants.get(roleId) : undefined;\n for (const grant of spec.grants ?? []) {\n const permissionId = resolved.permissions.get(grant.permission);\n const present = !!held && !!permissionId && held.includes(permissionId);\n push(\n present ? 'no-change' : 'create',\n 'role-grant',\n spec.key,\n `role ${JSON.stringify(spec.name)} grants ${JSON.stringify(grant.permission)}`,\n present\n ? { kind: 'noop' }\n : {\n kind: 'grant-permission',\n role: spec.key,\n permission: grant.permission,\n effect: grant.effect,\n scopes: grant.scopes ?? [],\n },\n );\n }\n }\n\n for (const spec of manifest.groups ?? []) {\n const found = snapshot.groups.find((g) => g.name === spec.name);\n const summary = `group ${JSON.stringify(spec.name)}`;\n if (found) {\n resolved.groups.set(spec.key, found.id);\n const drifted = found.description !== spec.description;\n push(\n drifted ? 'update' : 'no-change',\n 'group',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-group', key: spec.key, description: spec.description }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'group', spec.key, summary, {\n kind: 'create-group',\n key: spec.key,\n name: spec.name,\n description: spec.description,\n });\n }\n }\n\n for (const spec of manifest.groups ?? []) {\n const groupId = resolved.groups.get(spec.key);\n for (const roleKey of spec.roles ?? []) {\n const roleId = resolved.roles.get(roleKey);\n const present =\n !!roleId && !!groupId && (snapshot.roleGroups.get(roleId) ?? []).includes(groupId);\n push(\n present ? 'no-change' : 'create',\n 'group-role',\n spec.key,\n `group ${JSON.stringify(spec.name)} holds role ${JSON.stringify(roleKey)}`,\n present ? { kind: 'noop' } : { kind: 'assign-role-to-group', role: roleKey, group: spec.key },\n );\n }\n }\n\n for (const spec of manifest.users ?? []) {\n const found = snapshot.users.find((u) => u.username === spec.username);\n const summary = `user ${JSON.stringify(spec.username)}`;\n if (found) {\n resolved.users.set(spec.key, found.id);\n const drifted = found.email !== spec.email;\n push(\n drifted ? 'update' : 'no-change',\n 'user',\n spec.key,\n summary,\n drifted ? { kind: 'update-user', key: spec.key, email: spec.email } : { kind: 'noop' },\n );\n } else {\n // §27.6 rule 1: catch this here, before anything has been written,\n // rather than halfway through an apply.\n if (!spec.initialPassword) {\n throw new NetworkError(\n `user ${JSON.stringify(spec.username)} does not exist and would be created, but the ` +\n `spec carries no initialPassword`,\n );\n }\n push('create', 'user', spec.key, summary, {\n kind: 'create-user',\n key: spec.key,\n username: spec.username,\n email: spec.email,\n password: spec.initialPassword,\n });\n }\n }\n\n for (const spec of manifest.users ?? []) {\n const userId = resolved.users.get(spec.key);\n for (const roleKey of spec.roles ?? []) {\n const roleId = resolved.roles.get(roleKey);\n const present =\n !!roleId && !!userId && (snapshot.roleUsers.get(roleId) ?? []).includes(userId);\n push(\n present ? 'no-change' : 'create',\n 'user-role',\n spec.key,\n `user ${JSON.stringify(spec.username)} holds role ${JSON.stringify(roleKey)}`,\n present ? { kind: 'noop' } : { kind: 'assign-role-to-user', role: roleKey, user: spec.key },\n );\n }\n for (const groupKey of spec.groups ?? []) {\n const groupId = resolved.groups.get(groupKey);\n const present =\n !!groupId && !!userId && (snapshot.groupMembers.get(groupId) ?? []).includes(userId);\n push(\n present ? 'no-change' : 'create',\n 'group-member',\n spec.key,\n `user ${JSON.stringify(spec.username)} is in group ${JSON.stringify(groupKey)}`,\n present ? { kind: 'noop' } : { kind: 'add-group-member', group: groupKey, user: spec.key },\n );\n }\n }\n\n return out;\n }\n\n // -------------------------------------------------------------------\n // Apply\n // -------------------------------------------------------------------\n\n async #execute(\n steps: Array<{ action: PlannedAction; step: Step }>,\n resolved: Resolved,\n ): Promise<ApplyReport> {\n const out: ApplyReport['steps'] = [];\n let stopped = false;\n for (const { action, step } of steps) {\n if (stopped) {\n out.push({ action, outcome: { status: 'not-attempted' } });\n continue;\n }\n if (step.kind === 'noop') {\n out.push({ action, outcome: { status: 'unchanged' } });\n continue;\n }\n try {\n await this.#run(step, resolved);\n const outcome: StepOutcome =\n action.change === 'create' ? { status: 'created' } : { status: 'updated' };\n out.push({ action, outcome });\n } catch (err) {\n stopped = true;\n out.push({\n action,\n outcome: { status: 'failed', message: err instanceof Error ? err.message : String(err) },\n });\n }\n }\n return { steps: out };\n }\n\n async #run(step: Step, resolved: Resolved): Promise<void> {\n const c = this.#client;\n switch (step.kind) {\n case 'noop':\n return;\n case 'create-resource': {\n const created = await c.resources.create({\n name: step.name,\n resource_type: step.resourceType,\n parent_id: step.parent ? lookup(resolved.resources, step.parent, 'resource') : undefined,\n });\n resolved.resources.set(step.key, created.id);\n return;\n }\n case 'update-resource':\n await c.resources.update(lookup(resolved.resources, step.key, 'resource'), {\n resource_type: step.resourceType,\n });\n return;\n case 'create-scope': {\n const created = await c.scopes.create(\n lookup(resolved.resources, step.resource, 'resource'),\n { name: step.name, description: step.description },\n );\n resolved.scopes.set(step.key, created.id);\n return;\n }\n case 'create-permission': {\n const created = await c.permissions.create({\n action: step.action,\n description: step.description,\n });\n resolved.permissions.set(step.key, created.id);\n return;\n }\n case 'update-permission':\n await c.permissions.update(lookup(resolved.permissions, step.key, 'permission'), {\n description: step.description,\n });\n return;\n case 'create-role': {\n const created = await c.roles.create({\n name: step.name,\n description: step.description,\n is_global: step.isGlobal,\n });\n resolved.roles.set(step.key, created.id);\n return;\n }\n case 'update-role':\n await c.roles.update(lookup(resolved.roles, step.key, 'role'), {\n description: step.description,\n is_global: step.isGlobal,\n });\n return;\n case 'grant-permission':\n await c.roles.grantPermission(lookup(resolved.roles, step.role, 'role'), {\n permission_id: lookup(resolved.permissions, step.permission, 'permission'),\n effect: step.effect,\n scope_ids: step.scopes.length\n ? step.scopes.map((s) => lookup(resolved.scopes, s, 'scope'))\n : undefined,\n });\n return;\n case 'create-group': {\n const created = await c.groups.create({ name: step.name, description: step.description });\n resolved.groups.set(step.key, created.id);\n return;\n }\n case 'update-group':\n await c.groups.update(lookup(resolved.groups, step.key, 'group'), {\n description: step.description,\n });\n return;\n case 'assign-role-to-group':\n await c.roles.assignToGroup(lookup(resolved.roles, step.role, 'role'), {\n group_id: lookup(resolved.groups, step.group, 'group'),\n });\n return;\n case 'create-user': {\n const created = await c.users.create({\n username: step.username,\n email: step.email,\n password: step.password,\n });\n resolved.users.set(step.key, created.id);\n return;\n }\n case 'update-user':\n await c.users.update(lookup(resolved.users, step.key, 'user'), { email: step.email });\n return;\n case 'assign-role-to-user':\n await c.roles.assignToUser(lookup(resolved.roles, step.role, 'role'), {\n user_id: lookup(resolved.users, step.user, 'user'),\n });\n return;\n case 'add-group-member':\n await c.groups.addMember(lookup(resolved.groups, step.group, 'group'), {\n user_id: lookup(resolved.users, step.user, 'user'),\n });\n return;\n }\n }\n}\n\n/**\n * Resolve a manifest key to the id an earlier step recorded.\n *\n * A miss here is an SDK bug, not a user error — validation already rejected\n * dangling references and the plan orders producers before consumers — so it\n * says so rather than blaming the manifest.\n */\nfunction lookup(map: Map<string, string>, key: string, kind: string): string {\n const id = map.get(key);\n if (id === undefined) {\n throw new NetworkError(\n `internal: ${kind} key ${JSON.stringify(key)} was consumed before the step that creates it ran`,\n );\n }\n return id;\n}\n","/**\n * Pagination for the §27 management surface.\n *\n * Twenty of the 147 operations take `offset`/`limit` and answer with the\n * envelope `{ items, total, offset, limit }`. The other thirteen collection\n * reads answer with a bare array and are **not** paginated — §27.4 rule 4\n * forbids modelling those as a page, because a `Page` reporting\n * `total === items.length` is indistinguishable from a real one right up to\n * the moment a caller relies on `total`.\n */\n\n/**\n * Where a paginated read starts, and how much of it to take.\n *\n * `limit` is deliberately optional with no SDK-side default: §27.4 rule 4\n * forbids silently truncating, and a client-side default does exactly that\n * while leaving the caller no way to tell a short page from a complete one.\n */\nexport interface PageRequest {\n /** How many items to skip. Defaults to `0`. */\n offset?: number;\n /** How many items to take. Omitted lets the server decide. */\n limit?: number;\n /**\n * Free-text filter applied by the **server**, before `offset`/`limit`.\n *\n * Matched case-insensitively against the identifying fields of whatever is\n * being listed — a name or username, plus the record id, so a UUID out of a\n * log line pastes in as-is. `total` on the resulting {@link Page} counts\n * *matches*, not rows, which is what lets a pager built on it show a page\n * count belonging to the result set it is paging.\n *\n * It lives here rather than as a third argument on each of the twenty\n * generated `list` methods (§27.4 rule 4), and that is what makes the\n * auto-paging `listAll` form carry it across every request of the walk — a\n * walk that filtered its first request and not the rest would return the\n * matches followed by the unfiltered tail.\n *\n * Omitted sends no `search` parameter. An empty or whitespace-only term is\n * treated as omitted: a box that fires on every keystroke sends `?search=`\n * the moment it is cleared, and \"rows containing the empty string\" is a\n * different question.\n *\n * The server caps the term's length. This SDK deliberately does not\n * re-implement that cap — a client-side truncation the server would not have\n * made is a silently different query.\n */\n search?: string;\n}\n\n/** One page of a paginated management read. */\nexport interface Page<T> {\n /** The items on this page. */\n items: T[];\n /** How many items exist in the whole set, across every page. */\n total: number;\n /** The offset this page starts at. */\n offset: number;\n /** The page size the server applied. */\n limit: number;\n}\n\n/**\n * The query parameters a {@link PageRequest} contributes.\n *\n * `limit` is omitted entirely when unset rather than sent as `0` — the server\n * reads `limit=0` as \"none\", which would return an empty page.\n *\n * @internal\n */\nexport function pageQuery(page: PageRequest): Record<string, string | undefined> {\n return {\n offset: String(page.offset ?? 0),\n limit: page.limit === undefined ? undefined : String(page.limit),\n search: normalizeSearch(page.search),\n };\n}\n\n/**\n * The trimmed term, or `undefined` when there is nothing to filter on.\n *\n * Mirrors the server's own normalisation minus the length cap, which is the\n * server's to apply — see {@link PageRequest.search}.\n *\n * @internal\n */\nexport function normalizeSearch(term: string | undefined): string | undefined {\n const trimmed = term?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/** Whether another page follows `page`. */\nexport function hasMore<T>(page: Page<T>): boolean {\n return page.items.length > 0 && page.offset + page.items.length < page.total;\n}\n\n/**\n * Walk a paginated read to exhaustion, concatenating every page.\n *\n * The `list_all` shape §27.4 rule 4 requires. The walk stops on an empty page\n * even when `total` disagrees, so a misreporting server costs one wasted\n * request rather than an unbounded loop.\n *\n * @internal — each generated `list` exposes this as its own `…All` method.\n */\nexport async function collectPages<T>(\n start: PageRequest,\n fetch: (page: PageRequest) => Promise<Page<T>>,\n): Promise<T[]> {\n let request: PageRequest = {\n offset: start.offset ?? 0,\n limit: start.limit,\n search: start.search,\n };\n const out: T[] = [];\n for (;;) {\n const page = await fetch(request);\n out.push(...page.items);\n const next = page.offset + page.items.length;\n if (page.items.length === 0 || next >= page.total) return out;\n // `search` is carried, not dropped (§27.4 rule 4). A walk that filtered\n // only its first request would concatenate the matches with the\n // unfiltered remainder, which reads as a server bug from the caller's side.\n request = { offset: next, limit: request.limit, search: request.search };\n }\n}\n","/**\n * The §27.4 rule 7 error sub-types.\n *\n * §2 fixes the taxonomy at three error types and §27 does not widen it. What\n * it adds is a *classification* inside two of them, because a management\n * surface produces refusals §2 never had to describe — §2 has no 404 row at\n * all, since nothing before §27 could return one.\n *\n * TypeScript has real subclassing, so these are subclasses: every\n * `catch (e) { if (e instanceof AuthzError) … }` written before §27 keeps\n * working, and a caller who needs the distinction narrows further.\n */\n\nimport { AuthzError, NetworkError } from '../core/errors.js';\n\n/** One field-level complaint inside a {@link ValidationError}. */\nexport interface FieldError {\n /** The offending field's name, as the server names it. */\n field: string;\n /** What is wrong with it. */\n message: string;\n}\n\n/**\n * HTTP 404 — the resource does not exist, **or** belongs to another tenant.\n *\n * The server answers identically in both cases on purpose: a distinguishable\n * \"exists but not yours\" lets a caller enumerate another tenant's ids. That is\n * why this is an {@link AuthzError} rather than a category of its own — in a\n * multi-tenant IAM the two really are one outcome.\n */\nexport class NotFoundError extends AuthzError {\n /** The registry operation that found nothing, e.g. `\"users.get\"`. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'NotFoundError';\n this.operation = operation;\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * HTTP 409 — a uniqueness or state conflict, such as a role name already taken.\n *\n * Never retried (§27.4 rule 8): a 409 is the server telling the truth, not a\n * transient fault, and a retry produces the identical answer one round-trip\n * later.\n */\nexport class ConflictError extends AuthzError {\n /** The registry operation that conflicted. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'ConflictError';\n this.operation = operation;\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * HTTP 400/422 — the request was rejected.\n *\n * §2 maps 400 to `NetworkError`, described as an \"SDK programming error\". That\n * description was written when nothing but the SDK itself could produce a 400.\n * On this surface a 400 is usually a *user's* invalid input — an email that is\n * not an email, a slug already taken — and an application needs to tell that\n * from a broken socket without matching on message text. The parent type is\n * inherited from §2 rather than chosen here.\n */\nexport class ValidationError extends NetworkError {\n /** The HTTP status the server answered with — 400 or 422. */\n readonly status: number;\n /** The registry operation that was rejected. */\n readonly operation: string;\n /** Per-field detail, where the server sent any. Empty is normal. */\n readonly fields: FieldError[];\n\n constructor(operation: string, status: number, message: string, fields: FieldError[]) {\n super(message);\n this.name = 'ValidationError';\n this.status = status;\n this.operation = operation;\n this.fields = fields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Pull field-level detail out of an error body, on a best-effort basis.\n *\n * Two shapes are recognised — an array of `{field, message}` and an object\n * keyed by field name. A body in neither shape yields no fields rather than an\n * error: failing to parse an error body would replace a useful message with a\n * useless one.\n *\n * @internal\n */\nexport function parseFieldErrors(body: unknown): FieldError[] {\n if (!body || typeof body !== 'object') return [];\n const errors = (body as { errors?: unknown }).errors;\n if (Array.isArray(errors)) {\n return errors.filter(\n (e): e is FieldError =>\n !!e && typeof e === 'object' && typeof (e as FieldError).field === 'string',\n );\n }\n if (errors && typeof errors === 'object') {\n return Object.entries(errors as Record<string, unknown>)\n .filter(([, v]) => typeof v === 'string')\n .map(([field, message]) => ({ field, message: message as string }));\n }\n return [];\n}\n","/**\n * The one request path every §27 management operation goes through.\n *\n * §27.8 is explicit that the generated layer MUST sit on the SDK's existing\n * request path and MUST NOT build its own. That is what this module is: 147\n * generated operations all funnel into {@link sendManagement}, so they inherit\n * §3 (CSRF), §4 (the cookie jar), §5 (`X-Tenant-ID`), §6 (TLS), §9 (the\n * reactive single-flight refresh the response interceptor already performs),\n * §16 (retry) and §19 (telemetry) by construction rather than by 147\n * opportunities to forget one.\n */\n\nimport type { AxiosResponse } from 'axios';\n\nimport { AuthError, mapHttpStatusToError } from '../core/index.js';\nimport { withRetry } from '../rest/retry.js';\nimport type { AxiamClient } from '../rest/client.js';\nimport { ConflictError, NotFoundError, ValidationError, parseFieldErrors } from './errors.js';\n\n/** The HTTP verbs this surface uses. */\nexport type ManagementMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** One management call, fully resolved. */\nexport interface ManagementCall {\n /** `\"users.create\"` — the registry's namespace-qualified operation name. */\n operation: string;\n /** The HTTP verb. Only `GET` is retry-eligible (§27.4 rule 8). */\n method: ManagementMethod;\n /** `\"/api/v1/users/{user_id}\"`, ids **not** substituted — the §19.1 label. */\n pathTemplate: string;\n /** The same path with ids substituted, ready to send. */\n path: string;\n /** Query parameters; `undefined` values are dropped rather than sent empty. */\n query?: Record<string, string | undefined>;\n /** The request body, already converted to its wire shape. */\n body?: unknown;\n}\n\n/**\n * Issue a management request and return its parsed body.\n *\n * @internal — reached through the generated namespace handles.\n */\nexport async function sendManagement<T>(client: AxiamClient, call: ManagementCall): Promise<T> {\n // §18.1 rule 4: use-after-close is an error, never a silent reconnect.\n client.ensureOpen();\n\n // §27.4 rule 1: no session, no wire call. Letting the request go out trades\n // a clear local error for a 401 that then enters the §9 refresh guard and\n // fails there, two indirections from the actual mistake.\n if (!client.session.authenticated) {\n throw new AuthError(\n `${call.operation}: no active session — call login() before using the management API`,\n );\n }\n\n const params = Object.fromEntries(\n Object.entries(call.query ?? {}).filter(([, v]) => v !== undefined),\n );\n\n const attempt = async (n: number): Promise<T> => {\n const done = client.telemetry.startRequest(call.operation, call.method, call.pathTemplate, n);\n try {\n const response: AxiosResponse<T> = await client.session.axios.request<T>({\n method: call.method,\n url: call.path,\n params,\n data: call.body,\n });\n done(response.status, 'success');\n return response.data;\n } catch (err) {\n done(statusOf(err), 'failure');\n throw mapManagementError(call.operation, err);\n }\n };\n\n // §16.2 and §27.4 rule 8: only reads are retried, and only through the\n // shared runner so the backoff, jitter and `Retry-After` floor are the\n // contract's rather than this module's. No write here is retriable, not even\n // the ones that look idempotent — generating a certificate twice mints two,\n // and rotating a secret twice invalidates the one the caller already stored.\n return withRetry(attempt, {\n ...client.retryOptions(call.operation),\n idempotent: call.method === 'GET',\n });\n}\n\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 bodyOf(err: unknown): unknown {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { data?: unknown } }).response?.data;\n }\n return undefined;\n}\n\n/**\n * Map a failed management response onto the §2 taxonomy.\n *\n * Delegates to the shared `mapHttpStatusToError` for everything §27 does not\n * classify, so the two mappers cannot drift: this function's whole job is the\n * three statuses §27.4 rule 7 names, and 404 is the one §2 genuinely lacks.\n */\nfunction mapManagementError(operation: string, err: unknown): unknown {\n const status = statusOf(err);\n if (status === undefined) {\n // No response at all — a transport failure. The shared mapper owns it.\n return mapHttpStatusToError(0, `${operation}: request failed`, { cause: err });\n }\n const body = bodyOf(err);\n const detail = describe(body);\n\n if (status === 404) {\n return new NotFoundError(\n operation,\n `${operation}: not found (or not visible to this tenant)${detail}`,\n );\n }\n if (status === 409) {\n return new ConflictError(operation, `${operation}: conflict${detail}`);\n }\n if (status === 400 || status === 422) {\n return new ValidationError(\n operation,\n status,\n `${operation}: request rejected${detail}`,\n parseFieldErrors(body),\n );\n }\n return mapHttpStatusToError(status, `${operation}${detail}`, { cause: err });\n}\n\nfunction describe(body: unknown): string {\n if (typeof body === 'string' && body) return `: ${body}`;\n if (body && typeof body === 'object') {\n const message = (body as { message?: unknown; error?: unknown }).message\n ?? (body as { error?: unknown }).error;\n if (typeof message === 'string') return `: ${message}`;\n }\n return '';\n}\n","/**\n * Where `{org_id}` and `{tenant_id}` come from — CONTRACT §27.4 rule 3.\n *\n * Thirty-one of the 147 routes carry one or both, and in almost every call they\n * are the client's own. Making the caller restate them every time is ceremony\n * that gets wrapped in a helper anyway; making them impossible to override is\n * worse, because a platform-admin token legitimately administers a tenant\n * other than the one its client was built with. So they default from the\n * client, and every handle that needs one exposes an override.\n */\n\nimport { NetworkError } from '../core/errors.js';\nimport type { AxiamClient } from '../rest/client.js';\n\n/**\n * Per-handle overrides for the two implicit path parameters.\n *\n * Named `NamespaceScope` rather than `Scope` because the server's schema set\n * already has a `Scope` — the sub-resource kind §27.1's `scopes` namespace\n * administers — and two exported types of that name is one too many.\n */\nexport interface NamespaceScope {\n /** Override for `{org_id}`. Absent means \"the client's\". */\n orgId?: string;\n /** Override for `{tenant_id}`. Absent means \"the client's\". */\n tenantId?: string;\n}\n\n/**\n * Resolve `{org_id}`: the handle's override, else the client's.\n *\n * A client built with `orgSlug` and no `orgId` fails **here**, with no wire\n * call. §27.4 rule 3 forbids resolving the slug behind the caller's back: a\n * silent extra round-trip on an admin path is what §12.1 rule 2 refuses for\n * `/oauth2/*`, and for the same reason — the caller cannot see it, cannot\n * cache it, and pays for it on every call.\n *\n * @internal\n */\nexport function resolveOrg(client: AxiamClient, scope: NamespaceScope, operation: string): string {\n if (scope.orgId) return scope.orgId;\n const configured = client.session.orgId;\n if (configured) return configured;\n const slug = client.session.orgSlug;\n throw new NetworkError(\n slug\n ? `${operation}: this route needs an organization UUID, but the client was built with ` +\n `orgSlug ${JSON.stringify(slug)}. Rebuild it with orgId, or name one on the handle ` +\n `with .inOrg(...).`\n : `${operation}: this route needs an organization UUID and the client has none. Build ` +\n `the client with orgId, or name one on the handle with .inOrg(...).`,\n );\n}\n\n/**\n * Resolve `{tenant_id}` where it names the *context*, not the object.\n *\n * Namespaces where `{tenant_id}` names the thing being acted on — `tenants`,\n * and the signing CAs under `ca_certificates` — take it as an ordinary\n * argument instead and never reach this.\n *\n * @internal\n */\nexport function resolveTenant(client: AxiamClient, scope: NamespaceScope, operation: string): string {\n if (scope.tenantId) return scope.tenantId;\n const configured = client.session.tenantId ?? client.session.resolvedTenantId;\n if (configured) return configured;\n throw new NetworkError(\n `${operation}: this route needs a tenant UUID, but the client was built with ` +\n `tenantSlug ${JSON.stringify(client.session.tenantSlug)}. Rebuild it with tenantId, or ` +\n `name one on the handle with .forTenant(...).`,\n );\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `organizations` management namespace (CONTRACT §27.1).\n *\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `organizations` namespace handle.\n *\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class OrganizationsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): OrganizationsApi {\n return new OrganizationsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations` */\n async list(page: PageRequest = {}): Promise<Page<models.Organization>> {\n const wire = await sendManagement<Page<models.Organization>>(this.#client, {\n operation: 'organizations.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations',\n path: '/api/v1/organizations',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `organizations.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Organization[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /** `GET /api/v1/organizations/{org_id}` */\n async get(): Promise<models.Organization> {\n const orgId = resolveOrg(this.#client, this.#scope, \"organizations.get\");\n const wire = await sendManagement<models.Organization>(this.#client, {\n operation: 'organizations.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}',\n path: `/api/v1/organizations/${orgId}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(body: models.UpdateOrganizationRequest): Promise<models.Organization> {\n const orgId = resolveOrg(this.#client, this.#scope, \"organizations.update\");\n const wire = await sendManagement<models.Organization>(this.#client, {\n operation: 'organizations.update',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}',\n path: `/api/v1/organizations/${orgId}`,\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `tenants` management namespace (CONTRACT §27.1).\n *\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `tenants` namespace handle.\n *\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class TenantsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): TenantsApi {\n return new TenantsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants` */\n async list(page: PageRequest = {}): Promise<Page<models.Tenant>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.list\");\n const wire = await sendManagement<Page<models.Tenant>>(this.#client, {\n operation: 'tenants.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants',\n path: `/api/v1/organizations/${orgId}/tenants`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `tenants.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Tenant[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateTenantRequest): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.create\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.create',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants',\n path: `/api/v1/organizations/${orgId}/tenants`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants/{tenant_id}` */\n async get(tenantId: string): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.get\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/tenants/{tenant_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(tenantId: string, body: models.UpdateTenant): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.update\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.update',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/organizations/{org_id}/tenants/{tenant_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(tenantId: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.delete\");\n await sendManagement<void>(this.#client, {\n operation: 'tenants.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants/{tenant_id}/audit-export`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async exportAudit(tenantId: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.export_audit\");\n await sendManagement<void>(this.#client, {\n operation: 'tenants.export_audit',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/audit-export',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/audit-export`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n\n/**\n * Request and response types for the CONTRACT §27 management surface.\n *\n * Three shapes recur and are worth knowing before reading:\n *\n * - **Sparse update bodies.** Every field is optional, and an omitted field is\n * *absent from the wire body* rather than sent as `null` — so a body\n * carrying one field changes one field (§27.4 rule 5). This SDK cannot\n * express \"set this field to null\", which is the safe direction to be\n * inexpressive in.\n * - **Replacement bodies.** `SetOrgSettings`, the organization email config,\n * `WebauthnAttestationPolicy` and `SetMtlsTrustAnchor` have required\n * fields, because a `PUT` on those routes replaces rather than patches.\n * TypeScript will not let you build one half-filled, which is the point.\n * - **Types carrying a secret.** These hold a {@link Sensitive} and come with\n * a private wire twin, because `Sensitive.toJSON()` returns\n * `\"[SENSITIVE]\"` — serializing the public type directly would send the\n * placeholder to the server, and deserializing into it would leave the\n * secret an ordinary string.\n */\nimport { Sensitive } from '../core/sensitive.js';\n\n/**\n * Drops a `tenant_scope` that names no tenants.\n *\n * CONTRACT.md §5.2.3 rule 1: the server refuses `tenant_scope: []` with\n * `400`. An assignment reaching no tenant contributes nothing anywhere, so it\n * is a grant that does not exist rather than a restriction, and the server\n * declines to guess which was meant.\n *\n * `JSON.stringify` already drops `undefined`, so the absent case needs no\n * help. `[]` is the one that does: the natural way to build the field is to\n * collect into an array and pass it, which yields `[]` for \"no tenants named\"\n * and would put the refused shape on the wire. Both spellings of absent\n * therefore travel the same way — by not appearing.\n *\n * Returns the body unchanged when there is nothing to drop, so the common\n * path allocates nothing.\n */\nexport function omitEmptyTenantScope<T>(body: T): T {\n if (\n body\n && typeof body === 'object'\n && 'tenant_scope' in body\n && Array.isArray((body as { tenant_scope?: unknown }).tenant_scope)\n && (body as { tenant_scope: unknown[] }).tenant_scope.length === 0\n ) {\n const { tenant_scope: _dropped, ...rest } = body as Record<string, unknown>;\n return rest as T;\n }\n return body;\n}\n\n/**\n * `ActorType` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ActorType =\n | \"User\"\n | \"ServiceAccount\"\n | \"System\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `AddMemberRequest` (generated from openapi.json). */\nexport interface AddMemberRequest {\n /** `user_id`. */\n user_id: string;\n}\n\n/** `AddServiceAccountMemberRequest` (generated from openapi.json). */\nexport interface AddServiceAccountMemberRequest {\n /** `service_account_id`. */\n service_account_id: string;\n}\n\n/**\n * API-based provider configuration (SendGrid, Postmark, Resend, Brevo).\n *\n * `api_key` follows the same write-only + omit-preserving contract as\n * [`SmtpConfig::password`] (D-01/D-02).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface ApiProviderConfig {\n /** Override base URL (useful for testing / self-hosted instances). */\n api_url?: string | null;\n}\n\n/** `AssignRoleToGroupRequest` (generated from openapi.json). */\nexport interface AssignRoleToGroupRequest {\n /** `group_id`. */\n group_id: string;\n /** `resource_id`. */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n}\n\n/** `AssignRoleToServiceAccountRequest` (generated from openapi.json). */\nexport interface AssignRoleToServiceAccountRequest {\n /** `resource_id`. */\n resource_id?: string | null;\n /** `service_account_id`. */\n service_account_id: string;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n}\n\n/** `AssignRoleToUserRequest` (generated from openapi.json). */\nexport interface AssignRoleToUserRequest {\n /** `resource_id`. */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * What attestation conveyance a registration ceremony requests, and whether\n * the policy is enforced at all.\n *\n * `None` is the default and reproduces today's behavior byte-for-byte:\n * `evaluate` allows every registration unconditionally, with no MDS lookup\n * (D8 step 1).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AttestationMode =\n | \"none\"\n | \"indirect\"\n | \"direct_required\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `AuditLogEntry` (generated from openapi.json). */\nexport interface AuditLogEntry {\n /** `action`. */\n action: string;\n /** `actor_id`. */\n actor_id: string;\n /** `actor_type`. */\n actor_type: ActorType;\n /** `id`. */\n id: string;\n /** `ip_address`. */\n ip_address?: string | null;\n /** `metadata`. */\n metadata: unknown;\n /** `outcome`. */\n outcome: AuditOutcome;\n /** `resource_id`. */\n resource_id?: string | null;\n /** `tenant_id`. */\n tenant_id: string;\n /** `timestamp`. */\n timestamp: string;\n}\n\n/**\n * `AuditOutcome` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AuditOutcome =\n | \"Success\"\n | \"Failure\"\n | \"Denied\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Whether this client's authorization requests may carry OpenID Connect's\n * authentication-request parameters, or whether they are ignored (X7.1).\n *\n * The bundle this governs is `prompt`, `max_age`, `acr_values`, `claims`,\n * `id_token_hint`, `login_hint`, `display`, `ui_locales` and\n * `claims_locales`. It is **one** field rather than nine booleans for the\n * same reason [`ClientProfile`] is one field rather than a dozen: a client\n * that honours `max_age` but ignores `prompt=none` is not \"mostly\n * conformant\", it is a client a relying party cannot reason about.\n *\n * [`Ignore`](Self::Ignore) is the serde default and is exactly what AXIAM\n * has always done — unknown authorization-request parameters are dropped by\n * the query deserialiser and never reach a decision. Every row written\n * before schema v54 therefore decodes to the behaviour it already had.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AuthnRequestParamsMode =\n | \"ignore\"\n | \"honour\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Request to bind a certificate to a service account. */\nexport interface BindCertificate {\n /** `certificate_id`. */\n certificate_id: string;\n}\n\n/**\n * A CA (Certificate Authority) certificate at the organization level.\n *\n * CA certificates are the root of trust for all tenant certificates within\n * the organization. Private keys for signing CAs are encrypted with\n * AES-256-GCM and stored separately; non-signing CAs only store the public\n * certificate.\n */\nexport interface CaCertificate {\n /**\n * The issuers above [`Self::public_cert_pem`], concatenated PEM, nearest\n * issuer first and the root last.\n *\n * `None` for a CA that is its own root, which is every CA AXIAM generated\n * before Vault's PKI engine was an option. Present for a `vault_pki` CA,\n * where it is the only copy of the root certificate anything outside Vault\n * will ever see — a relying party cannot validate an AXIAM-issued leaf\n * without it, and `root/generate/internal` returns it exactly once.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /**\n * Which custodian holds this CA's signing key.\n *\n * Recorded per CA rather than read from configuration, so adopting a new\n * custodian does not strand the CAs that already exist. Not secret — an\n * operator needs to see it, and it discloses only where a key is kept.\n */\n key_custody?: string;\n /**\n * Where the custodian put the key. A Vault path under its mount; `None` for\n * database custody, whose locator is the row itself.\n */\n key_locator?: string | null;\n /**\n * Whether this CA is offered as a trust anchor for mutual TLS.\n *\n * When set, the server exports this CA's **public** certificate to the\n * bundle named by `AXIAM__SERVER__TLS__CLIENT_CA_BUNDLE_PATH` at startup and\n * turns client-certificate authentication on (`optional`) if the operator\n * has not configured it explicitly. A client presenting a certificate that\n * chains to this CA is then verified by the TLS layer itself, which is what\n * `axiam_pki::mtls` needs to authenticate an IoT device or a service account\n * by certificate rather than by secret.\n *\n * # What is and is not copied\n *\n * Only `public_cert_pem` — the certificate. The **private key stays where\n * its custodian put it** (Vault, or sealed into the row) and is never\n * written to the server volume. A trust anchor is public by construction: it\n * is what the server hands every client during the TLS handshake, and every\n * device that has to validate the chain already holds a copy.\n *\n * # Why a restart\n *\n * rustls builds its `RootCertStore` once, when the listener is constructed,\n * and actix-web binds that config for the process's life. Toggling this\n * changes what the *next* boot trusts, and the API says so in its response\n * rather than pretending the change took effect.\n *\n * Defaults to `false`, so a deployment that never touches this keeps exactly\n * the TLS posture it has today.\n */\n mtls_trust_anchor?: boolean;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** The organization this CA belongs to. */\n organization_id: string;\n /**\n * The CA in this organization that signed this one.\n *\n * `None` for an organization-level CA, which is either self-signed or\n * imported and has no parent inside AXIAM.\n */\n parent_ca_id?: string | null;\n /**\n * PEM-encoded public certificate.\n *\n * The certificate that *signs*, which under `vault_pki` custody is the\n * intermediate rather than the root beneath which it was created.\n */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=ACME Corp Root CA`). */\n subject: string;\n /**\n * The tenant this CA signs for, when it is a tenant signing CA.\n *\n * `None` for an organization-level CA — the trust anchor, and the only kind\n * that existed before tenant signing CAs. `Some` for an intermediate created\n * under one, which exists so a tenant's user, service and device\n * certificates chain through a CA that can be revoked and replaced without\n * touching the anchor the rest of the estate trusts.\n */\n tenant_id?: string | null;\n}\n\n/**\n * A tenant-level certificate for users, services, or IoT devices.\n *\n * Certificates are signed by the organization's CA. The private key is\n * returned once on generation and never stored by AXIAM.\n */\nexport interface Certificate {\n /**\n * Resolved by the list projection only.\n *\n * The server resolves this for a whole page in one query, so it is populated\n * by the `list` operation and is absent from `get` (CONTRACT §27.11 rule 4).\n * Absent there means \"this read does not carry it\", not \"there is nothing\n * bound\" — the SDK does not issue a second request to fill it in.\n */\n bound_service_account_id?: string | null;\n /** `cert_type`. */\n cert_type: CertificateType;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** The CA certificate that signed this certificate. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** Arbitrary key-value metadata (e.g., device serial, user ID binding). */\n metadata: unknown;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** PEM-encoded public certificate. */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=device-001`). */\n subject: string;\n /** The tenant this certificate belongs to. */\n tenant_id: string;\n}\n\n/** Certificate issuance constraints. */\nexport interface CertificatePolicy {\n /** `default_cert_validity_days`. */\n default_cert_validity_days: number;\n /** `max_cert_validity_days`. */\n max_cert_validity_days: number;\n}\n\n/**\n * Status of a certificate in its lifecycle.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificateStatus =\n | \"Active\"\n | \"Revoked\"\n | \"Expired\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * The purpose for which a certificate was issued.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificateType =\n | \"User\"\n | \"Service\"\n | \"Device\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * FIDO certification level, as recorded in an MDS `statusReports` entry's\n * `FIDO_CERTIFIED*` status.\n *\n * Variant order is significant: `derive(PartialOrd, Ord)` gives `L1 < L1Plus\n * < L2 < L2Plus < L3 < L3Plus`, which `WebauthnAttestationPolicy::evaluate`\n * (D8 step 9) relies on directly for the `min_certification` boundary check\n * (`entry_level >= policy_min`).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificationLevel =\n | \"L1\"\n | \"L1Plus\"\n | \"L2\"\n | \"L2Plus\"\n | \"L3\"\n | \"L3Plus\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * How a client proves its identity at the token endpoint (RFC 8705 §2, OIDC\n * Core §9 naming).\n *\n * Only the methods AXIAM actually implements are representable. There is\n * deliberately no `none` variant: every AXIAM client is confidential today\n * (see `handle_authorization_code`), and adding a public-client value here\n * before the rest of the server understands one would let an operator\n * register a client whose authentication is silently skipped.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ClientAuthMethod =\n | \"client_secret_post\"\n | \"client_secret_basic\"\n | \"tls_client_auth\"\n | \"self_signed_tls_client_auth\"\n | \"private_key_jwt\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Which security posture a client is registered under (X5.1).\n *\n * This is the FAPI \"one switch\". FAPI 2.0 is not a single feature but a\n * bundle of constraints — mandatory PAR, mandatory PKCE with `S256`,\n * mandatory strong client authentication, mandatory sender-constrained\n * tokens, and a refusal of every relaxation the base specs permit. Encoding\n * them as one profile rather than a dozen independent booleans means an\n * operator cannot register a client that is *nearly* FAPI, and a reviewer\n * can answer \"is this client financial-grade?\" by reading one field.\n *\n * The same philosophy as the rate-limit postures: ordinary clients see no\n * behaviour change at all, because [`Standard`](Self::Standard) is the serde\n * default and every row written before schema v38 decodes to it.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ClientProfile =\n | \"standard\"\n | \"fapi2\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** One credential's compliance outcome (D9). */\nexport interface ComplianceReportEntry {\n /** `aaguid`. */\n aaguid?: string | null;\n /** `authenticator_name`. */\n authenticator_name?: string | null;\n /**\n * `false` only for a genuine policy violation\n * ([`ComplianceStatus::NonCompliant`]) — a credential with no recorded\n * AAGUID ([`ComplianceStatus::Unknown`], D9's pre-X3 case) is always `true`\n * here, never reported as a violation.\n */\n compliant: boolean;\n /** `credential_id`. */\n credential_id: string;\n /**\n * The credential's user-assigned name (`WebauthnCredential::name`), not the\n * owning user's account name.\n */\n name: string;\n /**\n * `None` only when `compliant` and the credential has a recorded AAGUID; set\n * for every non-compliant *and* every \"unknown\" (pre-X3) credential.\n */\n reason?: string | null;\n /** `user_id`. */\n user_id: string;\n}\n\n/** One consent record, as the subject sees it. */\nexport interface ConsentView {\n /** `accepted_at`. */\n accepted_at: string;\n /**\n * What was consented to, e.g. `terms_of_service` or\n * `oidc_scope_release:<client_id>`.\n */\n consent_type: string;\n /** The document version or, for a scope release, the consented scopes. */\n version: string;\n /**\n * Whether this record can be withdrawn here.\n *\n * `false` for `terms_of_service`: withdrawing it is not a consent operation\n * but an erasure, and it has its own endpoint with its own grace period.\n * Reported rather than silently absent so the self-service page can show the\n * record and explain it.\n */\n withdrawable: boolean;\n}\n\n/** `CreateCaCertificateRequest` (generated from openapi.json). */\nexport interface CreateCaCertificateRequest {\n /**\n * Common name for the signing intermediate — `vault_pki` custody only.\n *\n * Under that custodian Vault generates a root and an intermediate beneath\n * it, and this names the second. Defaults to the root's subject with\n * `Intermediate Authority` appended. Ignored by every other custodian, which\n * produces one self-signed CA and has no second certificate to name.\n */\n intermediate_subject?: string | null;\n /** Validity of the signing intermediate, in days. Defaults to the root's. */\n intermediate_validity_days?: number | null;\n /**\n * Issue leaves straight from the generated root instead of creating an\n * intermediate. `vault_pki` custody only, and off by default.\n *\n * The default is the safer one: a root that signs only an intermediate can\n * have that intermediate revoked and replaced without redistributing the\n * trust anchor, and a root that signs leaves cannot.\n */\n issue_from_root?: boolean;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** `subject`. */\n subject: string;\n /** Validity duration in days. */\n validity_days: number;\n}\n\n/** `CreateCertificateRequest` (generated from openapi.json). */\nexport interface CreateCertificateRequest {\n /** `cert_type`. */\n cert_type: CertificateType;\n /** `issuer_ca_id`. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** `metadata`. */\n metadata?: unknown;\n /** `subject`. */\n subject: string;\n /** Validity duration in days. */\n validity_days: number;\n}\n\n/** `CreateFederationConfigRequest` (generated from openapi.json). */\nexport interface CreateFederationConfigRequest {\n /**\n * Whether tenants of this organization may inherit this provider. Only\n * meaningful on a config in the organization-scope tenant.\n */\n allow_tenant_inheritance?: boolean | null;\n /**\n * Accepted JWT signing algorithms (OIDC) or signature algorithms (SAML).\n * Defaults to `[\"RS256\"]` when not provided (CQ-B40/REQ-14 AC-5).\n */\n allowed_algorithms?: string[] | null;\n /**\n * External IdP tenant identifiers accepted when the provider publishes a\n * templated issuer (Entra ID's `{tenantid}`).\n */\n allowed_issuer_tenants?: string[] | null;\n /**\n * Apple Key ID of the `.p8` signing key (10 characters). With both Apple\n * identifiers set, `client_secret` is the `.p8` key itself and AXIAM mints a\n * fresh five-minute client secret per token exchange.\n */\n apple_key_id?: string | null;\n /** Apple Team ID (10 characters). */\n apple_team_id?: string | null;\n /** Maps external IdP attributes to AXIAM user fields. */\n attribute_map?: unknown;\n /** OAuth2-variant authorization endpoint. Required for `OAuth2`. */\n authorization_endpoint?: string | null;\n /**\n * Sign-in-button icon for a **generic** provider, as a base64 raster data\n * URL (`data:image/png;base64,…`), already cropped to\n * `PROVIDER_ICON_SIZE_PX` square by the client.\n *\n * Refused for the branded kinds: Google, Apple and Microsoft all publish\n * sign-in-button rules that require their own mark, so substituting a\n * picture would produce a button that breaks the guidelines it exists to\n * follow.\n */\n button_icon?: string | null;\n /** OAuth2 client ID registered with the external IdP. */\n client_id: string;\n /**\n * OAuth2 client secret registered with the external IdP.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /**\n * PEM-encoded X.509 certificate for verifying SAML assertions or OIDC\n * signatures (CQ-B40/REQ-14 AC-5). Required for SAML configs.\n */\n idp_signing_cert_pem?: string | null;\n /** OIDC discovery URL or SAML metadata URL. */\n metadata_url?: string | null;\n /** Federation protocol: \"OidcConnect\" or \"Saml\". */\n protocol: string;\n /** Display name for the identity provider (e.g., \"Google\", \"Okta\"). */\n provider: string;\n /**\n * Which provider this is: `google`, `github`, `facebook`, `apple`,\n * `microsoft`, `generic_oidc`, `generic_oauth2` or `generic_saml`.\n *\n * Selects the sign-in button's branding, the per-kind defaults, and the key\n * on which a tenant config overrides an inherited organization one. Omitted\n * ⇒ derived from `protocol`, which is what every config written before this\n * field existed means.\n */\n provider_kind?: string | null;\n /**\n * Operator-chosen identifier, **required** for the `generic_*` kinds and\n * refused for the branded ones.\n */\n provider_slug?: string | null;\n /** Send PKCE on the authorization request. Forced on for `OAuth2`. */\n require_pkce?: boolean | null;\n /** Scopes to request. Omitted or empty ⇒ the per-kind default. */\n scopes?: string[] | null;\n /** OAuth2-variant token endpoint. Required for `OAuth2`. */\n token_endpoint?: string | null;\n /** `token_exchange`. */\n token_exchange?: TokenExchangeTrustRequest | null;\n /** OAuth2-variant userinfo endpoint. Required for `OAuth2`. */\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Wire twin of {@link CreateFederationConfigRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateFederationConfigRequestWire {\n allow_tenant_inheritance?: boolean | null;\n allowed_algorithms?: string[] | null;\n allowed_issuer_tenants?: string[] | null;\n apple_key_id?: string | null;\n apple_team_id?: string | null;\n attribute_map?: unknown;\n authorization_endpoint?: string | null;\n button_icon?: string | null;\n client_id: string;\n client_secret: string;\n idp_signing_cert_pem?: string | null;\n metadata_url?: string | null;\n protocol: string;\n provider: string;\n provider_kind?: string | null;\n provider_slug?: string | null;\n require_pkce?: boolean | null;\n scopes?: string[] | null;\n token_endpoint?: string | null;\n token_exchange?: TokenExchangeTrustRequest | null;\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Unwrap a `CreateFederationConfigRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createFederationConfigRequestToWire(v: CreateFederationConfigRequest): CreateFederationConfigRequestWire {\n return {\n ...v,\n client_secret: v.client_secret.expose(),\n };\n}\n\n/** `CreateGroupRequest` (generated from openapi.json). */\nexport interface CreateGroupRequest {\n /** `description`. */\n description: string;\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n}\n\n/** Body of `POST .../tenants/{tenant_id}/signing-cas`. */\nexport interface CreateIntermediateCaRequest {\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** The organization CA that signs it. */\n parent_ca_id: string;\n /** Subject for the signing CA, e.g. `CN=ACME R&D Signing CA`. */\n subject: string;\n /** Validity duration in days, capped to the parent's own expiry. */\n validity_days: number;\n}\n\n/** `CreateNotificationRuleRequest` (generated from openapi.json). */\nexport interface CreateNotificationRuleRequest {\n /** Description of what this rule monitors. */\n description: string;\n /** Event types that trigger this rule. */\n events: NotificationEventType[];\n /** Human-readable name for the rule. */\n name: string;\n /** Email addresses to notify. */\n recipient_emails: string[];\n}\n\n/** `CreateOAuth2ClientRequest` (generated from openapi.json). */\nexport interface CreateOAuth2ClientRequest {\n /**\n * X7.1 — whether this client's authorization requests may carry the OpenID\n * Connect authentication-request parameters (`prompt`, `max_age`,\n * `acr_values`, `claims`, `id_token_hint`, `login_hint`, `display`,\n * `ui_locales`, `claims_locales`).\n *\n * `\"ignore\"` (the default) is what every AXIAM client has always done: they\n * are dropped and reach no decision. `\"honour\"` opts in, and is **refused on\n * a `fapi2` client** at both this gate and the authorization endpoint — the\n * two are different answers to the same question about what a request from\n * this client means.\n */\n authn_request_params?: AuthnRequestParamsMode;\n /**\n * B5 — where OIDC back-channel logout tokens are delivered. Omit for a\n * client that does not participate.\n */\n backchannel_logout_uri?: string | null;\n /**\n * X7.3 — whether an unauthenticated authorization request from this client\n * may be answered with a redirect to the login page rather than the `401`\n * AXIAM answers today.\n *\n * Accepted and stored, but **nothing reads it yet**: the login hop it gates\n * is a later wave. Unlike `authn_request_params` it is permitted on a\n * `fapi2` client, because it relaxes nothing — it decides only how an\n * anonymous browser is answered.\n */\n browser_sso?: boolean;\n /**\n * RFC 9449 §5.2 — issue DPoP-bound (sender-constrained) access tokens to\n * this client. Independent of both the authentication method and\n * `tls_client_certificate_bound_access_tokens`; a client may ask for both\n * constraints, and a token carrying both must satisfy both.\n */\n dpop_bound_access_tokens?: boolean;\n /**\n * RFC 9449 §8 — require this client's DPoP proofs to carry a server-issued\n * nonce.\n *\n * **Not implemented in this build (SEC-097).** `true` is refused with `400`;\n * only `false` (the default) is accepted. Nothing reads the stored value, so\n * accepting `true` would persist and echo back a security switch that does\n * nothing. DPoP proofs are made single-use at the token endpoint by `jti`\n * replay detection instead — see `docs/security-profiles.md`.\n */\n dpop_require_nonce?: boolean;\n /** Grant types this client is authorized to use. */\n grant_types: string[];\n /**\n * RFC 7591 §2 — the client's public key set, inline, for `private_key_jwt`.\n * Exactly one of `jwks` and `jwks_uri` may be set.\n */\n jwks?: string | null;\n /**\n * RFC 7591 §2 — where the client publishes its public key set. Must be an\n * absolute `https` URL, and is fetched through the SSRF-guarded JWKS cache,\n * which refuses private and loopback addresses.\n */\n jwks_uri?: string | null;\n /** Human-readable name for the client. */\n name: string;\n /**\n * B5 — allow-list for RP-initiated logout's `post_logout_redirect_uri`.\n * Separate from `redirect_uris` on purpose: that list receives authorization\n * codes, this one receives a browser after logout.\n */\n post_logout_redirect_uris?: string[];\n /**\n * X5.1 — the security posture this client is registered under.\n *\n * `\"standard\"` (the default) is every AXIAM client that has ever existed.\n * `\"fapi2\"` turns on the whole FAPI 2.0 constraint bundle at once, and the\n * registration is refused unless it also sets `require_par`, a strong\n * `token_endpoint_auth_method` (either mTLS method or `private_key_jwt`),\n * and at least one sender-constraining mechanism\n * (`tls_client_certificate_bound_access_tokens` or\n * `dpop_bound_access_tokens`). See the FAPI operator guide.\n */\n profile?: ClientProfile;\n /**\n * Allowed redirect URIs (must be HTTPS, except localhost for dev). SEC-089:\n * this list doubles as the token-exchange audience allow-list — adding a URI\n * here also authorises it as a token audience for this client, so review\n * additions on exchange-capable clients with that in mind (see\n * `docs/api/token-exchange.md#audience`).\n */\n redirect_uris: string[];\n /**\n * B5 — require this client to push its authorization parameters to\n * `/oauth2/par` (RFC 9126) rather than sending them through the browser.\n */\n require_par?: boolean;\n /** Scopes the client may request. */\n scopes: string[];\n /**\n * Accepted certificate thumbprints for `self_signed_tls_client_auth`, as\n * base64url-unpadded SHA-256 digests of the DER certificate (the same\n * `x5t#S256` encoding as the `cnf` claim). More than one permits an\n * overlapping rotation.\n */\n self_signed_tls_client_auth_thumbprints?: string[];\n /** RFC 8705 §2.1.2 — expected `dNSName` SAN. */\n tls_client_auth_san_dns?: string | null;\n /** RFC 8705 §2.1.2 — expected `uniformResourceIdentifier` SAN. */\n tls_client_auth_san_uri?: string | null;\n /**\n * RFC 8705 §2.1.2 — expected certificate subject DN, RFC 4514 form. Exactly\n * one of the three `tls_client_auth_*` parameters may be set.\n */\n tls_client_auth_subject_dn?: string | null;\n /**\n * RFC 8705 §3.4 — issue certificate-bound (sender-constrained) access tokens\n * to this client. Independent of the authentication method.\n */\n tls_client_certificate_bound_access_tokens?: boolean;\n /**\n * X5.1 — how this client authenticates at the token endpoint (RFC 8705 §2).\n * Defaults to `client_secret_post`.\n */\n token_endpoint_auth_method?: ClientAuthMethod;\n}\n\n/** `CreatePermissionRequest` (generated from openapi.json). */\nexport interface CreatePermissionRequest {\n /** `action`. */\n action: string;\n /** `description`. */\n description: string;\n}\n\n/** `CreatePgpKeyRequest` (generated from openapi.json). */\nexport interface CreatePgpKeyRequest {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** Email for the OpenPGP User ID. */\n email: string;\n /** `name`. */\n name: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n}\n\n/** `CreateReactorRequest` (generated from openapi.json). */\nexport interface CreateReactorRequest {\n /** `description`. */\n description?: string;\n /** `enabled`. */\n enabled?: boolean;\n /** Event names from the registry (`GET /api/v1/reactors/events`). */\n events: string[];\n /** `failure_policy`. */\n failure_policy?: FailurePolicy | null;\n /** `mode`. */\n mode: ReactorMode;\n /** `name`. */\n name: string;\n /** `priority`. */\n priority?: number;\n /** Omit to take the 500 ms default. Capped at 5 000 ms. */\n timeout_ms?: number | null;\n}\n\n/** `CreateResourceRequest` (generated from openapi.json). */\nexport interface CreateResourceRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n /** `parent_id`. */\n parent_id?: string | null;\n /** `resource_type`. */\n resource_type: string;\n}\n\n/** `CreateRoleRequest` (generated from openapi.json). */\nexport interface CreateRoleRequest {\n /** `description`. */\n description: string;\n /** `is_global`. */\n is_global: boolean;\n /** `name`. */\n name: string;\n}\n\n/** `CreateScimTokenRequest` (generated from openapi.json). */\nexport interface CreateScimTokenRequest {\n /**\n * Lifetime in days. Defaults to the deployment maximum, and is refused above\n * it.\n */\n expires_in_days?: number | null;\n /** Operator-facing label, e.g. `\"okta-production\"`. */\n name: string;\n /**\n * The tenant user the token authenticates as. Must already hold\n * `scim:provision` — see [`create`].\n */\n user_id: string;\n}\n\n/**\n * The one-time reveal. Same shape as service-account creation: the secret is\n * returned once and only its hash is kept.\n */\nexport interface CreateScimTokenResponse {\n /** `created_at`. */\n created_at: string;\n /** `created_by`. */\n created_by: string;\n /** `expires_at`. */\n expires_at: string;\n /** `id`. */\n id: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `name`. */\n name: string;\n /**\n * The plaintext handle — shown once, never retrievable again.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n provisioning_token: Sensitive<string>;\n /** `revoked_at`. */\n revoked_at?: string | null;\n /** `status`. */\n status: ScimTokenStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Wire twin of {@link CreateScimTokenResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateScimTokenResponseWire {\n created_at: string;\n created_by: string;\n expires_at: string;\n id: string;\n last_used_at?: string | null;\n name: string;\n provisioning_token: string;\n revoked_at?: string | null;\n status: ScimTokenStatus;\n tenant_id: string;\n user_id: string;\n}\n\n/**\n * Wrap the secret fields a `CreateScimTokenResponse` response carries\n * (§27.5).\n */\nexport function createScimTokenResponseFromWire(w: CreateScimTokenResponseWire): CreateScimTokenResponse {\n return {\n ...w,\n provisioning_token: new Sensitive(w.provisioning_token),\n };\n}\n\n/** `CreateScopeRequest` (generated from openapi.json). */\nexport interface CreateScopeRequest {\n /** `description`. */\n description: string;\n /** `name`. */\n name: string;\n}\n\n/** `CreateServiceAccountRequest` (generated from openapi.json). */\nexport interface CreateServiceAccountRequest {\n /** Optional human-readable description of the account's purpose. */\n description?: string | null;\n /** `name`. */\n name: string;\n}\n\n/**\n * Request body for tenant creation (organization_id comes from the URL\n * path).\n */\nexport interface CreateTenantRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n /** `slug`. */\n slug: string;\n}\n\n/** `CreateUserRequest` (generated from openapi.json). */\nexport interface CreateUserRequest {\n /** `email`. */\n email: string;\n /** `metadata`. */\n metadata?: unknown;\n /** `opaque`. */\n opaque?: OpaqueEnrollmentPayload | null;\n /**\n * `password`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n password: Sensitive<string>;\n /** `username`. */\n username: string;\n}\n\n/**\n * Wire twin of {@link CreateUserRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateUserRequestWire {\n email: string;\n metadata?: unknown;\n opaque?: OpaqueEnrollmentPayload | null;\n password: string;\n username: string;\n}\n\n/**\n * Unwrap a `CreateUserRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createUserRequestToWire(v: CreateUserRequest): CreateUserRequestWire {\n return {\n ...v,\n password: v.password.expose(),\n };\n}\n\n/** `CreateWebhookRequest` (generated from openapi.json). */\nexport interface CreateWebhookRequest {\n /** Event types to subscribe to (e.g. `[\"user.created\", \"auth.login\"]`). */\n events: string[];\n /** `retry_policy`. */\n retry_policy?: RetryPolicy | null;\n /**\n * HMAC-SHA256 shared secret for signing payloads.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n secret: Sensitive<string>;\n /** The HTTPS URL to deliver events to. */\n url: string;\n}\n\n/**\n * Wire twin of {@link CreateWebhookRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateWebhookRequestWire {\n events: string[];\n retry_policy?: RetryPolicy | null;\n secret: string;\n url: string;\n}\n\n/**\n * Unwrap a `CreateWebhookRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createWebhookRequestToWire(v: CreateWebhookRequest): CreateWebhookRequestWire {\n return {\n ...v,\n secret: v.secret.expose(),\n };\n}\n\n/** Fully resolved email configuration (all fields present). */\nexport interface EmailConfig {\n /** `created_at`. */\n created_at: string;\n /** `enabled`. */\n enabled: boolean;\n /** `from_email`. */\n from_email: string;\n /** `from_name`. */\n from_name: string;\n /** `id`. */\n id: string;\n /** `provider`. */\n provider: ProviderConfig;\n /** `reply_to`. */\n reply_to?: string | null;\n /** `scope`. */\n scope: SettingsScope;\n /** The org_id or tenant_id this config belongs to. */\n scope_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Partial tenant overrides for email configuration. `None` = inherit from\n * org baseline.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface EmailConfigOverride {\n /** `enabled`. */\n enabled?: boolean | null;\n /** `from_email`. */\n from_email?: string | null;\n /** `from_name`. */\n from_name?: string | null;\n /** `provider`. */\n provider?: ProviderConfig | null;\n /** `Some(None)` explicitly clears reply-to; `None` inherits. */\n reply_to?: string | null;\n}\n\n/** What a test send did. */\nexport interface EmailTestResult {\n /** The provider's message id, when it returns one. */\n message_id?: string | null;\n /** Which provider the effective configuration resolved to. */\n provider: string;\n /** Where the message went — always the caller's own address. */\n to: string;\n}\n\n/** Email verification requirements. */\nexport interface EmailVerificationPolicy {\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours: number;\n /** `email_verification_required`. */\n email_verification_required: boolean;\n}\n\n/** Request body for encrypting data. */\nexport interface EncryptRequest {\n /** Base64-encoded plaintext to encrypt. */\n data_base64: string;\n}\n\n/** Result of encrypting data with a PGP public key. */\nexport interface EncryptedExport {\n /** ASCII-armored PGP encrypted data. */\n ciphertext_armored: string;\n /** `recipient_key_id`. */\n recipient_key_id: string;\n}\n\n/**\n * What the server does when an interceptor does not produce a usable reply —\n * timeout, transport failure, bad signature, stale nonce, or a patch the\n * allow-list rejects.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type FailurePolicy =\n | \"fail_closed\"\n | \"fail_open\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Federation config response -- omits client_secret. */\nexport interface FederationConfigResponse {\n /** Whether tenants of this organization may inherit this provider. */\n allow_tenant_inheritance: boolean;\n /**\n * Accepted signing algorithms. Returned for OIDC and SAML; meaningless, and\n * therefore empty, for the OAuth2 variant.\n */\n allowed_algorithms: string[];\n /** Accepted external IdP tenants for a templated issuer. */\n allowed_issuer_tenants: string[];\n /** Apple Key ID. */\n apple_key_id?: string | null;\n /** Apple Team ID. Not secret — the `.p8` key is, and it is never returned. */\n apple_team_id?: string | null;\n /** `attribute_map`. */\n attribute_map: unknown;\n /** OAuth2-variant authorization endpoint. */\n authorization_endpoint?: string | null;\n /** Custom sign-in-button icon, when one is set. */\n button_icon?: string | null;\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /**\n * The per-kind default that an empty `scopes` resolves to. Returned so the\n * admin UI can show what will actually be requested without duplicating the\n * table.\n */\n effective_scopes: string[];\n /** `enabled`. */\n enabled: boolean;\n /**\n * Whether AXIAM ships this provider's own mark. When true the button uses it\n * and `button_icon` is refused; when false the button reads \"Sign in with\n * <provider>\" and may carry a custom icon.\n */\n has_bundled_mark: boolean;\n /** `id`. */\n id: string;\n /** `metadata_url`. */\n metadata_url?: string | null;\n /**\n * Whether AXIAM mints this provider's client secret itself, per exchange,\n * rather than sending a stored one. True only for an Apple config with both\n * identifiers set.\n */\n mints_client_secret: boolean;\n /**\n * Whether PKCE is sent on the authorization request. Always true for the\n * OAuth2 variant regardless of the stored flag.\n */\n pkce_required: boolean;\n /** `protocol`. */\n protocol: string;\n /** `provider`. */\n provider: string;\n /**\n * Which provider this is. Derived from `protocol` for a config written\n * before the field existed.\n */\n provider_kind: string;\n /** Operator-chosen identifier for a `generic_*` kind. */\n provider_slug?: string | null;\n /**\n * Scopes as stored. Empty means \"use the per-kind default\"; see\n * `effective_scopes`.\n */\n scopes: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** OAuth2-variant token endpoint. */\n token_endpoint?: string | null;\n /** X4 external token-exchange trust. */\n token_exchange: TokenExchangeTrustResponse;\n /** `updated_at`. */\n updated_at: string;\n /** OAuth2-variant userinfo endpoint. */\n userinfo_endpoint?: string | null;\n}\n\n/** `FederationLinkResponse` (generated from openapi.json). */\nexport interface FederationLinkResponse {\n /** `created_at`. */\n created_at: string;\n /** `external_email`. */\n external_email?: string | null;\n /** `external_subject`. */\n external_subject: string;\n /** `federation_config_id`. */\n federation_config_id: string;\n /** `id`. */\n id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Response returned when a CA certificate is generated.\n *\n * Includes the private key PEM, which is returned **once** and never stored\n * or retrievable again — when the custodian produced one at all. Under\n * `vault_pki` custody the key was born inside Vault and there is nothing to\n * return, which is the point of that custodian rather than a shortcoming of\n * this response.\n */\nexport interface GeneratedCaCertificate {\n /**\n * The issuers above [`Self::public_cert_pem`], concatenated PEM, nearest\n * issuer first and the root last.\n *\n * `None` for a CA that is its own root, which is every CA AXIAM generated\n * before Vault's PKI engine was an option. Present for a `vault_pki` CA,\n * where it is the only copy of the root certificate anything outside Vault\n * will ever see — a relying party cannot validate an AXIAM-issued leaf\n * without it, and `root/generate/internal` returns it exactly once.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /**\n * Which custodian holds this CA's signing key.\n *\n * Recorded per CA rather than read from configuration, so adopting a new\n * custodian does not strand the CAs that already exist. Not secret — an\n * operator needs to see it, and it discloses only where a key is kept.\n */\n key_custody?: string;\n /**\n * Where the custodian put the key. A Vault path under its mount; `None` for\n * database custody, whose locator is the row itself.\n */\n key_locator?: string | null;\n /**\n * Whether this CA is offered as a trust anchor for mutual TLS.\n *\n * When set, the server exports this CA's **public** certificate to the\n * bundle named by `AXIAM__SERVER__TLS__CLIENT_CA_BUNDLE_PATH` at startup and\n * turns client-certificate authentication on (`optional`) if the operator\n * has not configured it explicitly. A client presenting a certificate that\n * chains to this CA is then verified by the TLS layer itself, which is what\n * `axiam_pki::mtls` needs to authenticate an IoT device or a service account\n * by certificate rather than by secret.\n *\n * # What is and is not copied\n *\n * Only `public_cert_pem` — the certificate. The **private key stays where\n * its custodian put it** (Vault, or sealed into the row) and is never\n * written to the server volume. A trust anchor is public by construction: it\n * is what the server hands every client during the TLS handshake, and every\n * device that has to validate the chain already holds a copy.\n *\n * # Why a restart\n *\n * rustls builds its `RootCertStore` once, when the listener is constructed,\n * and actix-web binds that config for the process's life. Toggling this\n * changes what the *next* boot trusts, and the API says so in its response\n * rather than pretending the change took effect.\n *\n * Defaults to `false`, so a deployment that never touches this keeps exactly\n * the TLS posture it has today.\n */\n mtls_trust_anchor?: boolean;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** The organization this CA belongs to. */\n organization_id: string;\n /**\n * The CA in this organization that signed this one.\n *\n * `None` for an organization-level CA, which is either self-signed or\n * imported and has no parent inside AXIAM.\n */\n parent_ca_id?: string | null;\n /**\n * PEM-encoded private key — returned only on generation, and only when there\n * is one to return.\n *\n * Absent under `vault_pki` custody, where the key was generated inside Vault\n * and no API exports it. The field is omitted rather than sent as `null` so\n * a client that has always read it keeps working unchanged for every\n * custodian that does produce a key.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem?: Sensitive<string>;\n /**\n * PEM-encoded public certificate.\n *\n * The certificate that *signs*, which under `vault_pki` custody is the\n * intermediate rather than the root beneath which it was created.\n */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=ACME Corp Root CA`). */\n subject: string;\n /**\n * The tenant this CA signs for, when it is a tenant signing CA.\n *\n * `None` for an organization-level CA — the trust anchor, and the only kind\n * that existed before tenant signing CAs. `Some` for an intermediate created\n * under one, which exists so a tenant's user, service and device\n * certificates chain through a CA that can be revoked and replaced without\n * touching the anchor the rest of the estate trusts.\n */\n tenant_id?: string | null;\n}\n\n/**\n * Wire twin of {@link GeneratedCaCertificate} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedCaCertificateWire {\n chain_pem?: string | null;\n created_at: string;\n fingerprint: string;\n id: string;\n key_algorithm: KeyAlgorithm;\n key_custody?: string;\n key_locator?: string | null;\n mtls_trust_anchor?: boolean;\n not_after: string;\n not_before: string;\n organization_id: string;\n parent_ca_id?: string | null;\n private_key_pem?: string;\n public_cert_pem: string;\n status: CertificateStatus;\n subject: string;\n tenant_id?: string | null;\n}\n\n/**\n * Wrap the secret fields a `GeneratedCaCertificate` response carries\n * (§27.5).\n */\nexport function generatedCaCertificateFromWire(w: GeneratedCaCertificateWire): GeneratedCaCertificate {\n return {\n ...w,\n private_key_pem: w.private_key_pem === undefined ? undefined : new Sensitive(w.private_key_pem),\n };\n}\n\n/**\n * Response returned when a tenant certificate is generated.\n *\n * Includes the private key PEM, returned **once** and never stored.\n */\nexport interface GeneratedCertificate {\n /** `cert_type`. */\n cert_type: CertificateType;\n /**\n * The issuing chain, concatenated PEM, nearest issuer first.\n *\n * Present only when the signer returned one — which is the `vault_pki` case,\n * where the root's certificate exists nowhere a client could fetch it from.\n * For a CA AXIAM signed with itself the chain is the CA certificate, which\n * `GET .../ca-certificates/{id}` already serves, so the field is omitted\n * rather than restating it.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** The CA certificate that signed this certificate. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** Arbitrary key-value metadata (e.g., device serial, user ID binding). */\n metadata: unknown;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /**\n * PEM-encoded private key — returned only on generation.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem: Sensitive<string>;\n /** PEM-encoded public certificate. */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=device-001`). */\n subject: string;\n /** The tenant this certificate belongs to. */\n tenant_id: string;\n}\n\n/**\n * Wire twin of {@link GeneratedCertificate} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedCertificateWire {\n cert_type: CertificateType;\n chain_pem?: string | null;\n created_at: string;\n fingerprint: string;\n id: string;\n issuer_ca_id: string;\n key_algorithm: KeyAlgorithm;\n metadata: unknown;\n not_after: string;\n not_before: string;\n private_key_pem: string;\n public_cert_pem: string;\n status: CertificateStatus;\n subject: string;\n tenant_id: string;\n}\n\n/** Wrap the secret fields a `GeneratedCertificate` response carries (§27.5). */\nexport function generatedCertificateFromWire(w: GeneratedCertificateWire): GeneratedCertificate {\n return {\n ...w,\n private_key_pem: new Sensitive(w.private_key_pem),\n };\n}\n\n/** Response returned when a PGP key is generated. */\nexport interface GeneratedPgpKey {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** `created_at`. */\n created_at: string;\n /** OpenPGP key fingerprint (hex). */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /**\n * ASCII-armored private key — returned only on generation for `Export` keys.\n * For `AuditSigning` keys this is `None` (private key is server-side only).\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_armored?: Sensitive<string>;\n /** `public_key_armored`. */\n public_key_armored: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n /** `status`. */\n status: PgpKeyStatus;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * Wire twin of {@link GeneratedPgpKey} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedPgpKeyWire {\n algorithm: PgpKeyAlgorithm;\n created_at: string;\n fingerprint: string;\n id: string;\n name: string;\n private_key_armored?: string;\n public_key_armored: string;\n purpose: PgpKeyPurpose;\n status: PgpKeyStatus;\n tenant_id: string;\n}\n\n/** Wrap the secret fields a `GeneratedPgpKey` response carries (§27.5). */\nexport function generatedPgpKeyFromWire(w: GeneratedPgpKeyWire): GeneratedPgpKey {\n return {\n ...w,\n private_key_armored: w.private_key_armored === undefined ? undefined : new Sensitive(w.private_key_armored),\n };\n}\n\n/** `GrantPermissionRequest` (generated from openapi.json). */\nexport interface GrantPermissionRequest {\n /**\n * B1: `\"allow\"` (the default) or `\"deny\"`.\n *\n * A deny grant **overrides every allow**, at any depth of the resource\n * hierarchy and at equal specificity — it is not most-specific-wins. See\n * `claude_dev/deny-override-design.md` for the precedence table and for why\n * that trade was made.\n *\n * Omitting the field means `\"allow\"`, so every existing client keeps working\n * unchanged and no migration is required.\n */\n effect?: PermissionEffect;\n /** `permission_id`. */\n permission_id: string;\n /** `scope_ids`. */\n scope_ids?: string[];\n}\n\n/** Body for recording an OIDC scope-release consent. */\nexport interface GrantScopeConsent {\n /** The relying party the claims would be released to. */\n client_id: string;\n /**\n * The sensitive scopes being consented to. Order does not matter; the record\n * is written in the canonical order so that the same consent has one name.\n */\n scopes: string[];\n}\n\n/** A scope named by a grant, resolved to something a human can read. */\nexport interface GrantedScope {\n /** The scope's id, as it appears in the grant's `scope_ids`. */\n id: string;\n /** The scope's name, e.g. `invoices`. */\n name: string;\n /** The resource the scope belongs to. */\n resource_id: string;\n}\n\n/**\n * A group of users that can access resources based on their roles and\n * permissions. Groups simplify role management by allowing roles to be\n * assigned to a group rather than individual users.\n */\nexport interface Group {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `metadata`. */\n metadata: unknown;\n /** `name`. */\n name: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `HealthResponse` (generated from openapi.json). */\nexport interface HealthResponse {\n /** `status`. */\n status: string;\n}\n\n/**\n * Body of `POST /api/v1/organizations/{org_id}/ca-certificates/import`.\n *\n * Deliberately carries no subject, validity window or key algorithm: all\n * three are read out of the certificate itself. A caller that could name\n * them separately could name a subject the certificate does not have, and\n * AXIAM would enforce the claim while every relying party read the\n * certificate.\n */\nexport interface ImportCaCertificateRequest {\n /**\n * PEM-encoded private key, if AXIAM is to take custody of it.\n *\n * Omit it to register the certificate as a trust anchor only. Write-only: it\n * goes to the configured custodian on the way in and no endpoint returns it.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem?: Sensitive<string>;\n /** PEM-encoded CA certificate. */\n public_cert_pem: string;\n}\n\n/**\n * Wire twin of {@link ImportCaCertificateRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface ImportCaCertificateRequestWire {\n private_key_pem?: string;\n public_cert_pem: string;\n}\n\n/**\n * Unwrap a `ImportCaCertificateRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function importCaCertificateRequestToWire(v: ImportCaCertificateRequest): ImportCaCertificateRequestWire {\n return {\n ...v,\n private_key_pem: v.private_key_pem === undefined ? undefined : v.private_key_pem.expose(),\n };\n}\n\n/**\n * The type of key algorithm used for a certificate.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type KeyAlgorithm =\n | \"Rsa4096\"\n | \"Ed25519\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Account lockout rules. */\nexport interface LockoutPolicy {\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier: number;\n /** `lockout_duration_secs`. */\n lockout_duration_secs: number;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts: number;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs: number;\n}\n\n/**\n * `POST /api/v1/mds/refresh` response — the outcome of one ingestion attempt\n * (mirrors `axiam_db::mds_ingest::MdsIngestOutcome`).\n */\nexport type MdsRefreshOutcome =\n | {\n /** Discriminator: always `initial`. */\n outcome: \"initial\";\n /** `entry_count`. */\n entry_count: number;\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `replaced`. */\n outcome: \"replaced\";\n /** `entry_count`. */\n entry_count: number;\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `no_op_refresh`. */\n outcome: \"no_op_refresh\";\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `rollback_rejected`. */\n outcome: \"rollback_rejected\";\n /** `attempted_no`. */\n attempted_no: number;\n /** `stored_no`. */\n stored_no: number;\n };\n\n/**\n * `GET /api/v1/mds/status` response. `no`/`next_update`/`last_refreshed_at`\n * are `None` and `stale` is `false` when MDS has never been ingested — a\n * meaningful, valid answer (\"nothing ingested yet\"), not an error.\n */\nexport interface MdsStatusResponse {\n /** `entry_count`. */\n entry_count: number;\n /** `last_refreshed_at`. */\n last_refreshed_at?: string | null;\n /** `next_update`. */\n next_update?: string | null;\n /** `no`. */\n no?: number | null;\n /** `stale`. */\n stale: boolean;\n}\n\n/** `MfaMethodResponse` (generated from openapi.json). */\nexport interface MfaMethodResponse {\n /** `created_at`. */\n created_at: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `method_id`. */\n method_id: string;\n /** `method_type`. */\n method_type: MfaMethodType;\n /** `name`. */\n name: string;\n}\n\n/**\n * Type of MFA method.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type MfaMethodType =\n | \"Totp\"\n | \"Passkey\"\n | \"SecurityKey\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Multi-factor authentication policy. */\nexport interface MfaPolicy {\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs: number;\n /** `mfa_enforced`. */\n mfa_enforced: boolean;\n}\n\n/** What a custody migration did. */\nexport interface MigrateCustodyResponse {\n /** The CA whose key moved. */\n ca_certificate_id: string;\n /** Where it is now. */\n key_custody: string;\n /** Where the new custodian filed it, when the custodian has a path. */\n key_locator?: string | null;\n /** Where the key was. */\n previous_custody: string;\n}\n\n/** The acknowledgement, which is mostly about the restart. */\nexport interface MtlsTrustAnchorResponse {\n /** The CA this is about. */\n ca_certificate_id: string;\n /** A sentence an operator can act on, rather than a bare boolean. */\n message: string;\n /** The flag as now stored. */\n mtls_trust_anchor: boolean;\n /**\n * Whether the change still needs a restart to take effect.\n *\n * `false` when the live listener accepted the new anchor set — the ordinary\n * case on a TLS deployment. `true` only when there was no listener to reload\n * into (plaintext, or `client_auth = off`), where the flag is stored and\n * applies at the next start.\n */\n restart_required: boolean;\n /**\n * How many CAs the listener now trusts for client authentication, when it\n * was reloaded. `None` when nothing was reloaded.\n */\n trusted_anchors?: number | null;\n}\n\n/**\n * Events that can trigger an admin notification.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type NotificationEventType =\n | \"login_failure\"\n | \"account_locked\"\n | \"mfa_enrollment_changed\"\n | \"password_changed\"\n | \"password_reset_requested\"\n | \"role_assigned\"\n | \"role_unassigned\"\n | \"permission_granted\"\n | \"permission_revoked\"\n | \"certificate_issued\"\n | \"certificate_revoked\"\n | \"ca_certificate_revoked\"\n | \"user_created\"\n | \"user_deleted\"\n | \"user_updated\"\n | \"service_account_created\"\n | \"service_account_deleted\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Admin notification preferences. */\nexport interface NotificationPolicy {\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled: boolean;\n}\n\n/** Notification rule response. */\nexport interface NotificationRuleResponse {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: NotificationEventType[];\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `recipient_emails`. */\n recipient_emails: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Response for client creation -- includes the one-time plaintext secret. */\nexport interface OAuth2ClientCreatedResponse {\n /** `client_id`. */\n client_id: string;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /** `created_at`. */\n created_at: string;\n /** `grant_types`. */\n grant_types: string[];\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `redirect_uris`. */\n redirect_uris: string[];\n /** `scopes`. */\n scopes: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Wire twin of {@link OAuth2ClientCreatedResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface OAuth2ClientCreatedResponseWire {\n client_id: string;\n client_secret: string;\n created_at: string;\n grant_types: string[];\n id: string;\n name: string;\n redirect_uris: string[];\n scopes: string[];\n tenant_id: string;\n updated_at: string;\n}\n\n/**\n * Wrap the secret fields a `OAuth2ClientCreatedResponse` response carries\n * (§27.5).\n */\nexport function oAuth2ClientCreatedResponseFromWire(w: OAuth2ClientCreatedResponseWire): OAuth2ClientCreatedResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/** OAuth2 client response -- omits client_secret_hash. */\nexport interface OAuth2ClientResponse {\n /**\n * X7.1 — echoed so an operator can audit which clients act on the OIDC\n * authentication-request parameters, from this endpoint rather than from the\n * database.\n */\n authn_request_params: AuthnRequestParamsMode;\n /** X7.3 — echoed for the same reason. */\n browser_sso: boolean;\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /** `dpop_bound_access_tokens`. */\n dpop_bound_access_tokens: boolean;\n /** `dpop_require_nonce`. */\n dpop_require_nonce: boolean;\n /** `grant_types`. */\n grant_types: string[];\n /** `id`. */\n id: string;\n /**\n * X5.1 — echoed so an operator can confirm which key source is registered.\n * The document itself is public key material, so returning it leaks nothing;\n * a `jwks_uri` is likewise public by construction.\n */\n jwks?: string | null;\n /** `jwks_uri`. */\n jwks_uri?: string | null;\n /** `name`. */\n name: string;\n /**\n * X5.1 — the registered posture and mTLS credentials. Read-back matters: an\n * operator auditing which clients are financial-grade should be able to\n * answer it from this endpoint rather than from the database.\n */\n profile: ClientProfile;\n /** `redirect_uris`. */\n redirect_uris: string[];\n /** `require_par`. */\n require_par: boolean;\n /** `scopes`. */\n scopes: string[];\n /** `self_signed_tls_client_auth_thumbprints`. */\n self_signed_tls_client_auth_thumbprints: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `tls_client_auth_san_dns`. */\n tls_client_auth_san_dns?: string | null;\n /** `tls_client_auth_san_uri`. */\n tls_client_auth_san_uri?: string | null;\n /** `tls_client_auth_subject_dn`. */\n tls_client_auth_subject_dn?: string | null;\n /** `tls_client_certificate_bound_access_tokens`. */\n tls_client_certificate_bound_access_tokens: boolean;\n /** `token_endpoint_auth_method`. */\n token_endpoint_auth_method: ClientAuthMethod;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `OidcAuthorizeRequest` (generated from openapi.json). */\nexport interface OidcAuthorizeRequest {\n /** ID of the federation config to use. */\n config_id: string;\n /** Nonce for replay protection (generated by the caller). */\n nonce: string;\n /** Redirect URI the external IdP should return the user to. */\n redirect_uri: string;\n /** CSRF state value (generated by the caller). */\n state: string;\n}\n\n/** `OidcAuthorizeResponse` (generated from openapi.json). */\nexport interface OidcAuthorizeResponse {\n /** The full authorization URL to redirect the user to. */\n url: string;\n}\n\n/** `OidcCallbackRequest` (generated from openapi.json). */\nexport interface OidcCallbackRequest {\n /** Authorization code returned by the external IdP. */\n code: string;\n /** ID of the federation config used in the authorization request. */\n config_id: string;\n /**\n * Client-supplied nonce (SECHRD-07/D-04: retained for backward compatibility\n * with older callers, but IGNORED for verification — `expected_nonce` always\n * comes from the server-side `FederationLoginState` row looked up via\n * `state`, never from this field).\n */\n nonce: string;\n /** Redirect URI that was used in the authorization request. */\n redirect_uri: string;\n /**\n * CSRF state value from the authorization request. Used to look up the\n * server-side `FederationLoginState` row that holds the real nonce\n * (SECHRD-07/D-04) — required so the callback can find its login state.\n */\n state: string;\n}\n\n/** `OidcCallbackResponse` (generated from openapi.json). */\nexport interface OidcCallbackResponse {\n /** `federation_link_id`. */\n federation_link_id: string;\n /** `newly_provisioned`. */\n newly_provisioned: boolean;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * OpenID Connect surface controls (X7 G8, plan §4.6/§4.8).\n *\n * Two settings that are not password rules, and are here because this is the\n * org-baseline-plus-tenant-override surface every other per-tenant control\n * lives on. They are also the two settings in this model that are *not* of\n * the same kind as each other, so it is worth saying which is which:\n *\n * * [`Self::sensitive_scopes_enabled`] **is** ordered. Releasing personal\n * data is the less-restrictive direction, so it is validated disable-only —\n * the mirror image of `mfa_enforced` — and a tenant can turn its\n * organization's decision off but never on. * [`Self::default_locale`] is\n * **not** ordered, and no ordering is invented for it. A language is a\n * presentation preference; there is no sense in which Italian is stricter\n * than French. [`validate_tenant_override`] therefore does not check it and\n * [`clamp_overrides_to_org`] never clears it. The model's rule is \"a tenant\n * may only be more restrictive\", which binds every field that *has* a\n * restrictiveness; a field that has none cannot violate it.\n */\nexport interface OidcPolicy {\n /**\n * The BCP 47 tag the sign-in page falls back to when the relying party's\n * `ui_locales` selects nothing (W5's chain, plan §4.6).\n *\n * `None` means \"no tenant preference\", which lands on the deployment default\n * (`en`) — the behaviour every deployment had before this field existed. A\n * tag this build does not ship also lands there: the parse is exact rather\n * than a language lookup, so a stored `fr-CA` reads as \"somebody wrote\n * something this binary does not ship\" rather than as a guess at French.\n *\n * Stored as a string rather than as the `Locale` enum because that enum\n * lives in `axiam-oauth2`, four layers above this crate, and the crate\n * layering points inward.\n */\n default_locale?: string | null;\n /**\n * Whether `address` and `phone` may be registered on a client, requested at\n * the authorization endpoint, and released at UserInfo (X7 G8).\n *\n * **Off unless an organization turns it on.** The two scopes release a\n * postal address and a telephone number — categories of personal data AXIAM\n * has no other use for — so the deployment that has never thought about them\n * releases nothing, and the operator who has thought about them says so\n * once, at the organization level, where the lawful basis for holding the\n * data was decided.\n *\n * The switch is a *capability*, not a grant: with it on, a client still has\n * to register the scope, the request still has to ask for it, and the user\n * still has to have consented. It is the first of four gates, and it is the\n * only one an operator can close for everybody at once.\n */\n sensitive_scopes_enabled: boolean;\n}\n\n/**\n * The client-supplied half of an OPAQUE enrolment, as it appears inside\n * registration / change-password / reset-completion / bootstrap request\n * bodies.\n *\n * There is no standalone `register/finish` endpoint, deliberately. A record\n * can only be created at a moment when the plaintext password legitimately\n * exists on the client, and every one of those moments is already an\n * endpoint that takes a password. A free-standing finish would be an\n * endpoint whose only job is to attach a credential to an account, which is\n * a thing worth not having.\n *\n * Kept separate from [`CreateOpaqueCredential`] because the tenant, the user\n * and the credential identifier are all decided by the server — a client\n * that could name them could enrol a record against somebody else's account.\n */\nexport interface OpaqueEnrollmentPayload {\n /** The `opaque_session` from the register/start response, echoed verbatim. */\n opaque_session: string;\n /** Lowercase-hex serialized RFC 9807 `RegistrationRecord`. */\n registration_record: string;\n}\n\n/**\n * Secure Remote Password policy.\n *\n * `suite` and `ksf` are the parameters a *new* registration record is\n * enrolled with. They deliberately do not apply retroactively: an existing\n * record is only valid under the suite and KSF it was created with, so\n * tightening these takes effect as users next set a password rather than\n * invalidating everybody at once.\n */\nexport interface OpaquePolicy {\n /**\n * Key-stretching function new records are enrolled under. Both variants are\n * memory-hard; see [`opaque_ksf_is_at_least`] for the tighten-only ordering.\n */\n opaque_ksf: string;\n /** Whether OPAQUE is offered, and whether password login is still accepted. */\n opaque_mode: string;\n /** RFC 9807 ciphersuite new records are enrolled under. */\n opaque_suite: string;\n}\n\n/**\n * An organization groups multiple tenants under a single administrative\n * entity.\n *\n * Organizations represent companies, departments, or business units. CA\n * certificates are registered at the organization level, enabling a\n * hierarchical trust model across all tenants.\n */\nexport interface Organization {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /** Arbitrary key-value metadata. */\n metadata: unknown;\n /** Human-readable name. */\n name: string;\n /** URL-safe unique identifier (e.g., `acme-corp`). */\n slug: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Password complexity and history requirements. */\nexport interface PasswordPolicy {\n /** `hibp_check_enabled`. */\n hibp_check_enabled: boolean;\n /** `min_length`. */\n min_length: number;\n /** `password_history_count`. */\n password_history_count: number;\n /** `require_digits`. */\n require_digits: boolean;\n /** `require_lowercase`. */\n require_lowercase: boolean;\n /** `require_symbols`. */\n require_symbols: boolean;\n /** `require_uppercase`. */\n require_uppercase: boolean;\n}\n\n/** `Permission` (generated from openapi.json). */\nexport interface Permission {\n /** The action this permission represents (e.g., `read`, `write`, `delete`). */\n action: string;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Whether a grant permits an action or refuses it (B1, deny-override).\n *\n * # Precedence\n *\n * Default deny -> an [`PermissionEffect::Allow`] grant permits -> a\n * [`PermissionEffect::Deny`] grant refuses, **and beats every allow**,\n * wherever either sits in the resource hierarchy. Deny wins; there is no\n * most-specific-wins tie-break.\n *\n * That choice is deliberate and is argued in full in\n * `claude_dev/deny-override-design.md` §2.1. The short version:\n * deny-override buys one checkable property — **adding a deny rule can never\n * widen access, and can never be undone by adding allows** — and\n * most-specific-wins buys expressiveness at the cost of making \"is X\n * denied?\" unanswerable without enumerating every other rule that might\n * out-specify it.\n *\n * [`PermissionEffect::Allow`] is the default, so data written before this\n * existed, and clients that send no `effect`, both mean \"allow\". No\n * migration.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PermissionEffect =\n | \"allow\"\n | \"deny\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** An OpenPGP key stored by AXIAM. */\nexport interface PgpKey {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** `created_at`. */\n created_at: string;\n /** OpenPGP key fingerprint (hex). */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `public_key_armored`. */\n public_key_armored: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n /** `status`. */\n status: PgpKeyStatus;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * Key algorithm for OpenPGP keys.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyAlgorithm =\n | \"Rsa4096\"\n | \"Ed25519\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * The purpose of an OpenPGP key.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyPurpose =\n | \"AuditSigning\"\n | \"Export\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Status of an OpenPGP key.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyStatus =\n | \"Active\"\n | \"Revoked\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * `GET` response: the stored policy plus the unknown-AAGUID action it\n * currently *resolves to*.\n *\n * `unknown_aaguid` is nullable, where `null` means \"use this mode's default\"\n * (deny under `direct_required`, allow otherwise). A client that only saw\n * the stored `null` would have to re-derive that rule itself to display what\n * the policy actually does — and a security rule implemented twice is a\n * security rule that will eventually disagree with itself. So the server\n * resolves it once, here, and reports both: the admin's stored intent and\n * its effect.\n */\nexport interface PolicyResponse {\n /**\n * `None` = every AAGUID is allowed except `blocked_aaguids`.\n *\n * `Some(vec![])` is a deliberate \"nothing may register\" policy and is\n * accepted as such: `evaluate` denies every AAGUID against an empty\n * allow-list. Nothing rejects it, precisely because the failure direction is\n * safe — a client that sends `[]` when it meant `null` gets a locked-down\n * tenant, which is visible immediately, rather than an open one, which is\n * not.\n */\n allowed_aaguids?: string[] | null;\n /**\n * Deny registration if the MDS entry has ever reported `REVOKED` or any\n * `*_COMPROMISE` status (sticky — D8 step 7).\n */\n block_revoked_status: boolean;\n /** `blocked_aaguids`. */\n blocked_aaguids?: string[];\n /**\n * The action actually applied to an AAGUID with no MDS metadata, with\n * `unknown_aaguid: null` resolved against `mode`. Read-only — `PUT` ignores\n * it.\n */\n effective_unknown_aaguid: UnknownAaguidAction;\n /** `min_certification`. */\n min_certification?: CertificationLevel | null;\n /** `mode`. */\n mode: AttestationMode;\n /**\n * Require *some* `FIDO_CERTIFIED*` status, any level. Independent of (and\n * checked before) `min_certification`.\n */\n require_fido_certified: boolean;\n /** `unknown_aaguid`. */\n unknown_aaguid?: UnknownAaguidAction | null;\n}\n\n/** Data-retention rules that apply after a subject asks to be erased. */\nexport interface PrivacyPolicy {\n /**\n * How long a requested account erasure stays cancellable before the purge\n * runs, in days.\n *\n * The window exists so an erasure triggered by mistake, or under coercion,\n * can be undone — `POST /api/v1/auth/account/delete/cancel` works for\n * exactly this long. It was fixed at 30 days in the handler, which meant the\n * \"cancel a pending deletion\" control in the admin UI referred to a duration\n * no operator could see or change.\n *\n * Shorter is the more restrictive direction, so a tenant may lower it and\n * not raise it: it is time spent holding data the subject has already asked\n * to have erased, and GDPR Art. 17(1) asks for that to be \"without undue\n * delay\". The upper bound of 90 days is where Art. 12(3)'s one-month\n * response deadline plus its two-month extension for complex cases runs out;\n * anything past 30 wants a reason recorded.\n */\n deletion_grace_period_days: number;\n}\n\n/** Provider-specific connection details. */\nexport type ProviderConfig =\n | ({\n /** Discriminator: always `smtp`. */\n kind: \"smtp\";\n } & SmtpConfig)\n | ({\n /** Discriminator: always `send_grid`. */\n kind: \"send_grid\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `postmark`. */\n kind: \"postmark\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `resend`. */\n kind: \"resend\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `brevo`. */\n kind: \"brevo\";\n } & ApiProviderConfig);\n\n/** One hookable event, as the registry describes it. */\nexport interface ReactorEventDescriptor {\n /** `default_failure_policy`. */\n default_failure_policy: FailurePolicy;\n /** `description`. */\n description: string;\n /** `interceptable`. */\n interceptable: boolean;\n /** `mutable`. */\n mutable: boolean;\n /**\n * Exact field names, or a namespace prefix ending in `.` — `ext.` admits\n * `ext.department` and nothing outside the namespace.\n */\n mutable_fields: string[];\n /** `name`. */\n name: string;\n}\n\n/**\n * How a reactor participates in an event.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ReactorMode =\n | \"intercept\"\n | \"listen\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `ReactorResponse` (generated from openapi.json). */\nexport interface ReactorResponse {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: string[];\n /** `failure_policy`. */\n failure_policy: FailurePolicy;\n /** `id`. */\n id: string;\n /**\n * When this reactor last consumed from its queue. `null` means it has never\n * connected — which the admin UI shows differently from \"connected once,\n * silent since\".\n */\n last_seen_at?: string | null;\n /** `mode`. */\n mode: ReactorMode;\n /** `name`. */\n name: string;\n /** `priority`. */\n priority: number;\n /**\n * R2.3: dispatch failures against this registration in the last 24h whose\n * cause was a timeout (as opposed to a rejected reply, a transport failure,\n * or overload), capped at 100 — a health signal read from the audit trail\n * R2.2 started writing, not a replacement for the audit log itself (`GET\n * /api/v1/audit-log` is that).\n */\n recent_timeout_count: number;\n /**\n * R2.3: operations this reactor's own reply *denied* in the last 24h, capped\n * at 100. Distinct from `recent_timeout_count`: a veto is the reactor\n * working as designed; a timeout is the reactor not answering.\n */\n recent_veto_count: number;\n /** `tenant_id`. */\n tenant_id: string;\n /** `timeout_ms`. */\n timeout_ms: number;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `ReadyResponse` (generated from openapi.json). */\nexport interface ReadyResponse {\n /** `database`. */\n database: string;\n /** `status`. */\n status: string;\n}\n\n/**\n * A permission grant with its scopes resolved.\n *\n * A superset of [`PermissionGrant`]: `scope_ids` is still present and still\n * authoritative, so a client written before `scopes` existed is unaffected.\n */\nexport interface ResolvedPermissionGrant {\n /** Whether the grant permits or refuses. */\n effect: PermissionEffect;\n /** The permission this grant is about. */\n permission: Permission;\n /** The scope ids the grant is constrained to. Empty is the wildcard. */\n scope_ids: string[];\n /**\n * The scopes `scope_ids` names, in the same order where resolvable.\n *\n * A scope that cannot be resolved is **omitted** rather than represented by\n * a placeholder, so this can be shorter than `scope_ids`. That happens when\n * a scope was deleted while a grant still referenced it, and showing a name\n * for something that no longer exists would be worse than showing one fewer\n * chip beside a count that still says how many ids the grant carries.\n */\n scopes: GrantedScope[];\n}\n\n/** `Resource` (generated from openapi.json). */\nexport interface Resource {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /** `metadata`. */\n metadata: unknown;\n /** `name`. */\n name: string;\n /**\n * Parent resource ID for hierarchical organization. `None` for root\n * resources.\n */\n parent_id?: string | null;\n /** The type of resource (e.g., `project`, `service`, `endpoint`). */\n resource_type: string;\n /** `tenant_id`. */\n tenant_id: string;\n /**\n * The `client_id` that registered this resource through the UMA Protection\n * API (X2), or `None` for a resource created any other way.\n *\n * Read-only from every ordinary path: [`UpdateResource`] cannot set it and\n * [`CreateResource`] cannot either, so the only writer is the\n * resource-registration handler. That is deliberate — the field backs a\n * provenance badge in the admin UI, and a provenance marker anyone can write\n * is decoration that reads like evidence.\n */\n uma_registered_by?: string | null;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Retry policy for failed webhook deliveries. */\nexport interface RetryPolicy {\n /** Multiplier for exponential backoff. */\n backoff_multiplier: number;\n /** Initial delay between retries in seconds. */\n initial_delay_secs: number;\n /** Maximum number of retry attempts. */\n max_retries: number;\n}\n\n/** `Role` (generated from openapi.json). */\nexport interface Role {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** Global roles grant permissions across all resources. */\n is_global: boolean;\n /** `name`. */\n name: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * A role together with its assignment context (the resource it is scoped\n * to).\n */\nexport interface RoleAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /** `role`. */\n role: Role;\n /** The tenants this assignment reaches. See [`TenantScope`]. */\n tenant_scope?: string[] | null;\n}\n\n/** A group together with the resource scope of its assignment of this role. */\nexport interface RoleGroupAssignment {\n /** The assigned group. */\n group: Group;\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n}\n\n/** A service account together with the resource scope of its assignment. */\nexport interface RoleServiceAccountAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The assigned service account. Carries no secret — the client secret is\n * returned once, at creation, and never again.\n */\n service_account: ServiceAccountResponse;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n}\n\n/** A user together with the resource scope of their assignment of this role. */\nexport interface RoleUserAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n /** The assigned user. */\n user: UserResponse;\n}\n\n/** Response for secret rotation. */\nexport interface RotateSecretResponse {\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n}\n\n/**\n * Wire twin of {@link RotateSecretResponse} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface RotateSecretResponseWire {\n client_secret: string;\n}\n\n/** Wrap the secret fields a `RotateSecretResponse` response carries (§27.5). */\nexport function rotateSecretResponseFromWire(w: RotateSecretResponseWire): RotateSecretResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/**\n * Metadata only. The handle is never in a list response — it exists in\n * plaintext exactly once, in [`CreateScimTokenResponse`].\n */\nexport interface ScimTokenResponse {\n /** `created_at`. */\n created_at: string;\n /** `created_by`. */\n created_by: string;\n /** `expires_at`. */\n expires_at: string;\n /** `id`. */\n id: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `name`. */\n name: string;\n /** `revoked_at`. */\n revoked_at?: string | null;\n /** `status`. */\n status: ScimTokenStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Why a token is or is not currently usable — for display only. The\n * authentication path never surfaces this distinction on the wire.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ScimTokenStatus =\n | \"active\"\n | \"expired\"\n | \"revoked\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `Scope` (generated from openapi.json). */\nexport interface Scope {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** The resource this scope belongs to. */\n resource_id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Fully resolved security settings (all fields present). */\nexport interface SecuritySettings {\n /** `certificate`. */\n certificate: CertificatePolicy;\n /** `created_at`. */\n created_at: string;\n /** `email`. */\n email: EmailVerificationPolicy;\n /** `id`. */\n id: string;\n /** `lockout`. */\n lockout: LockoutPolicy;\n /** `mfa`. */\n mfa: MfaPolicy;\n /** `notification`. */\n notification: NotificationPolicy;\n /** `oidc`. */\n oidc: OidcPolicy;\n /** `opaque`. */\n opaque: OpaquePolicy;\n /** `password`. */\n password: PasswordPolicy;\n /** `privacy`. */\n privacy: PrivacyPolicy;\n /** `scope`. */\n scope: SettingsScope;\n /** `scope_id`. */\n scope_id: string;\n /** `token`. */\n token: TokenPolicy;\n /** `updated_at`. */\n updated_at: string;\n /** `webauthn`. */\n webauthn: WebauthnPolicy;\n}\n\n/**\n * Response for service account creation — includes the one-time plaintext\n * secret.\n */\nexport interface ServiceAccountCreatedResponse {\n /** `client_id`. */\n client_id: string;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description?: string | null;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Wire twin of {@link ServiceAccountCreatedResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface ServiceAccountCreatedResponseWire {\n client_id: string;\n client_secret: string;\n created_at: string;\n description?: string | null;\n id: string;\n name: string;\n status: UserStatus;\n tenant_id: string;\n updated_at: string;\n}\n\n/**\n * Wrap the secret fields a `ServiceAccountCreatedResponse` response carries\n * (§27.5).\n */\nexport function serviceAccountCreatedResponseFromWire(w: ServiceAccountCreatedResponseWire): ServiceAccountCreatedResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/** Public-safe service account representation. */\nexport interface ServiceAccountResponse {\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description?: string | null;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Body for `PUT .../ca-certificates/{id}/mtls-trust-anchor`. */\nexport interface SetMtlsTrustAnchor {\n /** Whether this CA should be trusted for client-certificate authentication. */\n enabled: boolean;\n}\n\n/** Input for setting organization-level email config. */\nexport interface SetOrgEmailConfig {\n /** `enabled`. */\n enabled: boolean;\n /** `from_email`. */\n from_email: string;\n /** `from_name`. */\n from_name: string;\n /** `provider`. */\n provider: ProviderConfig;\n /** `reply_to`. */\n reply_to?: string | null;\n}\n\n/** Input for setting organization-level security settings. */\nexport interface SetOrgSettings {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs: number;\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled: boolean;\n /** `default_cert_validity_days`. */\n default_cert_validity_days: number;\n /** `default_locale`. */\n default_locale?: string | null;\n /** `deletion_grace_period_days`. */\n deletion_grace_period_days?: number;\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours: number;\n /** `email_verification_required`. */\n email_verification_required: boolean;\n /** `hibp_check_enabled`. */\n hibp_check_enabled: boolean;\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier: number;\n /** `lockout_duration_secs`. */\n lockout_duration_secs: number;\n /** `max_cert_validity_days`. */\n max_cert_validity_days: number;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts: number;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs: number;\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs: number;\n /** `mfa_enforced`. */\n mfa_enforced: boolean;\n /** `min_length`. */\n min_length: number;\n /** `opaque_ksf`. */\n opaque_ksf?: string;\n /** `opaque_mode`. */\n opaque_mode?: string;\n /** `opaque_suite`. */\n opaque_suite?: string;\n /** `password_history_count`. */\n password_history_count: number;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs: number;\n /** `require_digits`. */\n require_digits: boolean;\n /** `require_lowercase`. */\n require_lowercase: boolean;\n /** `require_symbols`. */\n require_symbols: boolean;\n /** `require_uppercase`. */\n require_uppercase: boolean;\n /** `sensitive_scopes_enabled`. */\n sensitive_scopes_enabled?: boolean;\n /** `webauthn_user_verification`. */\n webauthn_user_verification?: string;\n}\n\n/**\n * Whether a settings row belongs to an organization or a tenant.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type SettingsScope =\n | \"Org\"\n | \"Tenant\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Request body for signing an audit batch. */\nexport interface SignAuditBatchRequest {\n /** `entry_ids`. */\n entry_ids: string[];\n}\n\n/**\n * Body of `POST .../tenants/{tenant_id}/signing-cas/sign-csr`.\n *\n * Deliberately carries no key algorithm: it is the CSR's, read out of the\n * request, because a caller who could state it separately could state one\n * the key does not have.\n */\nexport interface SignIntermediateCsrRequest {\n /** PEM-encoded PKCS#10 certificate signing request. */\n csr_pem: string;\n /** The organization CA that signs it. */\n parent_ca_id: string;\n /** Validity duration in days, capped to the parent's own expiry. */\n validity_days: number;\n}\n\n/** A signed batch of audit log entries. */\nexport interface SignedAuditBatch {\n /** `batch_id`. */\n batch_id: string;\n /** `entry_ids`. */\n entry_ids: string[];\n /** ASCII-armored PGP signed message containing the audit batch payload. */\n signature_armored: string;\n /** `signed_at`. */\n signed_at: string;\n /** `signing_key_id`. */\n signing_key_id: string;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * SMTP-specific configuration.\n *\n * `password` is write-only (D-01): `#[serde(skip_serializing)]` means it is\n * never emitted in a GET/serialized response. On the write path (D-02),\n * `#[serde(default)]` lets a caller omit the field entirely (deserializing\n * to `\"\"`); an empty string is the sentinel for \"no new secret supplied —\n * preserve whatever is already stored\" (see `SurrealEmailConfigRepository::\n * set_org_config`). A non-empty value is a real secret to encrypt+replace.\n */\nexport interface SmtpConfig {\n /** `host`. */\n host: string;\n /** `port`. */\n port: number;\n /** Use STARTTLS (true) or implicit TLS (false). */\n starttls: boolean;\n /** `username`. */\n username: string;\n}\n\n/**\n * A tenant is an isolated context within an organization.\n *\n * Each tenant has its own set of users, roles, permissions, resources,\n * certificates, and configuration. Tenants can represent environments\n * (dev/staging/prod) or separate business contexts.\n */\nexport interface Tenant {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /**\n * Whether this is an ordinary tenant or the organization's own scope.\n *\n * `#[serde(default)]` so every row written before organization scope existed\n * reads back as [`TenantKind::Standard`], which is what it is.\n */\n kind?: TenantKind;\n /** Arbitrary key-value metadata. */\n metadata: unknown;\n /** Human-readable name. */\n name: string;\n /** The organization this tenant belongs to. */\n organization_id: string;\n /** URL-safe unique identifier within the organization (e.g., `production`). */\n slug: string;\n /** Lifecycle status. New tenants default to [`TenantStatus::Active`]. */\n status: TenantStatus;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * What a tenant *is*, as distinct from what state it is in.\n *\n * Reserved rather than inferred: an organization has exactly one tenant of\n * kind [`Self::Organization`], enforced by a unique index rather than by\n * convention. Deriving it from a magic slug or from \"the oldest tenant\"\n * would make the organization scope something an operator could rename or\n * delete by accident, and it is the scope the super-admin lives in.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type TenantKind =\n | \"standard\"\n | \"organization\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Partial tenant overrides. `None` = inherit from org baseline.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface TenantSettingsOverride {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs?: number | null;\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled?: boolean | null;\n /** `default_cert_validity_days`. */\n default_cert_validity_days?: number | null;\n /**\n * The tenant's fallback UI language. Not ordered, therefore not validated\n * against the baseline and never clamped — see [`OidcPolicy`].\n */\n default_locale?: string | null;\n /** `deletion_grace_period_days`. */\n deletion_grace_period_days?: number | null;\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours?: number | null;\n /** `email_verification_required`. */\n email_verification_required?: boolean | null;\n /** `hibp_check_enabled`. */\n hibp_check_enabled?: boolean | null;\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier?: number | null;\n /** `lockout_duration_secs`. */\n lockout_duration_secs?: number | null;\n /** `max_cert_validity_days`. */\n max_cert_validity_days?: number | null;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts?: number | null;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs?: number | null;\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs?: number | null;\n /** `mfa_enforced`. */\n mfa_enforced?: boolean | null;\n /** `min_length`. */\n min_length?: number | null;\n /** `opaque_ksf`. */\n opaque_ksf?: string | null;\n /** `opaque_mode`. */\n opaque_mode?: string | null;\n /** `opaque_suite`. */\n opaque_suite?: string | null;\n /** `password_history_count`. */\n password_history_count?: number | null;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs?: number | null;\n /** `require_digits`. */\n require_digits?: boolean | null;\n /** `require_lowercase`. */\n require_lowercase?: boolean | null;\n /** `require_symbols`. */\n require_symbols?: boolean | null;\n /** `require_uppercase`. */\n require_uppercase?: boolean | null;\n /** `sensitive_scopes_enabled`. */\n sensitive_scopes_enabled?: boolean | null;\n /** `webauthn_user_verification`. */\n webauthn_user_verification?: string | null;\n}\n\n/**\n * Lifecycle status of a tenant.\n *\n * A `Suspended` tenant remains stored and its data isolated, but is treated\n * as administratively disabled. New tenants are `Active` by default.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type TenantStatus =\n | \"Active\"\n | \"Suspended\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * X4 trust for exchanging this provider's tokens (RFC 8693, external\n * issuer).\n *\n * Mirrors [`TokenExchangeTrust`] on the wire rather than reusing it directly\n * so the API surface can carry its own defaults: an admin PUTting a partial\n * block gets the documented default for anything they omitted, instead of a\n * deserialization error listing fields they have never heard of.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface TokenExchangeTrustRequest {\n /**\n * Audiences an incoming subject token may name. Required (non-empty) when\n * `enabled`; there is deliberately no accept-all value.\n */\n accepted_audiences?: string[];\n /**\n * Off unless explicitly enabled. Configuring a provider for *login* is not\n * agreement to accept its tokens as API credentials.\n */\n enabled?: boolean;\n /** Per-provider ceiling on the issued AXIAM token's lifetime. */\n max_lifetime_secs?: number | null;\n /** Bound on `now - iat`, independent of the token's own `exp`. */\n max_token_age_secs?: number | null;\n /**\n * External asserted value -> AXIAM scopes. Deny-by-default: an external\n * value with no entry contributes nothing.\n */\n scope_map?: Record<string, unknown>;\n /** `linked_only` (default) or `jit_provision`. */\n subject_mapping?: string | null;\n}\n\n/**\n * X4 trust as returned. Same shape as the request; nothing here is secret —\n * an operator reading a provider needs to see exactly what it trusts.\n */\nexport interface TokenExchangeTrustResponse {\n /** `accepted_audiences`. */\n accepted_audiences: string[];\n /** `enabled`. */\n enabled: boolean;\n /** `max_lifetime_secs`. */\n max_lifetime_secs?: number | null;\n /** `max_token_age_secs`. */\n max_token_age_secs: number;\n /** `scope_map`. */\n scope_map: Record<string, unknown>;\n /** `subject_mapping`. */\n subject_mapping: string;\n}\n\n/** Token lifetime configuration. */\nexport interface TokenPolicy {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs: number;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs: number;\n}\n\n/**\n * What to do with an AAGUID that has no MDS entry (i.e. FIDO Alliance has no\n * metadata for it — not necessarily malicious, MDS coverage is incomplete\n * for some legitimate authenticators).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type UnknownAaguidAction =\n | \"allow\"\n | \"deny\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * `UpdateFederationConfigRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateFederationConfigRequest {\n /** Whether tenants may inherit this organization-level provider. */\n allow_tenant_inheritance?: boolean | null;\n /** Accepted signature algorithms (CQ-B40/REQ-14 AC-5). */\n allowed_algorithms?: string[] | null;\n /** Accepted external IdP tenants for a templated issuer. Replaced wholesale. */\n allowed_issuer_tenants?: string[] | null;\n /** Apple Key ID. `Some(None)` clears it. */\n apple_key_id?: string | null;\n /** Apple Team ID. `Some(None)` clears it. */\n apple_team_id?: string | null;\n /** `attribute_map`. */\n attribute_map?: unknown;\n /** OAuth2-variant authorization endpoint. `Some(None)` clears it. */\n authorization_endpoint?: string | null;\n /** Sign-in-button icon for a generic provider. `Some(None)` clears it. */\n button_icon?: string | null;\n /** `client_id`. */\n client_id?: string | null;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret?: Sensitive<string>;\n /** `enabled`. */\n enabled?: boolean | null;\n /**\n * PEM-encoded X.509 certificate for verifying SAML assertions (CQ-B40/REQ-14\n * AC-5). `Some(None)` clears the stored cert.\n */\n idp_signing_cert_pem?: string | null;\n /** `metadata_url`. */\n metadata_url?: string | null;\n /** `provider`. */\n provider?: string | null;\n /** Operator-chosen identifier for a `generic_*` kind. `Some(None)` clears it. */\n provider_slug?: string | null;\n /** Send PKCE on the authorization request. */\n require_pkce?: boolean | null;\n /**\n * Scopes to request. Replaced wholesale; empty restores the per-kind\n * default.\n */\n scopes?: string[] | null;\n /** OAuth2-variant token endpoint. `Some(None)` clears it. */\n token_endpoint?: string | null;\n /** `token_exchange`. */\n token_exchange?: TokenExchangeTrustRequest | null;\n /** OAuth2-variant userinfo endpoint. `Some(None)` clears it. */\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Wire twin of {@link UpdateFederationConfigRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface UpdateFederationConfigRequestWire {\n allow_tenant_inheritance?: boolean | null;\n allowed_algorithms?: string[] | null;\n allowed_issuer_tenants?: string[] | null;\n apple_key_id?: string | null;\n apple_team_id?: string | null;\n attribute_map?: unknown;\n authorization_endpoint?: string | null;\n button_icon?: string | null;\n client_id?: string | null;\n client_secret?: string;\n enabled?: boolean | null;\n idp_signing_cert_pem?: string | null;\n metadata_url?: string | null;\n provider?: string | null;\n provider_slug?: string | null;\n require_pkce?: boolean | null;\n scopes?: string[] | null;\n token_endpoint?: string | null;\n token_exchange?: TokenExchangeTrustRequest | null;\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Unwrap a `UpdateFederationConfigRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function updateFederationConfigRequestToWire(v: UpdateFederationConfigRequest): UpdateFederationConfigRequestWire {\n return {\n ...v,\n client_secret: v.client_secret === undefined ? undefined : v.client_secret.expose(),\n };\n}\n\n/**\n * `UpdateGroup` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateGroup {\n /** `description`. */\n description?: string | null;\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateNotificationRuleRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateNotificationRuleRequest {\n /** `description`. */\n description?: string | null;\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: NotificationEventType[] | null;\n /** `name`. */\n name?: string | null;\n /** `recipient_emails`. */\n recipient_emails?: string[] | null;\n}\n\n/**\n * `UpdateOAuth2ClientRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateOAuth2ClientRequest {\n /** `authn_request_params`. */\n authn_request_params?: AuthnRequestParamsMode | null;\n /**\n * Pass an empty string to clear a previously registered URI — the one edit\n * an operator makes when an RP is decommissioned.\n */\n backchannel_logout_uri?: string | null;\n /** X7.3 — see [`CreateOAuth2ClientRequest::browser_sso`]. */\n browser_sso?: boolean | null;\n /** `dpop_bound_access_tokens`. */\n dpop_bound_access_tokens?: boolean | null;\n /** `dpop_require_nonce`. */\n dpop_require_nonce?: boolean | null;\n /** `grant_types`. */\n grant_types?: string[] | null;\n /**\n * X5.1 — see the create DTO. `Some(\"\")` clears, so a client can be migrated\n * from an inline key set to a published one.\n */\n jwks?: string | null;\n /** X5.1 — see the create DTO. `Some(\"\")` clears. */\n jwks_uri?: string | null;\n /** `name`. */\n name?: string | null;\n /** `post_logout_redirect_uris`. */\n post_logout_redirect_uris?: string[] | null;\n /** `profile`. */\n profile?: ClientProfile | null;\n /** `redirect_uris`. */\n redirect_uris?: string[] | null;\n /** `require_par`. */\n require_par?: boolean | null;\n /** `scopes`. */\n scopes?: string[] | null;\n /** `self_signed_tls_client_auth_thumbprints`. */\n self_signed_tls_client_auth_thumbprints?: string[] | null;\n /** `tls_client_auth_san_dns`. */\n tls_client_auth_san_dns?: string | null;\n /** `tls_client_auth_san_uri`. */\n tls_client_auth_san_uri?: string | null;\n /** Pass an empty string to clear, as with `backchannel_logout_uri`. */\n tls_client_auth_subject_dn?: string | null;\n /** `tls_client_certificate_bound_access_tokens`. */\n tls_client_certificate_bound_access_tokens?: boolean | null;\n /** `token_endpoint_auth_method`. */\n token_endpoint_auth_method?: ClientAuthMethod | null;\n}\n\n/**\n * `UpdateOrganizationRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateOrganizationRequest {\n /** Free-form metadata (the admin UI stores `description` here). */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `slug`. */\n slug?: string | null;\n}\n\n/**\n * `UpdatePermissionRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdatePermissionRequest {\n /** `action`. */\n action?: string | null;\n /** `description`. */\n description?: string | null;\n}\n\n/**\n * `UpdateReactorRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateReactorRequest {\n /** `description`. */\n description?: string | null;\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: string[] | null;\n /** `failure_policy`. */\n failure_policy?: FailurePolicy | null;\n /** `mode`. */\n mode?: ReactorMode | null;\n /** `name`. */\n name?: string | null;\n /** `priority`. */\n priority?: number | null;\n /** `timeout_ms`. */\n timeout_ms?: number | null;\n}\n\n/**\n * `UpdateResourceRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateResourceRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `parent_id`. */\n parent_id?: string | null;\n /** `resource_type`. */\n resource_type?: string | null;\n}\n\n/**\n * `UpdateRole` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateRole {\n /** `description`. */\n description?: string | null;\n /** `is_global`. */\n is_global?: boolean | null;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateScopeRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateScopeRequest {\n /** `description`. */\n description?: string | null;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateServiceAccount` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateServiceAccount {\n /** `description`. */\n description?: string | null;\n /** `name`. */\n name?: string | null;\n /** `status`. */\n status?: UserStatus | null;\n}\n\n/**\n * Fields that can be updated on an existing tenant.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateTenant {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `slug`. */\n slug?: string | null;\n /** `status`. */\n status?: TenantStatus | null;\n}\n\n/**\n * `UpdateUserRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateUserRequest {\n /** `email`. */\n email?: string | null;\n /** `metadata`. */\n metadata?: unknown;\n /** `status`. */\n status?: UserStatus | null;\n /** `username`. */\n username?: string | null;\n}\n\n/**\n * `UpdateWebhookRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateWebhookRequest {\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: string[] | null;\n /** `retry_policy`. */\n retry_policy?: RetryPolicy | null;\n /**\n * New HMAC-SHA256 shared secret (D-02 secret rotation). Encrypted\n * server-side with AES-256-GCM before storage; omit to leave the existing\n * secret untouched.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n secret?: Sensitive<string>;\n /** `url`. */\n url?: string | null;\n}\n\n/**\n * Wire twin of {@link UpdateWebhookRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface UpdateWebhookRequestWire {\n enabled?: boolean | null;\n events?: string[] | null;\n retry_policy?: RetryPolicy | null;\n secret?: string;\n url?: string | null;\n}\n\n/**\n * Unwrap a `UpdateWebhookRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function updateWebhookRequestToWire(v: UpdateWebhookRequest): UpdateWebhookRequestWire {\n return {\n ...v,\n secret: v.secret === undefined ? undefined : v.secret.expose(),\n };\n}\n\n/** Public-safe user representation (no password_hash, no mfa_secret). */\nexport interface UserResponse {\n /** `created_at`. */\n created_at: string;\n /** `email`. */\n email: string;\n /**\n * True when the user's email address has been verified (`email_verified_at`\n * is set). Exposed for the admin UI / profile.\n */\n email_verified: boolean;\n /** Number of consecutive failed login attempts. */\n failed_login_attempts: number;\n /** `id`. */\n id: string;\n /** Whether the account is currently locked (locked_until is in the future). */\n is_locked: boolean;\n /** Timestamp until which the account is locked, if any. */\n locked_until?: string | null;\n /** `metadata`. */\n metadata: unknown;\n /** `mfa_enabled`. */\n mfa_enabled: boolean;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `username`. */\n username: string;\n}\n\n/**\n * `UserStatus` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type UserStatus =\n | \"Active\"\n | \"Inactive\"\n | \"Locked\"\n | \"PendingVerification\"\n | \"Anonymized\"\n | \"Deleted\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Per-tenant WebAuthn attestation policy (D5). One row per tenant; an absent\n * row means [`WebauthnAttestationPolicy::default`], which is today's\n * behavior unchanged.\n */\nexport interface WebauthnAttestationPolicy {\n /**\n * `None` = every AAGUID is allowed except `blocked_aaguids`.\n *\n * `Some(vec![])` is a deliberate \"nothing may register\" policy and is\n * accepted as such: `evaluate` denies every AAGUID against an empty\n * allow-list. Nothing rejects it, precisely because the failure direction is\n * safe — a client that sends `[]` when it meant `null` gets a locked-down\n * tenant, which is visible immediately, rather than an open one, which is\n * not.\n */\n allowed_aaguids?: string[] | null;\n /**\n * Deny registration if the MDS entry has ever reported `REVOKED` or any\n * `*_COMPROMISE` status (sticky — D8 step 7).\n */\n block_revoked_status: boolean;\n /** `blocked_aaguids`. */\n blocked_aaguids?: string[];\n /** `min_certification`. */\n min_certification?: CertificationLevel | null;\n /** `mode`. */\n mode: AttestationMode;\n /**\n * Require *some* `FIDO_CERTIFIED*` status, any level. Independent of (and\n * checked before) `min_certification`.\n */\n require_fido_certified: boolean;\n /** `unknown_aaguid`. */\n unknown_aaguid?: UnknownAaguidAction | null;\n}\n\n/**\n * WebAuthn ceremony policy.\n *\n * One field today. It is a struct rather than a bare field on\n * [`SecuritySettings`] so that the next WebAuthn control has an obvious\n * home, and so the admin UI can group them.\n *\n * The *attestation* policy is deliberately not here: it lives in\n * [`crate::models::webauthn_policy::WebauthnAttestationPolicy`], is\n * tenant-only, and cannot join this model because AAGUID allow/block lists\n * have no \"more restrictive than\" ordering to validate an override against.\n * User verification does, so it can.\n */\nexport interface WebauthnPolicy {\n /**\n * How hard the authenticator must prove *who* is present.\n *\n * Applies to enrolment and to second-factor authentication. Usernameless\n * sign-in is held to `required` whatever this says — see\n * [`WebauthnUserVerification`].\n */\n webauthn_user_verification: string;\n}\n\n/** Webhook response — omits the shared secret. */\nexport interface WebhookResponse {\n /** `created_at`. */\n created_at: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: string[];\n /** `id`. */\n id: string;\n /** `retry_policy`. */\n retry_policy: RetryPolicy;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `url`. */\n url: string;\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `users` management namespace (CONTRACT §27.1).\n *\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `users` namespace handle.\n *\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class UsersApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/users` */\n async list(page: PageRequest = {}): Promise<Page<models.UserResponse>> {\n const wire = await sendManagement<Page<models.UserResponse>>(this.#client, {\n operation: 'users.list',\n method: 'GET',\n pathTemplate: '/api/v1/users',\n path: '/api/v1/users',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `users.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.UserResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/users`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateUserRequest): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.create',\n method: 'POST',\n pathTemplate: '/api/v1/users',\n path: '/api/v1/users',\n body: models.createUserRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/users/{user_id}` */\n async get(userId: string): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.get',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(userId: string, body: models.UpdateUserRequest): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.update',\n method: 'PUT',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n });\n }\n\n /** `GET /api/v1/users/{user_id}/mfa-methods` */\n async listMfaMethods(userId: string): Promise<models.MfaMethodResponse[]> {\n const wire = await sendManagement<models.MfaMethodResponse[]>(this.#client, {\n operation: 'users.list_mfa_methods',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}/mfa-methods',\n path: `/api/v1/users/${encodeURIComponent(userId)}/mfa-methods`,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/users/{user_id}/mfa-methods/{method_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteMfaMethod(userId: string, methodId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.delete_mfa_method',\n method: 'DELETE',\n pathTemplate: '/api/v1/users/{user_id}/mfa-methods/{method_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}/mfa-methods/${encodeURIComponent(methodId)}`,\n });\n }\n\n /**\n * `POST /api/v1/users/{user_id}/reset-mfa`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async resetMfa(userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.reset_mfa',\n method: 'POST',\n pathTemplate: '/api/v1/users/{user_id}/reset-mfa',\n path: `/api/v1/users/${encodeURIComponent(userId)}/reset-mfa`,\n });\n }\n\n /**\n * `POST /api/v1/users/{user_id}/unlock`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unlock(userId: string): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.unlock',\n method: 'POST',\n pathTemplate: '/api/v1/users/{user_id}/unlock',\n path: `/api/v1/users/${encodeURIComponent(userId)}/unlock`,\n });\n return wire;\n }\n\n /** `GET /api/v1/users/{user_id}/roles` */\n async listRoles(userId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'users.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}/roles',\n path: `/api/v1/users/${encodeURIComponent(userId)}/roles`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `groups` management namespace (CONTRACT §27.1).\n *\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `groups` namespace handle.\n *\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class GroupsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/groups` */\n async list(page: PageRequest = {}): Promise<Page<models.Group>> {\n const wire = await sendManagement<Page<models.Group>>(this.#client, {\n operation: 'groups.list',\n method: 'GET',\n pathTemplate: '/api/v1/groups',\n path: '/api/v1/groups',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Group[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/groups`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateGroupRequest): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.create',\n method: 'POST',\n pathTemplate: '/api/v1/groups',\n path: '/api/v1/groups',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/groups/{group_id}` */\n async get(groupId: string): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.get',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(groupId: string, body: models.UpdateGroup): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.update',\n method: 'PUT',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(groupId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n });\n }\n\n /** `GET /api/v1/groups/{group_id}/members` */\n async listMembers(groupId: string, page: PageRequest = {}): Promise<Page<models.UserResponse>> {\n const wire = await sendManagement<Page<models.UserResponse>>(this.#client, {\n operation: 'groups.list_members',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/members',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list_members` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listMembersAll(groupId: string, start: PageRequest = {}): Promise<models.UserResponse[]> {\n return collectPages(start, (p) => this.listMembers(groupId, p));\n }\n\n /**\n * `POST /api/v1/groups/{group_id}/members`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async addMember(groupId: string, body: models.AddMemberRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.add_member',\n method: 'POST',\n pathTemplate: '/api/v1/groups/{group_id}/members',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}/members/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async removeMember(groupId: string, userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.remove_member',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}/members/{user_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(userId)}`,\n });\n }\n\n /** `GET /api/v1/groups/{group_id}/roles` */\n async listRoles(groupId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'groups.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/roles',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/roles`,\n });\n return wire;\n }\n\n /** `GET /api/v1/groups/{group_id}/service-accounts` */\n async listServiceAccounts(groupId: string, page: PageRequest = {}): Promise<Page<models.ServiceAccountResponse>> {\n const wire = await sendManagement<Page<models.ServiceAccountResponse>>(this.#client, {\n operation: 'groups.list_service_accounts',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list_service_accounts` to exhaustion, concatenating every\n * page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listServiceAccountsAll(groupId: string, start: PageRequest = {}): Promise<models.ServiceAccountResponse[]> {\n return collectPages(start, (p) => this.listServiceAccounts(groupId, p));\n }\n\n /**\n * `POST /api/v1/groups/{group_id}/service-accounts`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async addServiceAccount(groupId: string, body: models.AddServiceAccountMemberRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.add_service_account',\n method: 'POST',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}/service-accounts/{service_account_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async removeServiceAccount(groupId: string, serviceAccountId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.remove_service_account',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts/{service_account_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts/${encodeURIComponent(serviceAccountId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `roles` management namespace (CONTRACT §27.1).\n *\n * Roles, their permission sets, and their assignment to users and groups.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `roles` namespace handle.\n *\n * Roles, their permission sets, and their assignment to users and groups.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class RolesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/roles` */\n async list(page: PageRequest = {}): Promise<Page<models.Role>> {\n const wire = await sendManagement<Page<models.Role>>(this.#client, {\n operation: 'roles.list',\n method: 'GET',\n pathTemplate: '/api/v1/roles',\n path: '/api/v1/roles',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `roles.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Role[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/roles`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateRoleRequest): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.create',\n method: 'POST',\n pathTemplate: '/api/v1/roles',\n path: '/api/v1/roles',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/roles/{role_id}` */\n async get(roleId: string): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.get',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/roles/{role_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(roleId: string, body: models.UpdateRole): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.update',\n method: 'PUT',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(roleId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/users` */\n async listUsers(roleId: string): Promise<models.RoleUserAssignment[]> {\n const wire = await sendManagement<models.RoleUserAssignment[]>(this.#client, {\n operation: 'roles.list_users',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/users',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/users`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToUser(roleId: string, body: models.AssignRoleToUserRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_user',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/users',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromUser(roleId: string, userId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_user',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/users/{user_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users/${encodeURIComponent(userId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/groups` */\n async listGroups(roleId: string): Promise<models.RoleGroupAssignment[]> {\n const wire = await sendManagement<models.RoleGroupAssignment[]>(this.#client, {\n operation: 'roles.list_groups',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/groups',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/groups`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToGroup(roleId: string, body: models.AssignRoleToGroupRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_group',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/groups',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromGroup(roleId: string, groupId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_group',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/groups/{group_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups/${encodeURIComponent(groupId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/permissions` */\n async listPermissions(roleId: string): Promise<models.ResolvedPermissionGrant[]> {\n const wire = await sendManagement<models.ResolvedPermissionGrant[]>(this.#client, {\n operation: 'roles.list_permissions',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/permissions',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/permissions`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async grantPermission(roleId: string, body: models.GrantPermissionRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.grant_permission',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/permissions',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revokePermission(roleId: string, permissionId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.revoke_permission',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/permissions/{permission_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions/${encodeURIComponent(permissionId)}`,\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/service-accounts` */\n async listServiceAccounts(roleId: string): Promise<models.RoleServiceAccountAssignment[]> {\n const wire = await sendManagement<models.RoleServiceAccountAssignment[]>(this.#client, {\n operation: 'roles.list_service_accounts',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/service-accounts`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToServiceAccount(roleId: string, body: models.AssignRoleToServiceAccountRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_service_account',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/service-accounts/{service_account_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromServiceAccount(roleId: string, serviceAccountId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_service_account',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts/{service_account_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts/${encodeURIComponent(serviceAccountId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `permissions` management namespace (CONTRACT §27.1).\n *\n * Permissions -- an action on a resource, optionally narrowed by a scope.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `permissions` namespace handle.\n *\n * Permissions -- an action on a resource, optionally narrowed by a scope.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PermissionsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/permissions` */\n async list(page: PageRequest = {}): Promise<Page<models.Permission>> {\n const wire = await sendManagement<Page<models.Permission>>(this.#client, {\n operation: 'permissions.list',\n method: 'GET',\n pathTemplate: '/api/v1/permissions',\n path: '/api/v1/permissions',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `permissions.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Permission[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/permissions`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreatePermissionRequest): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.create',\n method: 'POST',\n pathTemplate: '/api/v1/permissions',\n path: '/api/v1/permissions',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/permissions/{permission_id}` */\n async get(permissionId: string): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.get',\n method: 'GET',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(permissionId: string, body: models.UpdatePermissionRequest): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.update',\n method: 'PUT',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(permissionId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'permissions.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `resources` management namespace (CONTRACT §27.1).\n *\n * The resource hierarchy role assignments cascade down.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `resources` namespace handle.\n *\n * The resource hierarchy role assignments cascade down.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ResourcesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/resources` */\n async list(page: PageRequest = {}): Promise<Page<models.Resource>> {\n const wire = await sendManagement<Page<models.Resource>>(this.#client, {\n operation: 'resources.list',\n method: 'GET',\n pathTemplate: '/api/v1/resources',\n path: '/api/v1/resources',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `resources.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Resource[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/resources`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateResourceRequest): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.create',\n method: 'POST',\n pathTemplate: '/api/v1/resources',\n path: '/api/v1/resources',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}` */\n async get(resourceId: string): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.get',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/resources/{resource_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(resourceId: string, body: models.UpdateResourceRequest): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.update',\n method: 'PUT',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/resources/{resource_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(resourceId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'resources.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n });\n }\n\n /** `GET /api/v1/resources/{resource_id}/children` */\n async listChildren(resourceId: string): Promise<models.Resource[]> {\n const wire = await sendManagement<models.Resource[]>(this.#client, {\n operation: 'resources.list_children',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/children',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/children`,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}/ancestors` */\n async listAncestors(resourceId: string): Promise<models.Resource[]> {\n const wire = await sendManagement<models.Resource[]>(this.#client, {\n operation: 'resources.list_ancestors',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/ancestors',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/ancestors`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `scopes` management namespace (CONTRACT §27.1).\n *\n * Sub-resource granularity, always addressed under their resource.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `scopes` namespace handle.\n *\n * Sub-resource granularity, always addressed under their resource.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ScopesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/resources/{resource_id}/scopes` */\n async list(resourceId: string): Promise<models.Scope[]> {\n const wire = await sendManagement<models.Scope[]>(this.#client, {\n operation: 'scopes.list',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/resources/{resource_id}/scopes`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(resourceId: string, body: models.CreateScopeRequest): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.create',\n method: 'POST',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}/scopes/{scope_id}` */\n async get(resourceId: string, scopeId: string): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.get',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/resources/{resource_id}/scopes/{scope_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(resourceId: string, scopeId: string, body: models.UpdateScopeRequest): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.update',\n method: 'PUT',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/resources/{resource_id}/scopes/{scope_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(resourceId: string, scopeId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'scopes.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `service_accounts` management namespace (CONTRACT §27.1).\n *\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `service_accounts` namespace handle.\n *\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ServiceAccountsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/service-accounts` */\n async list(page: PageRequest = {}): Promise<Page<models.ServiceAccountResponse>> {\n const wire = await sendManagement<Page<models.ServiceAccountResponse>>(this.#client, {\n operation: 'service_accounts.list',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts',\n path: '/api/v1/service-accounts',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `service_accounts.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.ServiceAccountResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/service-accounts`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateServiceAccountRequest): Promise<models.ServiceAccountCreatedResponse> {\n const wire = await sendManagement<models.ServiceAccountCreatedResponseWire>(this.#client, {\n operation: 'service_accounts.create',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts',\n path: '/api/v1/service-accounts',\n body: body,\n });\n return models.serviceAccountCreatedResponseFromWire(wire);\n }\n\n /** `GET /api/v1/service-accounts/{sa_id}` */\n async get(saId: string): Promise<models.ServiceAccountResponse> {\n const wire = await sendManagement<models.ServiceAccountResponse>(this.#client, {\n operation: 'service_accounts.get',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/service-accounts/{sa_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(saId: string, body: models.UpdateServiceAccount): Promise<models.ServiceAccountResponse> {\n const wire = await sendManagement<models.ServiceAccountResponse>(this.#client, {\n operation: 'service_accounts.update',\n method: 'PUT',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/service-accounts/{sa_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(saId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'service_accounts.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n });\n }\n\n /**\n * `POST /api/v1/service-accounts/{sa_id}/rotate-secret`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async rotateSecret(saId: string): Promise<models.RotateSecretResponse> {\n const wire = await sendManagement<models.RotateSecretResponseWire>(this.#client, {\n operation: 'service_accounts.rotate_secret',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts/{sa_id}/rotate-secret',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}/rotate-secret`,\n });\n return models.rotateSecretResponseFromWire(wire);\n }\n\n /**\n * `POST /api/v1/service-accounts/{sa_id}/bind-certificate`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async bindCertificate(saId: string, body: models.BindCertificate): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'service_accounts.bind_certificate',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts/{sa_id}/bind-certificate',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}/bind-certificate`,\n body: body,\n });\n }\n\n /** `GET /api/v1/service-accounts/{service_account_id}/roles` */\n async listRoles(serviceAccountId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'service_accounts.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{service_account_id}/roles',\n path: `/api/v1/service-accounts/${encodeURIComponent(serviceAccountId)}/roles`,\n });\n return wire;\n }\n\n /** `GET /api/v1/service-accounts/{service_account_id}/groups` */\n async listGroups(serviceAccountId: string): Promise<models.Group[]> {\n const wire = await sendManagement<models.Group[]>(this.#client, {\n operation: 'service_accounts.list_groups',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{service_account_id}/groups',\n path: `/api/v1/service-accounts/${encodeURIComponent(serviceAccountId)}/groups`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `certificates` management namespace (CONTRACT §27.1).\n *\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `certificates` namespace handle.\n *\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class CertificatesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/certificates` */\n async list(page: PageRequest = {}): Promise<Page<models.Certificate>> {\n const wire = await sendManagement<Page<models.Certificate>>(this.#client, {\n operation: 'certificates.list',\n method: 'GET',\n pathTemplate: '/api/v1/certificates',\n path: '/api/v1/certificates',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `certificates.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Certificate[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/certificates`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreateCertificateRequest): Promise<models.GeneratedCertificate> {\n const wire = await sendManagement<models.GeneratedCertificateWire>(this.#client, {\n operation: 'certificates.generate',\n method: 'POST',\n pathTemplate: '/api/v1/certificates',\n path: '/api/v1/certificates',\n body: body,\n });\n return models.generatedCertificateFromWire(wire);\n }\n\n /** `GET /api/v1/certificates/{id}` */\n async get(id: string): Promise<models.Certificate> {\n const wire = await sendManagement<models.Certificate>(this.#client, {\n operation: 'certificates.get',\n method: 'GET',\n pathTemplate: '/api/v1/certificates/{id}',\n path: `/api/v1/certificates/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/certificates/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'certificates.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/certificates/{id}/revoke',\n path: `/api/v1/certificates/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `ca_certificates` management namespace (CONTRACT §27.1).\n *\n * Organization CAs and the per-tenant signing CAs chained beneath them.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `ca_certificates` namespace handle.\n *\n * Organization CAs and the per-tenant signing CAs chained beneath them.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class CaCertificatesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): CaCertificatesApi {\n return new CaCertificatesApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/ca-certificates` */\n async list(page: PageRequest = {}): Promise<Page<models.CaCertificate>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.list\");\n const wire = await sendManagement<Page<models.CaCertificate>>(this.#client, {\n operation: 'ca_certificates.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates',\n path: `/api/v1/organizations/${orgId}/ca-certificates`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `ca_certificates.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.CaCertificate[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreateCaCertificateRequest): Promise<models.GeneratedCaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.generate\");\n const wire = await sendManagement<models.GeneratedCaCertificateWire>(this.#client, {\n operation: 'ca_certificates.generate',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates',\n path: `/api/v1/organizations/${orgId}/ca-certificates`,\n body: body,\n });\n return models.generatedCaCertificateFromWire(wire);\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/import`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async importCa(body: models.ImportCaCertificateRequest): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.import_ca\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.import_ca',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/import',\n path: `/api/v1/organizations/${orgId}/ca-certificates/import`,\n body: models.importCaCertificateRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/ca-certificates/{id}` */\n async get(id: string): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.get\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.revoke\");\n await sendManagement<void>(this.#client, {\n operation: 'ca_certificates.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/revoke',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/{id}/migrate-custody`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async migrateCustody(id: string): Promise<models.MigrateCustodyResponse> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.migrate_custody\");\n const wire = await sendManagement<models.MigrateCustodyResponse>(this.#client, {\n operation: 'ca_certificates.migrate_custody',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/migrate-custody',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/migrate-custody`,\n });\n return wire;\n }\n\n /**\n * `PUT\n * /api/v1/organizations/{org_id}/ca-certificates/{id}/mtls-trust-anchor`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setMtlsTrustAnchor(id: string, body: models.SetMtlsTrustAnchor): Promise<models.MtlsTrustAnchorResponse> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.set_mtls_trust_anchor\");\n const wire = await sendManagement<models.MtlsTrustAnchorResponse>(this.#client, {\n operation: 'ca_certificates.set_mtls_trust_anchor',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/mtls-trust-anchor',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/mtls-trust-anchor`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas` */\n async listSigningCas(tenantId: string, page: PageRequest = {}): Promise<Page<models.CaCertificate>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.list_signing_cas\");\n const wire = await sendManagement<Page<models.CaCertificate>>(this.#client, {\n operation: 'ca_certificates.list_signing_cas',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `ca_certificates.list_signing_cas` to exhaustion, concatenating every\n * page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listSigningCasAll(tenantId: string, start: PageRequest = {}): Promise<models.CaCertificate[]> {\n return collectPages(start, (p) => this.listSigningCas(tenantId, p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generateSigningCa(tenantId: string, body: models.CreateIntermediateCaRequest): Promise<models.GeneratedCaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.generate_signing_ca\");\n const wire = await sendManagement<models.GeneratedCaCertificateWire>(this.#client, {\n operation: 'ca_certificates.generate_signing_ca',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas`,\n body: body,\n });\n return models.generatedCaCertificateFromWire(wire);\n }\n\n /**\n * `POST\n * /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas/sign-csr`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async signSigningCaCsr(tenantId: string, body: models.SignIntermediateCsrRequest): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.sign_signing_ca_csr\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.sign_signing_ca_csr',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas/sign-csr',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas/sign-csr`,\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `pgp_keys` management namespace (CONTRACT §27.1).\n *\n * OpenPGP keys used for audit signing and encrypted data export.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `pgp_keys` namespace handle.\n *\n * OpenPGP keys used for audit signing and encrypted data export.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PgpKeysApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/pgp-keys` */\n async list(page: PageRequest = {}): Promise<Page<models.PgpKey>> {\n const wire = await sendManagement<Page<models.PgpKey>>(this.#client, {\n operation: 'pgp_keys.list',\n method: 'GET',\n pathTemplate: '/api/v1/pgp-keys',\n path: '/api/v1/pgp-keys',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `pgp_keys.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.PgpKey[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/pgp-keys`\n *\n * **Returns secret material, once.** `private_key_armored` is returned by\n * this call and by no other; no later `get` will return it again, and the\n * `get` projection has no field where it was. Discarding the result destroys\n * the credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreatePgpKeyRequest): Promise<models.GeneratedPgpKey> {\n const wire = await sendManagement<models.GeneratedPgpKeyWire>(this.#client, {\n operation: 'pgp_keys.generate',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys',\n path: '/api/v1/pgp-keys',\n body: body,\n });\n return models.generatedPgpKeyFromWire(wire);\n }\n\n /** `GET /api/v1/pgp-keys/{id}` */\n async get(id: string): Promise<models.PgpKey> {\n const wire = await sendManagement<models.PgpKey>(this.#client, {\n operation: 'pgp_keys.get',\n method: 'GET',\n pathTemplate: '/api/v1/pgp-keys/{id}',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/pgp-keys/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'pgp_keys.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/{id}/revoke',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n /**\n * `POST /api/v1/pgp-keys/{id}/encrypt`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async encrypt(id: string, body: models.EncryptRequest): Promise<models.EncryptedExport> {\n const wire = await sendManagement<models.EncryptedExport>(this.#client, {\n operation: 'pgp_keys.encrypt',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/{id}/encrypt',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}/encrypt`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/pgp-keys/sign-audit-batch`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async signAuditBatch(body: models.SignAuditBatchRequest): Promise<models.SignedAuditBatch> {\n const wire = await sendManagement<models.SignedAuditBatch>(this.#client, {\n operation: 'pgp_keys.sign_audit_batch',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/sign-audit-batch',\n path: '/api/v1/pgp-keys/sign-audit-batch',\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `webhooks` management namespace (CONTRACT §27.1).\n *\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `webhooks` namespace handle.\n *\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class WebhooksApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/webhooks` */\n async list(page: PageRequest = {}): Promise<Page<models.WebhookResponse>> {\n const wire = await sendManagement<Page<models.WebhookResponse>>(this.#client, {\n operation: 'webhooks.list',\n method: 'GET',\n pathTemplate: '/api/v1/webhooks',\n path: '/api/v1/webhooks',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `webhooks.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.WebhookResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/webhooks`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateWebhookRequest): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.create',\n method: 'POST',\n pathTemplate: '/api/v1/webhooks',\n path: '/api/v1/webhooks',\n body: models.createWebhookRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/webhooks/{id}` */\n async get(id: string): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.get',\n method: 'GET',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/webhooks/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateWebhookRequest): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.update',\n method: 'PUT',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n body: models.updateWebhookRequestToWire(body),\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/webhooks/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'webhooks.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `oauth2_clients` management namespace (CONTRACT §27.1).\n *\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `oauth2_clients` namespace handle.\n *\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class Oauth2ClientsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/oauth2-clients` */\n async list(page: PageRequest = {}): Promise<Page<models.OAuth2ClientResponse>> {\n const wire = await sendManagement<Page<models.OAuth2ClientResponse>>(this.#client, {\n operation: 'oauth2_clients.list',\n method: 'GET',\n pathTemplate: '/api/v1/oauth2-clients',\n path: '/api/v1/oauth2-clients',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `oauth2_clients.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.OAuth2ClientResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/oauth2-clients`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateOAuth2ClientRequest): Promise<models.OAuth2ClientCreatedResponse> {\n const wire = await sendManagement<models.OAuth2ClientCreatedResponseWire>(this.#client, {\n operation: 'oauth2_clients.create',\n method: 'POST',\n pathTemplate: '/api/v1/oauth2-clients',\n path: '/api/v1/oauth2-clients',\n body: body,\n });\n return models.oAuth2ClientCreatedResponseFromWire(wire);\n }\n\n /** `GET /api/v1/oauth2-clients/{id}` */\n async get(id: string): Promise<models.OAuth2ClientResponse> {\n const wire = await sendManagement<models.OAuth2ClientResponse>(this.#client, {\n operation: 'oauth2_clients.get',\n method: 'GET',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/oauth2-clients/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateOAuth2ClientRequest): Promise<models.OAuth2ClientResponse> {\n const wire = await sendManagement<models.OAuth2ClientResponse>(this.#client, {\n operation: 'oauth2_clients.update',\n method: 'PUT',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/oauth2-clients/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'oauth2_clients.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `federation` management namespace (CONTRACT §27.1).\n *\n * Upstream IdP configuration and the per-user links it produces.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `federation` namespace handle.\n *\n * Upstream IdP configuration and the per-user links it produces.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class FederationApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/federation-configs` */\n async listConfigs(page: PageRequest = {}): Promise<Page<models.FederationConfigResponse>> {\n const wire = await sendManagement<Page<models.FederationConfigResponse>>(this.#client, {\n operation: 'federation.list_configs',\n method: 'GET',\n pathTemplate: '/api/v1/federation-configs',\n path: '/api/v1/federation-configs',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `federation.list_configs` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listConfigsAll(start: PageRequest = {}): Promise<models.FederationConfigResponse[]> {\n return collectPages(start, (p) => this.listConfigs(p));\n }\n\n /**\n * `POST /api/v1/federation-configs`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async createConfig(body: models.CreateFederationConfigRequest): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.create_config',\n method: 'POST',\n pathTemplate: '/api/v1/federation-configs',\n path: '/api/v1/federation-configs',\n body: models.createFederationConfigRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/federation-configs/{id}` */\n async getConfig(id: string): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.get_config',\n method: 'GET',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/federation-configs/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async updateConfig(id: string, body: models.UpdateFederationConfigRequest): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.update_config',\n method: 'PUT',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n body: models.updateFederationConfigRequestToWire(body),\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/federation-configs/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteConfig(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'federation.delete_config',\n method: 'DELETE',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n });\n }\n\n /** `GET /api/v1/federation-links/user/{user_id}` */\n async listUserLinks(userId: string): Promise<models.FederationLinkResponse[]> {\n const wire = await sendManagement<models.FederationLinkResponse[]>(this.#client, {\n operation: 'federation.list_user_links',\n method: 'GET',\n pathTemplate: '/api/v1/federation-links/user/{user_id}',\n path: `/api/v1/federation-links/user/${encodeURIComponent(userId)}`,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/federation-links/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteLink(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'federation.delete_link',\n method: 'DELETE',\n pathTemplate: '/api/v1/federation-links/{id}',\n path: `/api/v1/federation-links/${encodeURIComponent(id)}`,\n });\n }\n\n /**\n * `POST /api/v1/federation/oidc/authorize`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async oidcAuthorize(body: models.OidcAuthorizeRequest): Promise<models.OidcAuthorizeResponse> {\n const wire = await sendManagement<models.OidcAuthorizeResponse>(this.#client, {\n operation: 'federation.oidc_authorize',\n method: 'POST',\n pathTemplate: '/api/v1/federation/oidc/authorize',\n path: '/api/v1/federation/oidc/authorize',\n body: body,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/federation/oidc/callback`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async oidcCallback(body: models.OidcCallbackRequest): Promise<models.OidcCallbackResponse> {\n const wire = await sendManagement<models.OidcCallbackResponse>(this.#client, {\n operation: 'federation.oidc_callback',\n method: 'POST',\n pathTemplate: '/api/v1/federation/oidc/callback',\n path: '/api/v1/federation/oidc/callback',\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `notification_rules` management namespace (CONTRACT §27.1).\n *\n * Which events raise a notification, and to whom.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `notification_rules` namespace handle.\n *\n * Which events raise a notification, and to whom.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class NotificationRulesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/notification-rules` */\n async list(page: PageRequest = {}): Promise<Page<models.NotificationRuleResponse>> {\n const wire = await sendManagement<Page<models.NotificationRuleResponse>>(this.#client, {\n operation: 'notification_rules.list',\n method: 'GET',\n pathTemplate: '/api/v1/notification-rules',\n path: '/api/v1/notification-rules',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `notification_rules.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.NotificationRuleResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/notification-rules`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateNotificationRuleRequest): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.create',\n method: 'POST',\n pathTemplate: '/api/v1/notification-rules',\n path: '/api/v1/notification-rules',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/notification-rules/{id}` */\n async get(id: string): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.get',\n method: 'GET',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/notification-rules/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateNotificationRuleRequest): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.update',\n method: 'PUT',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/notification-rules/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'notification_rules.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `email_config` management namespace (CONTRACT §27.1).\n *\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `email_config` namespace handle.\n *\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class EmailConfigApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): EmailConfigApi {\n return new EmailConfigApi(this.#client, { ...this.#scope, orgId });\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): EmailConfigApi {\n return new EmailConfigApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/email-config` */\n async getOrg(): Promise<models.EmailConfig> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.get_org\");\n const wire = await sendManagement<models.EmailConfig>(this.#client, {\n operation: 'email_config.get_org',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/email-config`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setOrg(body: models.SetOrgEmailConfig): Promise<models.EmailConfig> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.set_org\");\n const wire = await sendManagement<models.EmailConfig>(this.#client, {\n operation: 'email_config.set_org',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/organizations/{org_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteOrg(): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.delete_org\");\n await sendManagement<void>(this.#client, {\n operation: 'email_config.delete_org',\n method: 'DELETE',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/email-config/test`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async testOrg(): Promise<models.EmailTestResult> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.test_org\");\n const wire = await sendManagement<models.EmailTestResult>(this.#client, {\n operation: 'email_config.test_org',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config/test',\n path: `/api/v1/organizations/${orgId}/email-config/test`,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/email-config` */\n async getTenant(): Promise<models.EmailConfigOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.get_tenant\");\n const wire = await sendManagement<models.EmailConfigOverride>(this.#client, {\n operation: 'email_config.get_tenant',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setTenant(body: models.EmailConfigOverride): Promise<models.EmailConfigOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.set_tenant\");\n const wire = await sendManagement<models.EmailConfigOverride>(this.#client, {\n operation: 'email_config.set_tenant',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/tenants/{tenant_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteTenant(): Promise<void> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.delete_tenant\");\n await sendManagement<void>(this.#client, {\n operation: 'email_config.delete_tenant',\n method: 'DELETE',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n });\n }\n\n /**\n * `POST /api/v1/tenants/{tenant_id}/email-config/test`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async testTenant(): Promise<models.EmailTestResult> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.test_tenant\");\n const wire = await sendManagement<models.EmailTestResult>(this.#client, {\n operation: 'email_config.test_tenant',\n method: 'POST',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config/test',\n path: `/api/v1/tenants/${tenantId}/email-config/test`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `settings` management namespace (CONTRACT §27.1).\n *\n * Effective settings, and the organization/tenant layers they resolve from.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `settings` namespace handle.\n *\n * Effective settings, and the organization/tenant layers they resolve from.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class SettingsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): SettingsApi {\n return new SettingsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): SettingsApi {\n return new SettingsApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/settings` */\n async getOrg(): Promise<models.SecuritySettings> {\n const orgId = resolveOrg(this.#client, this.#scope, \"settings.get_org\");\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.get_org',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/settings',\n path: `/api/v1/organizations/${orgId}/settings`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/settings`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setOrg(body: models.SetOrgSettings): Promise<models.SecuritySettings> {\n const orgId = resolveOrg(this.#client, this.#scope, \"settings.set_org\");\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.set_org',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/settings',\n path: `/api/v1/organizations/${orgId}/settings`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/settings` */\n async getEffective(): Promise<models.SecuritySettings> {\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.get_effective',\n method: 'GET',\n pathTemplate: '/api/v1/settings',\n path: '/api/v1/settings',\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setEffective(body: models.TenantSettingsOverride): Promise<models.SecuritySettings> {\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.set_effective',\n method: 'PUT',\n pathTemplate: '/api/v1/settings',\n path: '/api/v1/settings',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/settings` */\n async getTenantOverride(): Promise<models.TenantSettingsOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.get_tenant_override\");\n const wire = await sendManagement<models.TenantSettingsOverride>(this.#client, {\n operation: 'settings.get_tenant_override',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setTenantOverride(body: models.TenantSettingsOverride): Promise<models.TenantSettingsOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.set_tenant_override\");\n const wire = await sendManagement<models.TenantSettingsOverride>(this.#client, {\n operation: 'settings.set_tenant_override',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/tenants/{tenant_id}/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteTenantOverride(): Promise<void> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.delete_tenant_override\");\n await sendManagement<void>(this.#client, {\n operation: 'settings.delete_tenant_override',\n method: 'DELETE',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `scim_tokens` management namespace (CONTRACT §27.1).\n *\n * Bearer tokens for the SCIM 2.0 provisioning endpoint.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `scim_tokens` namespace handle.\n *\n * Bearer tokens for the SCIM 2.0 provisioning endpoint.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ScimTokensApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/scim-tokens` */\n async list(): Promise<models.ScimTokenResponse[]> {\n const wire = await sendManagement<models.ScimTokenResponse[]>(this.#client, {\n operation: 'scim_tokens.list',\n method: 'GET',\n pathTemplate: '/api/v1/scim-tokens',\n path: '/api/v1/scim-tokens',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/scim-tokens`\n *\n * **Returns secret material, once.** `provisioning_token` is returned by\n * this call and by no other; no later `get` will return it again, and the\n * `get` projection has no field where it was. Discarding the result destroys\n * the credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateScimTokenRequest): Promise<models.CreateScimTokenResponse> {\n const wire = await sendManagement<models.CreateScimTokenResponseWire>(this.#client, {\n operation: 'scim_tokens.create',\n method: 'POST',\n pathTemplate: '/api/v1/scim-tokens',\n path: '/api/v1/scim-tokens',\n body: body,\n });\n return models.createScimTokenResponseFromWire(wire);\n }\n\n /**\n * `DELETE /api/v1/scim-tokens/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'scim_tokens.revoke',\n method: 'DELETE',\n pathTemplate: '/api/v1/scim-tokens/{id}',\n path: `/api/v1/scim-tokens/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `reactors` management namespace (CONTRACT §27.1).\n *\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `reactors` namespace handle.\n *\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ReactorsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/reactors` */\n async list(page: PageRequest = {}): Promise<Page<models.ReactorResponse>> {\n const wire = await sendManagement<Page<models.ReactorResponse>>(this.#client, {\n operation: 'reactors.list',\n method: 'GET',\n pathTemplate: '/api/v1/reactors',\n path: '/api/v1/reactors',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `reactors.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.ReactorResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/reactors`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateReactorRequest): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.create',\n method: 'POST',\n pathTemplate: '/api/v1/reactors',\n path: '/api/v1/reactors',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/reactors/{id}` */\n async get(id: string): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.get',\n method: 'GET',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/reactors/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateReactorRequest): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.update',\n method: 'PUT',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/reactors/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'reactors.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n });\n }\n\n /** `GET /api/v1/reactors/events` */\n async listEvents(): Promise<models.ReactorEventDescriptor[]> {\n const wire = await sendManagement<models.ReactorEventDescriptor[]>(this.#client, {\n operation: 'reactors.list_events',\n method: 'GET',\n pathTemplate: '/api/v1/reactors/events',\n path: '/api/v1/reactors/events',\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `webauthn_policy` management namespace (CONTRACT §27.1).\n *\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `webauthn_policy` namespace handle.\n *\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class WebauthnPolicyApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): WebauthnPolicyApi {\n return new WebauthnPolicyApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/webauthn/attestation-policy` */\n async get(): Promise<models.PolicyResponse> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.get\");\n const wire = await sendManagement<models.PolicyResponse>(this.#client, {\n operation: 'webauthn_policy.get',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/attestation-policy',\n path: `/api/v1/tenants/${tenantId}/webauthn/attestation-policy`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/webauthn/attestation-policy`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async set(body: models.WebauthnAttestationPolicy): Promise<models.WebauthnAttestationPolicy> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.set\");\n const wire = await sendManagement<models.WebauthnAttestationPolicy>(this.#client, {\n operation: 'webauthn_policy.set',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/attestation-policy',\n path: `/api/v1/tenants/${tenantId}/webauthn/attestation-policy`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/webauthn/compliance-report` */\n async complianceReport(): Promise<models.ComplianceReportEntry[]> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.compliance_report\");\n const wire = await sendManagement<models.ComplianceReportEntry[]>(this.#client, {\n operation: 'webauthn_policy.compliance_report',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/compliance-report',\n path: `/api/v1/tenants/${tenantId}/webauthn/compliance-report`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `audit` management namespace (CONTRACT §27.1).\n *\n * Append-only audit log, read-only by construction.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * Optional filters for `audit.list`.\n *\n * Six loose optional arguments is a call site a reader cannot check and a\n * refactor silently reorders, so they travel as one object.\n */\nexport interface AuditListFilter {\n /** Filter on `actor_id`. */\n actorId?: string;\n /** Filter on `action`. */\n action?: string;\n /** Filter on `outcome`. */\n outcome?: string;\n /** Filter on `resource_id`. */\n resourceId?: string;\n /** Filter on `from`. */\n from?: string;\n /** Filter on `to`. */\n to?: string;\n}\n\n/**\n * Optional filters for `audit.list_system`.\n *\n * Six loose optional arguments is a call site a reader cannot check and a\n * refactor silently reorders, so they travel as one object.\n */\nexport interface AuditListSystemFilter {\n /** Filter on `actor_id`. */\n actorId?: string;\n /** Filter on `action`. */\n action?: string;\n /** Filter on `outcome`. */\n outcome?: string;\n /** Filter on `resource_id`. */\n resourceId?: string;\n /** Filter on `from`. */\n from?: string;\n /** Filter on `to`. */\n to?: string;\n}\n\n/**\n * The `audit` namespace handle.\n *\n * Append-only audit log, read-only by construction.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class AuditApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/audit-logs` */\n async list(filter: AuditListFilter = {}, page: PageRequest = {}): Promise<Page<models.AuditLogEntry>> {\n const wire = await sendManagement<Page<models.AuditLogEntry>>(this.#client, {\n operation: 'audit.list',\n method: 'GET',\n pathTemplate: '/api/v1/audit-logs',\n path: '/api/v1/audit-logs',\n query: { ...pageQuery(page), 'actor_id': filter.actorId, 'action': filter.action, 'outcome': filter.outcome, 'resource_id': filter.resourceId, 'from': filter.from, 'to': filter.to },\n });\n return wire;\n }\n\n /**\n * Walk `audit.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(filter: AuditListFilter = {}, start: PageRequest = {}): Promise<models.AuditLogEntry[]> {\n return collectPages(start, (p) => this.list(filter, p));\n }\n\n /** `GET /api/v1/audit-logs/system` */\n async listSystem(filter: AuditListSystemFilter = {}, page: PageRequest = {}): Promise<Page<models.AuditLogEntry>> {\n const wire = await sendManagement<Page<models.AuditLogEntry>>(this.#client, {\n operation: 'audit.list_system',\n method: 'GET',\n pathTemplate: '/api/v1/audit-logs/system',\n path: '/api/v1/audit-logs/system',\n query: { ...pageQuery(page), 'actor_id': filter.actorId, 'action': filter.action, 'outcome': filter.outcome, 'resource_id': filter.resourceId, 'from': filter.from, 'to': filter.to },\n });\n return wire;\n }\n\n /**\n * Walk `audit.list_system` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listSystemAll(filter: AuditListSystemFilter = {}, start: PageRequest = {}): Promise<models.AuditLogEntry[]> {\n return collectPages(start, (p) => this.listSystem(filter, p));\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `privacy` management namespace (CONTRACT §27.1).\n *\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `privacy` namespace handle.\n *\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PrivacyApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * `POST /api/v1/account/export`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async requestExport(body: unknown): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.request_export',\n method: 'POST',\n pathTemplate: '/api/v1/account/export',\n path: '/api/v1/account/export',\n body: body,\n });\n }\n\n /** `GET /api/v1/account/export/{token}` */\n async downloadExport(token: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.download_export',\n method: 'GET',\n pathTemplate: '/api/v1/account/export/{token}',\n path: `/api/v1/account/export/${encodeURIComponent(token)}`,\n });\n }\n\n /**\n * `POST /api/v1/account/delete`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async requestDelete(body: unknown): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.request_delete',\n method: 'POST',\n pathTemplate: '/api/v1/account/delete',\n path: '/api/v1/account/delete',\n body: body,\n });\n }\n\n /** `GET /api/v1/auth/account/delete/cancel` */\n async cancelDelete(token: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.cancel_delete',\n method: 'GET',\n pathTemplate: '/api/v1/auth/account/delete/cancel',\n path: '/api/v1/auth/account/delete/cancel',\n query: { \"token\": token },\n });\n }\n\n /** `GET /api/v1/account/consents` */\n async listConsents(): Promise<models.ConsentView[]> {\n const wire = await sendManagement<models.ConsentView[]>(this.#client, {\n operation: 'privacy.list_consents',\n method: 'GET',\n pathTemplate: '/api/v1/account/consents',\n path: '/api/v1/account/consents',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/account/consents/oidc-scopes`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async grantScopeConsent(body: models.GrantScopeConsent): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.grant_scope_consent',\n method: 'POST',\n pathTemplate: '/api/v1/account/consents/oidc-scopes',\n path: '/api/v1/account/consents/oidc-scopes',\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/account/consents/oidc-scopes/{client_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async withdrawScopeConsent(clientId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.withdraw_scope_consent',\n method: 'DELETE',\n pathTemplate: '/api/v1/account/consents/oidc-scopes/{client_id}',\n path: `/api/v1/account/consents/oidc-scopes/${encodeURIComponent(clientId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `platform` management namespace (CONTRACT §27.1).\n *\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `platform` namespace handle.\n *\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PlatformApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /health` */\n async health(): Promise<models.HealthResponse> {\n const wire = await sendManagement<models.HealthResponse>(this.#client, {\n operation: 'platform.health',\n method: 'GET',\n pathTemplate: '/health',\n path: '/health',\n });\n return wire;\n }\n\n /** `GET /ready` */\n async ready(): Promise<models.ReadyResponse> {\n const wire = await sendManagement<models.ReadyResponse>(this.#client, {\n operation: 'platform.ready',\n method: 'GET',\n pathTemplate: '/ready',\n path: '/ready',\n });\n return wire;\n }\n\n /** `GET /api/v1/mds/status` */\n async mdsStatus(): Promise<models.MdsStatusResponse> {\n const wire = await sendManagement<models.MdsStatusResponse>(this.#client, {\n operation: 'platform.mds_status',\n method: 'GET',\n pathTemplate: '/api/v1/mds/status',\n path: '/api/v1/mds/status',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/mds/refresh`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async mdsRefresh(): Promise<models.MdsRefreshOutcome> {\n const wire = await sendManagement<models.MdsRefreshOutcome>(this.#client, {\n operation: 'platform.mds_refresh',\n method: 'POST',\n pathTemplate: '/api/v1/mds/refresh',\n path: '/api/v1/mds/refresh',\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * One handle per §27 namespace, and the accessors that reach them.\n *\n * §27.2 makes this namespacing normative rather than stylistic: twenty\n * namespaces have a `list` and fourteen a `get`, so flattening 147 operations\n * onto the client would need a disambiguating prefix invented once per\n * operation — and would bury the eight §1 methods most callers actually want\n * under five times as many they do not.\n */\n\nexport * from './organizations.js';\nexport * from './tenants.js';\nexport * from './users.js';\nexport * from './groups.js';\nexport * from './roles.js';\nexport * from './permissions.js';\nexport * from './resources.js';\nexport * from './scopes.js';\nexport * from './service_accounts.js';\nexport * from './certificates.js';\nexport * from './ca_certificates.js';\nexport * from './pgp_keys.js';\nexport * from './webhooks.js';\nexport * from './oauth2_clients.js';\nexport * from './federation.js';\nexport * from './notification_rules.js';\nexport * from './email_config.js';\nexport * from './settings.js';\nexport * from './scim_tokens.js';\nexport * from './reactors.js';\nexport * from './webauthn_policy.js';\nexport * from './audit.js';\nexport * from './privacy.js';\nexport * from './platform.js';\n\nimport { OrganizationsApi } from './organizations.js';\nimport { TenantsApi } from './tenants.js';\nimport { UsersApi } from './users.js';\nimport { GroupsApi } from './groups.js';\nimport { RolesApi } from './roles.js';\nimport { PermissionsApi } from './permissions.js';\nimport { ResourcesApi } from './resources.js';\nimport { ScopesApi } from './scopes.js';\nimport { ServiceAccountsApi } from './service_accounts.js';\nimport { CertificatesApi } from './certificates.js';\nimport { CaCertificatesApi } from './ca_certificates.js';\nimport { PgpKeysApi } from './pgp_keys.js';\nimport { WebhooksApi } from './webhooks.js';\nimport { Oauth2ClientsApi } from './oauth2_clients.js';\nimport { FederationApi } from './federation.js';\nimport { NotificationRulesApi } from './notification_rules.js';\nimport { EmailConfigApi } from './email_config.js';\nimport { SettingsApi } from './settings.js';\nimport { ScimTokensApi } from './scim_tokens.js';\nimport { ReactorsApi } from './reactors.js';\nimport { WebauthnPolicyApi } from './webauthn_policy.js';\nimport { AuditApi } from './audit.js';\nimport { PrivacyApi } from './privacy.js';\nimport { PlatformApi } from './platform.js';\nimport type { AxiamClient } from '../../rest/client.js';\n\n/** Every §27 namespace handle, lazily constructed per access. */\nexport interface ManagementNamespaces {\n /**\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n */\n readonly organizations: OrganizationsApi;\n /**\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n */\n readonly tenants: TenantsApi;\n /**\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n */\n readonly users: UsersApi;\n /**\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n */\n readonly groups: GroupsApi;\n /** Roles, their permission sets, and their assignment to users and groups. */\n readonly roles: RolesApi;\n /** Permissions -- an action on a resource, optionally narrowed by a scope. */\n readonly permissions: PermissionsApi;\n /** The resource hierarchy role assignments cascade down. */\n readonly resources: ResourcesApi;\n /** Sub-resource granularity, always addressed under their resource. */\n readonly scopes: ScopesApi;\n /**\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n */\n readonly serviceAccounts: ServiceAccountsApi;\n /**\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n */\n readonly certificates: CertificatesApi;\n /** Organization CAs and the per-tenant signing CAs chained beneath them. */\n readonly caCertificates: CaCertificatesApi;\n /** OpenPGP keys used for audit signing and encrypted data export. */\n readonly pgpKeys: PgpKeysApi;\n /**\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n */\n readonly webhooks: WebhooksApi;\n /**\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n */\n readonly oauth2Clients: Oauth2ClientsApi;\n /** Upstream IdP configuration and the per-user links it produces. */\n readonly federation: FederationApi;\n /** Which events raise a notification, and to whom. */\n readonly notificationRules: NotificationRulesApi;\n /**\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n */\n readonly emailConfig: EmailConfigApi;\n /** Effective settings, and the organization/tenant layers they resolve from. */\n readonly settings: SettingsApi;\n /** Bearer tokens for the SCIM 2.0 provisioning endpoint. */\n readonly scimTokens: ScimTokensApi;\n /**\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n */\n readonly reactors: ReactorsApi;\n /**\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n */\n readonly webauthnPolicy: WebauthnPolicyApi;\n /** Append-only audit log, read-only by construction. */\n readonly audit: AuditApi;\n /**\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n */\n readonly privacy: PrivacyApi;\n /**\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n */\n readonly platform: PlatformApi;\n}\n\n/**\n * Build the namespace handles for `client`.\n *\n * @internal — reached as `client.users`, `client.roles`, and so on.\n */\nexport function managementNamespaces(client: AxiamClient): ManagementNamespaces {\n return {\n get organizations() {\n return new OrganizationsApi(client);\n },\n get tenants() {\n return new TenantsApi(client);\n },\n get users() {\n return new UsersApi(client);\n },\n get groups() {\n return new GroupsApi(client);\n },\n get roles() {\n return new RolesApi(client);\n },\n get permissions() {\n return new PermissionsApi(client);\n },\n get resources() {\n return new ResourcesApi(client);\n },\n get scopes() {\n return new ScopesApi(client);\n },\n get serviceAccounts() {\n return new ServiceAccountsApi(client);\n },\n get certificates() {\n return new CertificatesApi(client);\n },\n get caCertificates() {\n return new CaCertificatesApi(client);\n },\n get pgpKeys() {\n return new PgpKeysApi(client);\n },\n get webhooks() {\n return new WebhooksApi(client);\n },\n get oauth2Clients() {\n return new Oauth2ClientsApi(client);\n },\n get federation() {\n return new FederationApi(client);\n },\n get notificationRules() {\n return new NotificationRulesApi(client);\n },\n get emailConfig() {\n return new EmailConfigApi(client);\n },\n get settings() {\n return new SettingsApi(client);\n },\n get scimTokens() {\n return new ScimTokensApi(client);\n },\n get reactors() {\n return new ReactorsApi(client);\n },\n get webauthnPolicy() {\n return new WebauthnPolicyApi(client);\n },\n get audit() {\n return new AuditApi(client);\n },\n get privacy() {\n return new PrivacyApi(client);\n },\n get platform() {\n return new PlatformApi(client);\n },\n };\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 */\nimport { ManifestApi } from '../management/manifest/engine.js';\nimport type { ManagementNamespaces } from '../management/ops/index.js';\nimport { managementNamespaces } from '../management/ops/index.js';\n\n/**\n * The §27 management namespaces, merged onto the client.\n *\n * Declaration merging rather than 24 hand-written getters: the namespace set\n * is generated from `management-registry.json`, and a hand-maintained copy of\n * it on this class is the thing §27.8 exists to prevent.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface AxiamClient extends ManagementNamespaces {}\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 // §27.2 rule 1: acquiring a handle performs no I/O and is not meant to be\n // observable. Copying the *descriptors* keeps the generated getters lazy,\n // so constructing a client does not construct 24 namespace objects; a\n // plain `Object.assign` would invoke every getter here.\n Object.defineProperties(this, Object.getOwnPropertyDescriptors(managementNamespaces(this)));\n }\n\n /**\n * Declarative management — CONTRACT.md §27.6.\n *\n * `client.manifest.plan(m)` says what would change and writes nothing;\n * `client.manifest.apply(m)` reconciles.\n */\n get manifest(): ManifestApi {\n return new ManifestApi(this);\n }\n\n /**\n * Every §27 namespace behind one accessor (§27.2 rule 4).\n *\n * `client.management.users` and `client.users` are the same handle; this\n * exists for callers who prefer the management surface not to be mixed in\n * with §1's eight methods when reading a call site.\n */\n get management(): ManagementNamespaces {\n return managementNamespaces(this);\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), sealed against the tenant this client is **acting on**.\n * The server cannot build one — it never sees the plaintext.\n *\n * Right for creating **another** account (§27 `users.create`); for the\n * caller's *own* password change use {@link opaqueEnrollmentForSelf}, which\n * seals against the tenant the account lives in (§5.2.2 rule 2).\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 * Build an OPAQUE registration record for the **caller's own** new password,\n * sealed against the tenant the caller's account lives in (§5.2.2 rule 2).\n *\n * Identical to {@link opaqueEnrollment} for every ordinary principal — the\n * two tenants are the same value there. They diverge for an\n * organization-level principal that has selected another tenant to act on,\n * and a record sealed against the acting one is refused with *\"the OPAQUE\n * session was issued for a different tenant\"*.\n *\n * Requires a completed login: the principal tenant is reported by the login\n * response, so there is nothing to seal against before then.\n */\n opaqueEnrollmentForSelf(password: string): Promise<opaqueMethods.OpaqueEnrollment> {\n return opaqueMethods.opaqueEnrollmentForSelf(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 /**\n * `POST /api/v1/auth/resend-verification` (§25.1) — the unauthenticated\n * resend. Resolves whatever the outcome; use {@link resendOwnVerification}\n * when there is a session (§25.7).\n */\n resendVerification(email: string, tenantId: string): Promise<void> {\n return accountMethods.resendVerification(this, email, tenantId);\n }\n\n /**\n * `POST /api/v1/users/me/resend-verification` (§25.1, §25.7) — the\n * authenticated resend, which takes no address and reports what happened.\n */\n resendOwnVerification(): Promise<void> {\n return accountMethods.resendOwnVerification(this);\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","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/http';\nimport type { AxiosInstance } from 'axios';\nimport type { NodeTlsOptions } from '../rest/session.js';\n\n/** The `axiam_access` cookie name (httpOnly, path `/`). */\nexport const ACCESS_COOKIE = 'axiam_access';\n/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */\nexport const REFRESH_COOKIE = 'axiam_refresh';\n/** The `axiam_csrf` cookie name (JS-readable, path `/`). */\nexport const CSRF_COOKIE = 'axiam_csrf';\n\n/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */\nexport function createJar(): CookieJar {\n return new CookieJar();\n}\n\n/**\n * Attach jar-aware agents to an axios instance so the jar persists\n * `Set-Cookie` responses across requests and replays them on subsequent\n * requests to the same origin/path (§4). Mutates and returns the same\n * instance.\n *\n * The agents are constructed HERE rather than via `axios-cookiejar-support`'s\n * `wrapper()`, which used to do it. That wrapper is a thin convenience layer:\n * all cookie handling lives in `http-cookie-agent`'s agents, which it builds\n * for you inside a request interceptor — and that interceptor is hostile to\n * any other agent. It THROWS\n *\n * axios-cookiejar-support does not support for use with other http(s).Agent.\n *\n * when it finds an `httpsAgent` it did not create, and otherwise replaces it.\n * Since `createSession` attaches an `https.Agent` whenever `customCa` or a\n * §6.1 client certificate is configured, the Node persona could never use\n * either: with TLS material configured every request threw, and there was no\n * seam to pass CA/cert/key through the wrapper's own agent construction.\n *\n * Building the agent ourselves closes that: ONE `HttpsCookieAgent` that is\n * both jar-aware and TLS-configured. Cookie behaviour is unchanged — it is\n * the same agent class the wrapper was constructing, just with the TLS\n * options merged in.\n *\n * @param tls §6/§6.1 TLS material, or undefined for the default trust store.\n * Never carries `rejectUnauthorized`: strict server verification\n * is not negotiable (§6).\n */\nexport function wrapAxios(\n instance: AxiosInstance,\n jar: CookieJar,\n tls?: NodeTlsOptions,\n): AxiosInstance {\n // `http-cookie-agent`'s .d.ts resolves tough-cookie through the CJS\n // condition while this file resolves it through the ESM one, so TypeScript\n // sees two structurally identical CookieJar declarations with separate\n // private fields and refuses the assignment. It is the same class at\n // runtime (one tough-cookie install, one instance). Narrow the cast to the\n // jar itself rather than loosening either signature.\n type AgentCookieOptions = NonNullable<ConstructorParameters<typeof HttpCookieAgent>[0]['cookies']>;\n const cookies = { jar } as unknown as AgentCookieOptions;\n instance.defaults.httpAgent = new HttpCookieAgent({ cookies });\n instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...(tls ?? {}) });\n return instance;\n}\n\n/**\n * Read a single cookie's value out of the jar by name, for the given URL.\n * This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body\n * fallback exists on the wire).\n */\nexport async function extractCookieValue(\n jar: CookieJar,\n url: string,\n name: string,\n): Promise<string | undefined> {\n const cookies = await jar.getCookies(url);\n return cookies.find((c) => c.key === name)?.value;\n}\n","// TokenManager — Node-persona token state (CONTRACT.md §7, D-09/D-11/D-26).\n//\n// Tokens are read from the tough-cookie jar by name (the ONLY token-source\n// path — login/refresh response bodies carry no token fields; see\n// RESEARCH.md Area 3) and wrapped in Sensitive<T> immediately. A\n// synchronous, non-blocking `cachedAccessToken()` fast-path is provided for\n// the grpc-js interceptor's `start()`, which cannot await (Pitfall 3) —\n// mirrors the Rust SDK's src/token/manager.rs::cached_access_token exactly.\n\nimport type { CookieJar } from 'tough-cookie';\nimport { Sensitive } from '../core/index.js';\nimport { ACCESS_COOKIE, REFRESH_COOKIE, extractCookieValue } from './cookieJar.js';\n\n/** Path the server scopes the `axiam_refresh` cookie to (mirrors csrf.rs). */\nconst REFRESH_COOKIE_PATH = '/api/v1/auth/refresh';\n\n/** Tracks the access/refresh token pair for a Node session, kept in sync with the cookie jar after each REST call/refresh. */\nexport class TokenManager {\n readonly #jar: CookieJar;\n readonly #baseUrl: string;\n #tenantId: string | undefined;\n /**\n * Non-blocking cached copy of the current access token, kept in sync via\n * `syncFromJar()` after each REST call/refresh. Read via\n * `cachedAccessToken()` without ever touching the jar's async API — this\n * is the fast-path the grpc-js interceptor's synchronous `start()` needs\n * (Pitfall 3).\n */\n #cachedAccess: Sensitive<string> | null = null;\n\n constructor(jar: CookieJar, baseUrl: string, tenantId?: string) {\n this.#jar = jar;\n this.#baseUrl = baseUrl;\n this.#tenantId = tenantId;\n }\n\n /**\n * Synchronous, best-effort read of the last-known access token. Returns\n * `null` if no token has been cached yet (no request/refresh has\n * completed since construction, or `syncFromJar()` was never called).\n */\n cachedAccessToken(): Sensitive<string> | null {\n return this.#cachedAccess;\n }\n\n /**\n * Async read of the current `axiam_refresh` cookie value from the jar,\n * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL\n * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible\n * at the bare base URL).\n */\n async refreshTokenValue(): Promise<Sensitive<string> | null> {\n const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);\n return value === undefined ? null : new Sensitive(value);\n }\n\n /**\n * Refresh the in-memory cached access token from the jar. Call this after\n * every REST request/refresh so the synchronous gRPC-interceptor fast-path\n * (`cachedAccessToken()`) stays current (Pitfall 3).\n */\n async syncFromJar(): Promise<void> {\n const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);\n this.#cachedAccess = value === undefined ? null : new Sensitive(value);\n }\n\n /** The resolved tenant identifier (slug or UUID form), if known. */\n tenantId(): string | undefined {\n return this.#tenantId;\n }\n\n /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */\n setTenantId(tenantId: string): void {\n this.#tenantId = tenantId;\n }\n\n /**\n * Best-effort decode of the `tenant_id`/`org_id` claims out of the cached\n * access token, WITHOUT signature verification. Used only to populate the\n * `refresh` request body (`RefreshRequest` requires both UUIDs) — never as a\n * trust decision: the actual credential is the httpOnly `axiam_access` cookie\n * the server verifies, and the server re-derives the authoritative `org_id`\n * from the tenant on refresh (see crates/axiam-api-rest handlers/auth.rs),\n * so echoing these values back carries no security weight. A malformed or\n * absent token yields an empty result (the caller then keeps whatever UUIDs\n * were resolved from construction options).\n */\n claimsFromCachedToken(): { tenantId?: string; orgId?: string } {\n const token = this.#cachedAccess?.expose();\n if (!token) {\n return {};\n }\n const claims = decodeJwtPayload(token);\n return {\n tenantId: typeof claims.tenant_id === 'string' ? claims.tenant_id : undefined,\n orgId: typeof claims.org_id === 'string' ? claims.org_id : undefined,\n };\n }\n\n /** Clear all cached token state (used by logout()). */\n clear(): void {\n this.#cachedAccess = null;\n }\n}\n\n/**\n * Decode a JWT's payload segment (the middle base64url part) into an object,\n * without verifying its signature. Returns `{}` for anything that is not a\n * well-formed three-segment JWT with a JSON object payload. This is a routing\n * helper, not a verifier — see {@link TokenManager.claimsFromCachedToken}.\n */\nfunction decodeJwtPayload(token: string): Record<string, unknown> {\n try {\n const segments = token.split('.');\n if (segments.length !== 3) {\n return {};\n }\n const json = Buffer.from(segments[1], 'base64url').toString('utf8');\n const parsed: unknown = JSON.parse(json);\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n","// ID-token claim validation — CONTRACT.md §12.4, OIDC Core §3.1.3.7.\n//\n// PURE logic only: no network, no jose, no crypto beyond a constant-time\n// compare. The signature half of §12.4 (rules 1–2: `alg` allowlist, `kid`\n// lookup, Ed25519 verification, single JWKS re-fetch) lives in node/jwks.ts,\n// on the SAME verifier the §10 middleware already uses — §12 forbids forking\n// it. This module holds rules 3–6 (issuer, audience, time, nonce) plus the\n// reason-code vocabulary, so both halves can be unit-tested independently and\n// ported as one pair.\n//\n// Every failure raises `AuthError` carrying one of the seven stable reason\n// codes from §12.3 rule 3. Rule 7 (all-or-nothing discard) is enforced by the\n// caller — `OidcClient.oidcExchange` never returns a token set whose ID token\n// failed here, so `access_token`/`refresh_token` from the same response are\n// dropped with it.\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { AuthError, type IdTokenFailureReason } from '../core/index.js';\n\n/**\n * The decoded, **already-validated** ID-token claim set carried by\n * {@link OidcTokenSet.idClaims} (CONTRACT.md §12.1).\n *\n * @remarks\n * Claim names are kept verbatim in their JWT/OIDC spelling (`iss`, `sub`,\n * `aud`, …) rather than camelCased: they are protocol identifiers a caller\n * cross-references against OIDC Core, exactly as {@link AxiamClaims} already\n * does for access-token claims. The open index signature is mandated by\n * §12.1 — the ID token's full claim set is not enumerated by `openapi.json`,\n * so unknown claims MUST be preserved and MUST NOT be rejected.\n */\nexport interface IdTokenClaims {\n /** Issuer — matched for exact string equality against the discovery document's `issuer` (§12.4 rule 3). */\n iss: string;\n /** Subject — the authenticated end user's stable identifier at AXIAM. */\n sub: string;\n /** Audience — contains the relying party's `client_id` (§12.4 rule 4). */\n aud: string | string[];\n /** Expiry time (epoch seconds). */\n exp: number;\n /** Issued-at time (epoch seconds). */\n iat: number;\n /** Not-before time (epoch seconds), when the server sends one. */\n nbf?: number;\n /** The `nonce` echoed back from the authorization request (§12.4 rule 6). */\n nonce?: string;\n /** Authorized party — required to equal `client_id` when `aud` holds multiple audiences (§12.4 rule 4). */\n azp?: string;\n /** Any further claim the server sends (e.g. `email`, `preferred_username`) — preserved, never rejected (§12.1). */\n [claim: string]: unknown;\n}\n\n/**\n * What an ID token is checked against by {@link IdTokenVerifier.verifyIdToken}\n * (CONTRACT.md §12.4 rules 3–6).\n */\nexport interface IdTokenExpectations {\n /**\n * The authoritative issuer — always the `issuer` value of the discovery\n * document the token endpoint was read from, never the client base URL\n * (§12.3 rule 6: behind a proxy the two legitimately differ).\n */\n issuer: string;\n /** The relying party's own `client_id`, matched against `aud`/`azp` (rule 4). */\n clientId: string;\n /**\n * The `nonce` returned by `oidcBegin` and passed back into `oidcExchange`.\n *\n * Mandatory for `oidcExchange`. Left `undefined` by `oidcRefresh` and\n * `loginClientCredentials`, which skip rule 6 entirely — OIDC Core §12.2\n * does not require a `nonce` in a refresh-issued ID token.\n */\n nonce?: string;\n /**\n * Permitted clock skew in seconds for `exp`/`iat`/`nbf` (rule 5). Defaults\n * to {@link MAX_CLOCK_SKEW_SEC} and is clamped to it — the contract forbids\n * configuring it *above* 60 s, so a larger value is silently reduced rather\n * than honoured.\n */\n clockSkewSec?: number;\n}\n\n/**\n * Maximum (and default) permitted clock skew in seconds for ID-token time\n * claims. CONTRACT.md §12.4 rule 5 caps this at 60 s and forbids any\n * configuration above the bound.\n */\nexport const MAX_CLOCK_SKEW_SEC = 60;\n\n/**\n * Build the `AuthError` for a §12.4 failure: a stable machine-readable\n * `reason` code plus a human-readable message that — per §12.3 rule 3 and §2's\n * construction rules — never embeds the token, a claim value that could carry\n * secret material, or the expected nonce.\n */\nexport function idTokenAuthError(reason: IdTokenFailureReason, message: string): AuthError {\n return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);\n}\n\n/**\n * Resolve the effective clock skew: the caller's value clamped into\n * `[0, MAX_CLOCK_SKEW_SEC]`, or the maximum when unset.\n */\nexport function resolveClockSkewSec(clockSkewSec?: number): number {\n if (clockSkewSec === undefined) {\n return MAX_CLOCK_SKEW_SEC;\n }\n return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);\n}\n\n/**\n * Constant-time string equality, used for the `nonce` comparison §12.4 rule 6\n * requires. A length mismatch short-circuits to `false` (`timingSafeEqual`\n * throws on unequal-length buffers) — the same idiom\n * `middleware/cookieHeader.ts` and `amqp/hmac.ts` already use.\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8');\n const right = Buffer.from(b, 'utf8');\n if (left.length !== right.length) {\n return false;\n }\n return timingSafeEqual(left, right);\n}\n\n/** Reject the JOSE header `alg` unless it is exactly `EdDSA` (§12.4 rule 1). */\nexport const ID_TOKEN_ALG = 'EdDSA';\n\n/**\n * §12.4 rule 1 — algorithm check, run against the JOSE **header** and BEFORE\n * any signature work, so the token can never select its own verification\n * algorithm. `none` is rejected by the same equality test as every other\n * non-`EdDSA` value; it gets no special case and no separate code path.\n */\nexport function assertIdTokenAlg(alg: unknown): void {\n if (alg !== ID_TOKEN_ALG) {\n throw idTokenAuthError(\n 'invalid_alg',\n `expected alg \"${ID_TOKEN_ALG}\", got ${typeof alg === 'string' ? `\"${alg}\"` : 'no alg header'}`,\n );\n }\n}\n\n/**\n * §12.4 rules 3–6 — issuer, audience, time and nonce checks over an\n * already-signature-verified claim set. Returns the claims unchanged on\n * success; throws the matching `AuthError` reason code on the first failure.\n *\n * @param claims the verified JWT payload.\n * @param expectations issuer/client_id/nonce to check against.\n * @param nowSec current time in epoch seconds — injectable so tests can pin it.\n */\nexport function checkIdTokenClaims(\n claims: IdTokenClaims,\n expectations: IdTokenExpectations,\n nowSec: number = Math.floor(Date.now() / 1000),\n): IdTokenClaims {\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n\n // Rule 3 — exact string comparison. No normalization, no trailing-slash\n // tolerance, no prefix matching.\n if (claims.iss !== expectations.issuer) {\n throw idTokenAuthError('invalid_issuer', 'iss does not equal the discovery document issuer');\n }\n\n // Rule 4 — aud must contain our client_id; with multiple audiences an azp\n // claim must be present and equal to it.\n const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!audiences.includes(expectations.clientId)) {\n throw idTokenAuthError('invalid_audience', 'aud does not contain this client_id');\n }\n if (audiences.length > 1 && claims.azp !== expectations.clientId) {\n throw idTokenAuthError(\n 'invalid_audience',\n 'aud holds multiple audiences and azp is absent or does not equal this client_id',\n );\n }\n\n // Rule 5 — exp must be in the future, iat must not be in the future, nbf is\n // honored when present; all within `skew` seconds. `exp` is treated as\n // REQUIRED: a token with no expiry could never satisfy \"exp must be in the\n // future\", so its absence is an expiry failure rather than a free pass.\n if (typeof claims.exp !== 'number') {\n throw idTokenAuthError('token_expired', 'exp claim is missing or not a number');\n }\n if (claims.exp + skew <= nowSec) {\n throw idTokenAuthError('token_expired', 'exp is in the past');\n }\n if (typeof claims.iat !== 'number') {\n throw idTokenAuthError('token_expired', 'iat claim is missing or not a number');\n }\n if (claims.iat - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'iat is in the future');\n }\n if (typeof claims.nbf === 'number' && claims.nbf - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'nbf is in the future');\n }\n\n // Rule 6 — mandatory for oidcExchange, skipped when the caller supplied no\n // expected nonce (oidcRefresh / loginClientCredentials).\n if (expectations.nonce !== undefined) {\n if (typeof claims.nonce !== 'string' || !constantTimeEquals(claims.nonce, expectations.nonce)) {\n throw idTokenAuthError('nonce_mismatch', 'nonce claim is absent or does not match the request nonce');\n }\n }\n\n return claims;\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist) — for BOTH inbound access tokens (§10\n// middleware) and relying-party ID tokens (§12.4). One verifier, one cached\n// remote key set, two entry points: `verifyAccessToken` and `verifyIdToken`.\n// §12 explicitly forbids forking this module for the OIDC flow.\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nimport { AuthError } from '../core/index.js';\nimport {\n assertIdTokenAlg,\n checkIdTokenClaims,\n ID_TOKEN_ALG,\n idTokenAuthError,\n resolveClockSkewSec,\n type IdTokenClaims,\n type IdTokenExpectations,\n} from './oidcIdToken.js';\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n /**\n * RFC 7800 / RFC 8705 §3.1 confirmation claim — present **only** on a\n * sender-constrained token (CONTRACT.md §10.1 rule 9, contract 1.15).\n *\n * Its presence changes what the token *is*. Without it, the token is a\n * bearer credential: whoever holds it may use it. With it, the token names\n * a key, and accepting it without proving the caller holds that key\n * converts it straight back into a bearer token.\n *\n * {@link Verifier.verifyAccessToken} does **not** check this — it cannot,\n * having no access to the connection's client certificate. Use\n * {@link verifyCertificateBinding}.\n */\n cnf?: CnfClaim;\n}\n\n/**\n * RFC 7800 confirmation claim.\n *\n * Deliberately an object with one optional field rather than a union: RFC 7800\n * permits confirmation methods this SDK does not implement, and such a token\n * must still *parse*. What it must not do is validate — see\n * {@link verifyCertificateBinding}.\n */\nexport interface CnfClaim {\n /**\n * RFC 8705 §3.1 — base64url (unpadded) SHA-256 of the DER client\n * certificate the token was issued to.\n */\n 'x5t#S256'?: string;\n /**\n * RFC 9449 §6.1 — base64url (unpadded) RFC 7638 thumbprint of the DPoP\n * public key the token was issued to (contract 1.16).\n */\n jkt?: string;\n}\n\n/**\n * The proofs a caller can present for a sender-constrained token\n * (contract 1.16, CONTRACT.md §10.1 rule 9).\n *\n * Both fields are optional because a caller may hold one, both or neither —\n * and \"neither\" is legitimate for an ordinary bearer token, which is why\n * {@link verifyTokenBinding} accepts `{}` and returns when the token names no\n * confirmation.\n *\n * @remarks\n * **Every thumbprint must come from the transport.** Take the certificate\n * thumbprint from the TLS peer certificate\n * (`TLSSocket.getPeerCertificate().raw` under Node), or from a *trusted*\n * terminating proxy over a channel your application controls. Never from a\n * caller-settable header: a forgeable input makes the mechanism decorative.\n */\nexport interface PresentedProofs {\n /** RFC 8705 §3.1 `x5t#S256` of the peer certificate on this connection. */\n certificateThumbprint?: string;\n /**\n * RFC 9449 §6.1 `jkt` of the key that signed a DPoP proof this SDK has\n * **already verified** for this request's `htm`/`htu`.\n *\n * Supplying a value here asserts the proof checked out. A thumbprint lifted\n * off an unverified proof would let a proof captured from any other\n * endpoint authorize this request.\n */\n dpopThumbprint?: string;\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * the certificate the caller presented on **this** connection\n * (RFC 8705 §3, contract 1.15).\n *\n * `presentedThumbprint` is the RFC 8705 §3.1 `x5t#S256` of the peer\n * certificate: base64url, **unpadded**, SHA-256 over the **DER** encoding.\n * {@link certificateThumbprintS256} computes it from DER bytes.\n *\n * | token's `cnf` | `presentedThumbprint` | result |\n * |---|---|---|\n * | absent | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | returns |\n * | `x5t#S256` | different, or `undefined` | **throws** |\n * | present, no `x5t#S256` | anything | **throws** |\n *\n * The first row is why adopting this rule breaks nothing: an unbound token is\n * still accepted whether or not a certificate is present. The last row is the\n * one that is easy to get wrong — a `cnf` naming a method this SDK cannot\n * check is an *unverifiable constraint*, never *no constraint*. Read the\n * other way, a sender-constrained token silently degrades to a bearer token\n * the day a newer AXIAM issues a confirmation this SDK predates.\n *\n * @remarks\n * **The thumbprint must come from the transport.** Take it from the TLS peer\n * certificate (`TLSSocket.getPeerCertificate().raw` under Node) or from a\n * value a *trusted* terminating proxy forwarded over a channel your\n * application controls. Never from a caller-settable request header: a\n * forgeable input makes the whole mechanism decorative.\n *\n * @throws {Error} on any of the three rejecting rows. The §10 middleware\n * wraps this into an `AuthError`.\n */\nexport function verifyCertificateBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n presentedThumbprint: string | undefined,\n): void {\n const cnf = claims.cnf;\n if (cnf === undefined || cnf === null) return;\n\n const expected = cnf['x5t#S256'];\n if (typeof expected !== 'string' || expected.length === 0) {\n // Includes the DPoP case: this entry point has no proof to check, so a\n // `jkt`-bound token is refused rather than silently downgraded.\n throw new Error(\n 'token carries a cnf confirmation naming a method this entry point cannot verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one; ' +\n 'use verifyTokenBinding for DPoP)',\n );\n }\n // A token naming BOTH methods is a conjunction (contract 1.16): this\n // function can establish one half and must not answer for the whole.\n // Refusing here is what stops \"check whichever we can\".\n if (typeof cnf.jkt === 'string' && cnf.jkt.length > 0) {\n throw new Error(\n 'token names both a certificate and a DPoP key; both must hold ' +\n '(CONTRACT.md §10.1 rule 9) — use verifyTokenBinding',\n );\n }\n if (presentedThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expected, presentedThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * **every** proof the caller presented (contract 1.16).\n *\n * This is the full rule, and the one to use unless your transport genuinely\n * cannot produce a DPoP thumbprint.\n *\n * | token's `cnf` | certificate | DPoP | result |\n * |---|---|---|---|\n * | absent | anything | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | ignored | returns |\n * | `x5t#S256` | different or absent | ignored | **throws** |\n * | `jkt` | ignored | equal | returns |\n * | `jkt` | ignored | different or absent | **throws** |\n * | both | equal | equal | returns — **conjunction** |\n * | both | either wrong or missing | — | **throws** |\n * | present, names neither | anything | anything | **throws** |\n *\n * Two rows carry the weight. **Both present is a conjunction**: an operator\n * who turned on two constraints asked for two, and satisfying the more\n * convenient one is not compliance. **Names neither is a refusal**: a\n * confirmation this SDK cannot interpret is an unverifiable constraint, and\n * reading it as \"unconstrained\" is the exact downgrade rule 9 exists to\n * prevent. That includes an *empty* `cnf` — which is also how proto3 delivers\n * an empty `CnfClaim` over gRPC (§10.3 rule 3).\n *\n * @remarks\n * This function compares thumbprints; it does **not** verify proofs. Supply\n * `dpopThumbprint` only after checking the proof's signature, `htm`, `htu`,\n * `iat` and `jti` for *this* request.\n *\n * @throws {Error} on any rejecting row. The §10 middleware wraps this into an\n * `AuthError`.\n */\nexport function verifyTokenBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n proofs: PresentedProofs = {},\n): void {\n const cnf = claims.cnf;\n // The fast path, and the common one. First on purpose: an unbound token is\n // accepted with no proofs at all, which is what keeps existing deployments\n // working when a guard adopts this rule.\n if (cnf === undefined || cnf === null) return;\n\n const expectedCert = typeof cnf['x5t#S256'] === 'string' && cnf['x5t#S256'].length > 0\n ? cnf['x5t#S256']\n : undefined;\n const expectedJkt = typeof cnf.jkt === 'string' && cnf.jkt.length > 0 ? cnf.jkt : undefined;\n\n if (expectedCert === undefined && expectedJkt === undefined) {\n throw new Error(\n 'token carries a cnf confirmation naming no method this SDK can verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one)',\n );\n }\n\n // Each arm that applies must pass. Written as two independent checks rather\n // than a switch on the pair precisely so \"both named\" needs no branch of its\n // own — it is simply the case where both run.\n if (expectedCert !== undefined) {\n if (proofs.certificateThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expectedCert, proofs.certificateThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n }\n\n if (expectedJkt !== undefined) {\n if (proofs.dpopThumbprint === undefined) {\n throw new Error('token is DPoP-bound but no verified DPoP proof was presented');\n }\n if (!constantTimeEqual(expectedJkt, proofs.dpopThumbprint)) {\n throw new Error('token is bound to a different DPoP key than the one presented');\n }\n }\n}\n\n/**\n * Constant-time string comparison for {@link verifyCertificateBinding}.\n *\n * The thumbprint is usually public — it derives from a certificate sent in the\n * clear during the handshake — so this is defence in depth. It matters most\n * for a self-signed client, where the registered thumbprint is the whole\n * credential. Hand-rolled rather than `crypto.timingSafeEqual` so that this\n * function stays usable in the browser build, where `node:crypto` is absent.\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n // Length inequality short-circuits, leaking only the length. Both operands\n // are fixed-length base64url SHA-256 digests whenever either is well-formed.\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i += 1) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/**\n * Compute the RFC 8705 §3.1 `x5t#S256` thumbprint of a DER client\n * certificate: base64url-encoded SHA-256, **without** padding.\n *\n * Unpadded is not a style choice — RFC 7515 §2 defines base64url in JOSE as\n * omitting `=`, and a padded value will not compare equal to what AXIAM put in\n * the token.\n *\n * Node only (it needs `node:crypto`). A browser-side guard has no peer\n * certificate to fingerprint in the first place.\n */\nexport async function certificateThumbprintS256(der: Uint8Array): Promise<string> {\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(der).digest('base64url');\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/**\n * Clock-skew leeway applied to the `exp` and `nbf` checks (CONTRACT.md §10.1\n * rule 7).\n *\n * A **named, bounded, non-configurable** constant, fixed at the contract's\n * RECOMMENDED 60 seconds. Rule 7 forbids both an inline literal and an\n * operator-settable value that could be widened without bound, so there is\n * deliberately no option to override it — widening the window is a source\n * change, reviewable as such.\n */\nexport const CLOCK_SKEW_LEEWAY_SEC = 60;\n\n/**\n * The verification policy {@link Verifier.verifyAccessToken} enforces, per\n * CONTRACT.md §10.1.\n *\n * `expectedTenantId` is **required** (rule 4): the `/oauth2/jwks` trust\n * anchor is organization-wide, so a valid signature proves only \"some tenant\n * in this organization\". `expectedIssuer` and `expectedAudience` are\n * **conditional** (rules 5 and 6) — omitted means the check is not performed,\n * and the SDK never assumes a default issuer.\n */\nexport interface AccessTokenExpectations {\n /**\n * §10.1 rule 4 — the tenant this resource server is configured for. The\n * token's `tenant_id` claim MUST equal it; an absent claim, an empty\n * expectation, or a mismatch all reject (fail closed).\n */\n expectedTenantId: string;\n /** §10.1 rule 5 — expected `iss`. Omit for no issuer check. */\n expectedIssuer?: string;\n /**\n * §10.1 rule 6 — expected `aud`. Omit for no audience check. A resource\n * server guarding user-facing routes SHOULD pass `\"axiam:user\"`.\n */\n expectedAudience?: string;\n}\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /**\n * Verify `token` against the **complete** CONTRACT.md §10.1 minimum\n * local-verification set and return its claims.\n *\n * | § | rule | how it is enforced |\n * |---|---|---|\n * | 1 | signature | `algorithms: ['EdDSA']` is checked by `jose` against the JWS header *before* the remote key set function is invoked, so `alg: none` and an HS-signed token bearing an EdDSA `kid` are rejected without a key lookup. |\n * | 2 | `exp` | `requiredClaims: ['exp']` — `jose` only checks `exp` *if present* by default, so an absent `exp` (a permanent credential) would otherwise sail through. A non-numeric `exp` is rejected by `jose`'s own type check. |\n * | 3 | `nbf` | honoured by `jose` when present, bounded by {@link CLOCK_SKEW_LEEWAY_SEC}. |\n * | 4 | `tenant_id` | asserted against {@link AccessTokenExpectations.expectedTenantId}; absent claim, absent expectation, or mismatch all reject. |\n * | 5 | `iss` | checked only when `expectedIssuer` is supplied. |\n * | 6 | `aud` | checked only when `expectedAudience` is supplied. |\n * | 7 | clock skew | {@link CLOCK_SKEW_LEEWAY_SEC}, passed as `clockTolerance`. |\n *\n * Rejects with the underlying error on any failed rule; the §10 middleware\n * wraps that into an `AuthError`.\n */\n verifyAccessToken(token: string, expectations: AccessTokenExpectations): Promise<AxiamClaims>;\n\n /**\n * Verify **only** the EdDSA signature of `token` — CONTRACT.md §10.1's\n * \"raw signature-only primitive\".\n *\n * @remarks\n * **This is not a guard.** It performs no `exp`, `nbf`, `tenant_id`, `iss`\n * or `aud` check whatsoever: an expired token, a not-yet-valid token, and a\n * token minted for a *different tenant* in the same organization all pass.\n * It exists only for integrators deliberately implementing their own\n * policy on top of the signature — the `Unchecked` suffix is there to make\n * that omission obvious at the call site. Anything guarding a route MUST\n * use {@link Verifier.verifyAccessToken} (or, better, the §10 middleware\n * built on it).\n */\n verifySignatureOnlyUnchecked(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * The relying-party half of the same verifier (CONTRACT.md §12.4): validates\n * an OIDC **ID token** rather than an AXIAM access token.\n *\n * @remarks\n * Kept as its own interface, and *added* to the object {@link createVerifier}\n * returns rather than to {@link Verifier} itself, so existing code that\n * implements `Verifier` (e.g. a hand-rolled test double supplied as\n * `VerifiableSession.jwksVerifier`) keeps compiling — contract 1.4 is\n * additive.\n */\nexport interface IdTokenVerifier {\n /**\n * Validate an OIDC ID token per CONTRACT.md §12.4 and return its claims.\n *\n * Enforces rule 1 (`alg` MUST be `EdDSA`, read from the header *before* any\n * signature work — `none` and every other algorithm rejected), rule 2\n * (Ed25519 signature against the key selected by `kid`, with the single\n * JWKS re-fetch policy §10 already implements), then rules 3–6 via\n * {@link checkIdTokenClaims}. Rejects with `AuthError` carrying the\n * matching §12.3 reason code on the first failure.\n */\n verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims>;\n}\n\n/**\n * The concrete verifier {@link createVerifier} / {@link createJwksVerifier}\n * return: one object, one cached remote key set, both the §10 access-token\n * path and the §12.4 ID-token path. §12 forbids a second verifier.\n */\nexport interface JwksVerifier extends Verifier, IdTokenVerifier {}\n\n/**\n * Build a verifier bound to `{baseUrl}/oauth2/jwks`.\n *\n * `jose` is loaded lazily via dynamic `import()` (Pitfall 1 — CJS-safe); the\n * remote JWKS itself is also fetched/cached lazily by `jose`, not eagerly\n * here.\n *\n * For the relying-party (§12) flow use {@link createJwksVerifier} with the\n * `jwks_uri` the discovery document advertises instead of hardcoding\n * {@link JWKS_PATH} — §12.3 rule 6 requires reading the URI from the document.\n */\nexport function createVerifier(baseUrl: string): JwksVerifier {\n return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);\n}\n\n/**\n * Build a verifier bound to an explicit, absolute JWKS URI — the `jwks_uri`\n * value taken from the OIDC discovery document (CONTRACT.md §12.3 rule 6).\n *\n * Identical machinery to {@link createVerifier}: one lazily-resolved\n * `createRemoteJWKSet` singleton per verifier instance, shared by\n * `verifyAccessToken` and `verifyIdToken`.\n */\nexport function createJwksVerifier(jwksUri: string): JwksVerifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // the same createRemoteJWKSet cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent invalid-`kid` burst\n // against a cold cache must collapse to exactly ONE network fetch. Proven\n // (not just assumed) by `test/node/jwks.test.ts`'s \"collapses N concurrent\n // verifyAccessToken calls ... to exactly one JWKS fetch\" test, which mocks\n // global `fetch` with a call counter and fires 8 concurrent calls: jose's\n // `createRemoteJWKSet` (see jose's `RemoteJWKSet.reload()`,\n // `this.#pendingFetch ||= fetchJwks(...).then(...)`) ALREADY holds its own\n // internal lazy-promise-singleton around the underlying fetch, so\n // concurrent callers reaching a cold/unknown-kid getter share the same\n // in-flight fetch promise natively — no additional `inFlightFetch` guard\n // is added here (it would be redundant). If a future `jose` upgrade\n // removes that internal guarantee, the burst test above will start\n // failing and an explicit guard (mirroring `jwksPromise`'s shape) must be\n // added at that point.\n let jwksPromise: Promise<ReturnType<typeof import('jose').createRemoteJWKSet>> | null = null;\n\n async function getJwks() {\n if (!jwksPromise) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n jwksPromise = import('jose').then(({ createRemoteJWKSet }) =>\n createRemoteJWKSet(new URL(jwksUri), {\n cooldownDuration: COOLDOWN_DURATION_MS,\n timeoutDuration: TIMEOUT_DURATION_MS,\n }),\n );\n }\n return jwksPromise;\n }\n\n return {\n async verifyAccessToken(\n token: string,\n expectations: AccessTokenExpectations,\n ): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // §10.1 rule 1: explicit algorithm allowlist — never trust the token's\n // own `alg` header; defense against algorithm-confusion attacks\n // (T-17-14). jose checks this against the JWS protected header BEFORE\n // it calls the remote-key-set resolver, so `alg: none` and an HS256\n // token carrying our EdDSA `kid` both die without a key lookup.\n //\n // §10.1 rule 2: `requiredClaims: ['exp']` is load-bearing and NOT a\n // jose default — jose validates `exp` only `if (payload.exp !==\n // undefined)`, so a token minted with no `exp` at all (a permanent\n // credential) would otherwise verify. This is precisely the SEC-080\n // defect. A present-but-non-numeric `exp` is rejected by jose's own\n // `\"exp\" claim must be a number` check.\n //\n // §10.1 rules 5/6: `issuer`/`audience` are passed ONLY when configured\n // — supplying them also makes jose require the corresponding claim to\n // be present, which is the intended fail-closed behaviour; omitting\n // them means no check, per the conditional wording of the rules.\n //\n // §10.1 rules 3/7: jose honours `nbf` when present; `clockTolerance`\n // bounds both the `exp` and the `nbf` comparison.\n const { payload } = await jwtVerify(token, jwks, {\n algorithms: ['EdDSA'],\n requiredClaims: ['exp'],\n clockTolerance: CLOCK_SKEW_LEEWAY_SEC,\n ...(expectations.expectedIssuer !== undefined\n ? { issuer: expectations.expectedIssuer }\n : {}),\n ...(expectations.expectedAudience !== undefined\n ? { audience: expectations.expectedAudience }\n : {}),\n });\n\n // §10.1 rule 4 — the tenant assertion, which no JWT library can do for\n // us: `tenant_id` is an AXIAM claim, and the JWKS trust anchor is\n // organization-wide. Fails closed on all three failure shapes: no\n // configured tenant, an absent/ill-typed claim, and a mismatch.\n // \"Nothing to compare against, so nothing to check\" is the SEC-080\n // defect, not a pass.\n assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);\n\n return payload as unknown as AxiamClaims;\n },\n\n async verifySignatureOnlyUnchecked(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Signature + algorithm pinning ONLY — see the interface docs. No\n // `requiredClaims`, no `clockTolerance`, and deliberately no tenant\n // assertion. `jose` still refuses an *expired* token here because its\n // `exp` check is unconditional when the claim is present; a token with\n // no `exp` at all is accepted, which is exactly why this entry point\n // must never guard a route.\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n\n async verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims> {\n const { decodeProtectedHeader, jwtVerify } = await import('jose');\n\n // §12.4 rule 1 — read `alg` from the header and reject anything but\n // EdDSA BEFORE touching the JWKS or the signature. A malformed token\n // (not three base64url segments) cannot even yield a header, which is\n // itself an `invalid_alg` failure: no algorithm was assertable.\n let header: { alg?: string; kid?: string };\n try {\n header = decodeProtectedHeader(token);\n } catch {\n throw idTokenAuthError('invalid_alg', 'token is not a well-formed JWS');\n }\n assertIdTokenAlg(header.alg);\n\n // §12.4 rule 2 — a token with no `kid` is rejected outright: there is\n // no key to select, and guessing \"the only key\" would defeat rotation.\n if (!header.kid) {\n throw idTokenAuthError('unknown_kid', 'token carries no kid header');\n }\n\n const jwks = await getJwks();\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n let claims: IdTokenClaims;\n try {\n // `algorithms` is passed again (belt and braces with rule 1) so jose\n // can never be talked into another algorithm either. `clockTolerance`\n // keeps jose's own exp/nbf checks aligned with rule 5's bound; the\n // explicit re-checks in checkIdTokenClaims cover iat and give each\n // failure its own reason code.\n const { payload } = await jwtVerify(token, jwks, {\n algorithms: [ID_TOKEN_ALG],\n clockTolerance: skew,\n });\n claims = payload as unknown as IdTokenClaims;\n } catch (err) {\n throw mapJoseVerifyError(err);\n }\n\n return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });\n },\n };\n}\n\n/**\n * CONTRACT.md §10.1 rule 4 — assert the token's `tenant_id` claim against the\n * tenant the relying party is configured for.\n *\n * Exported so the §10 middleware can re-assert it on the guard side, where it\n * cannot be bypassed by a caller-supplied {@link Verifier} implementation\n * that ignores its expectations.\n *\n * @param claim - the raw `tenant_id` claim value off the verified payload.\n * @param expected - the configured tenant.\n * @throws AuthError when no tenant is configured, when the claim is absent or\n * not a non-empty string, or when the two differ.\n */\nexport function assertTenantClaim(claim: unknown, expected: string | undefined): void {\n if (typeof expected !== 'string' || expected === '') {\n throw new AuthError(\n 'no configured tenant to verify the token against; refusing the request ' +\n '(CONTRACT.md §10.1 rule 4 fails closed)',\n );\n }\n if (typeof claim !== 'string' || claim === '') {\n throw new AuthError('invalid tenant_id claim');\n }\n if (claim !== expected) {\n warnOnceIfComparandLooksLikeASlug(claim, expected);\n throw new AuthError('token tenant_id does not match configured tenant');\n }\n}\n\n/** Canonical 8-4-4-4-12 hex UUID shape. Shape only — no version/variant check. */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Latches {@link warnOnceIfComparandLooksLikeASlug} to one emission per process. */\nlet slugComparandWarned = false;\n\n/**\n * Test seam: reset the once-per-process latch so each test observes its own\n * behaviour rather than a previous test's.\n *\n * @internal\n */\nexport function resetTenantComparandWarningForTests(): void {\n slugComparandWarned = false;\n}\n\n/**\n * Name the slug-vs-UUID misconfiguration explicitly (§13.4 observation 6).\n *\n * AXIAM access tokens carry the tenant **UUID** in `tenant_id`, but this SDK's\n * client is commonly configured with a tenant **slug**. A guard handed that slug\n * rejects 100% of traffic — fail-closed and safe, but it presents as \"every\n * token is invalid\" with nothing pointing at the cause, which is a miserable\n * thing to debug.\n *\n * Deliberately: emitted **once per process**, so it is a configuration\n * diagnostic and not a log-flood sink an attacker can drive with bad tokens;\n * keyed on the **shape of the operator-configured value**, never on anything a\n * caller supplies, so it cannot be triggered on demand; and emitted **after**\n * the rejection is decided, so it only ever explains a failure and the\n * verification outcome is byte-for-byte unchanged.\n *\n * A UUID-vs-UUID mismatch is a genuine cross-tenant rejection and stays silent.\n */\nfunction warnOnceIfComparandLooksLikeASlug(claim: string, expected: string): void {\n if (slugComparandWarned) return;\n if (!UUID_RE.test(claim) || UUID_RE.test(expected)) return;\n\n slugComparandWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM: the tenant this guard was configured with (\"${expected}\") is not a UUID, ` +\n 'but access tokens carry the tenant UUID in their `tenant_id` claim, so this guard ' +\n 'will reject every request. Configure it with the tenant UUID, not the slug. ' +\n '(CONTRACT.md §10.1 rule 4; logged once per process, and it does not affect the ' +\n 'rejection itself.)',\n );\n}\n\n/**\n * Translate a `jose` verification failure into the §12.3 reason-code\n * vocabulary. jose's error `code` strings are stable public API\n * (`ERR_JWKS_NO_MATCHING_KEY`, `ERR_JWT_EXPIRED`, …); anything unrecognized\n * degrades to `invalid_signature`, the safest catch-all — an unclassifiable\n * verification failure is never treated as success.\n */\nfunction mapJoseVerifyError(err: unknown): AuthError {\n const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : '';\n switch (code) {\n case 'ERR_JWKS_NO_MATCHING_KEY':\n // jose has already performed its single re-fetch-then-fail dance here\n // (createRemoteJWKSet reloads once per cooldown window on an unmatched\n // kid) — exactly the §12.4 rule 2 / §10 policy.\n return idTokenAuthError('unknown_kid', 'no JWKS key matches the token kid');\n case 'ERR_JWT_EXPIRED':\n return idTokenAuthError('token_expired', 'exp is in the past');\n case 'ERR_JWT_CLAIM_VALIDATION_FAILED':\n return idTokenAuthError('token_expired', 'a time-based claim (nbf/iat) is not yet valid');\n default:\n return idTokenAuthError('invalid_signature', 'signature verification failed');\n }\n}\n","// createNodeSession — extends the 17-02 SharedSession with the Node\n// persona's auth internals (D-13).\n//\n// Builds the same REST SharedSession the browser persona uses, then swaps\n// in a tough-cookie jar (via wrapAxios) so httpOnly Set-Cookie tokens\n// persist, and attaches a TokenManager + JWKS verifier. This is the ONE\n// shared session object gRPC (interceptor.ts/callWithRefresh.ts) and REST\n// both operate on — the single-flight refresh guard (`session.refreshGuard`,\n// a per-session instance created in the SharedSession constructor, CR-02)\n// is therefore transparently shared across both transports FOR THIS\n// SESSION ONLY, since both call it with an equivalent `POST\n// /api/v1/auth/refresh` closure. A different NodeSession/SharedSession\n// instance gets its own independent guard — refreshes never cross-wire\n// between sessions.\n\nimport type { CookieJar } from 'tough-cookie';\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, resolveNodeTlsOptions, SharedSession } from '../rest/session.js';\nimport { AxiamClient } from '../rest/client.js';\nimport { CSRF_COOKIE, createJar, extractCookieValue, wrapAxios } from './cookieJar.js';\nimport { TokenManager } from './tokenManager.js';\nimport { createVerifier, type Verifier } from './jwks.js';\n\n/** Node-only {@link SharedSession} adding a {@link TokenManager} and a JWKS {@link Verifier} for local (offline) access-token verification. */\nexport class NodeSession extends SharedSession {\n /** Manages the access/refresh token pair backing this session. */\n readonly tokenManager: TokenManager;\n /** Local JWKS verifier for validating access tokens without a server round-trip. */\n readonly jwksVerifier: Verifier;\n readonly #jar: CookieJar;\n\n constructor(\n options: AxiamClientOptions,\n base: SharedSession,\n tokenManager: TokenManager,\n jwksVerifier: Verifier,\n jar: CookieJar,\n ) {\n super(options, base.axios, base.tenantHeaderValue);\n this.tokenManager = tokenManager;\n this.jwksVerifier = jwksVerifier;\n this.#jar = jar;\n }\n\n /**\n * Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this\n * session's per-instance `refreshGuard` (inherited from SharedSession) by\n * both REST's reactive interceptor (rest/interceptors.ts) and gRPC's\n * callWithRefresh — since `refreshGuard` is scoped to THIS session\n * instance (CR-02, D-13), both transports share exactly one in-flight\n * refresh for this session regardless of which one triggers it, while\n * remaining fully independent from any other session's guard.\n */\n doRefresh = async (): Promise<void> => {\n await this.axios.post('/api/v1/auth/refresh', this.buildRefreshBody());\n await this.tokenManager.syncFromJar();\n // A rotated access token may carry a new tenant_id/org_id — keep the\n // resolved refresh identifiers current for the next refresh.\n this.#resolveIdentifiersFromToken();\n // The refresh response may rotate the axiam_csrf cookie — resync\n // session.csrfToken from the jar so the next state-changing request\n // still forwards a valid X-CSRF-Token (CR-01).\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a\n * successful login()/verifyMfa(). Refreshes the cached access token (so\n * the gRPC interceptor's synchronous fast-path is current immediately\n * after login) and reads the `axiam_csrf` cookie out of the jar into\n * `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.\n */\n onAuthenticated = async (): Promise<void> => {\n await this.tokenManager.syncFromJar();\n // D-14: resolve the authoritative tenant_id/org_id UUIDs from the freshly\n // issued access token so refresh() can supply them (RefreshRequest needs\n // the UUID form, and the client may have been constructed with slugs).\n this.#resolveIdentifiersFromToken();\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Populate `resolvedTenantId`/`resolvedOrgId` from the cached access token's\n * claims when present, leaving any UUID resolved from construction options in\n * place otherwise. Best-effort and unverified (see\n * TokenManager.claimsFromCachedToken) — used purely to build the refresh body.\n */\n #resolveIdentifiersFromToken(): void {\n const { tenantId, orgId } = this.tokenManager.claimsFromCachedToken();\n if (tenantId) {\n this.resolvedTenantId = tenantId;\n this.tokenManager.setTenantId(tenantId);\n }\n if (orgId) {\n this.resolvedOrgId = orgId;\n }\n }\n\n async #syncCsrfFromJar(): Promise<void> {\n this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);\n }\n}\n\n/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */\nexport function createNodeSession(options: AxiamClientOptions): NodeSession {\n const base = createSession(options);\n const jar = createJar();\n // Hand the §6/§6.1 TLS material to the jar-aware agent. createSession's own\n // `https.Agent` is unusable here — a cookie agent must own the socket — so\n // this is the ONLY place a customCa or client certificate reaches the wire\n // under the Node persona. See wrapAxios' doc comment.\n wrapAxios(base.axios, jar, resolveNodeTlsOptions(options));\n\n const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);\n const jwksVerifier = createVerifier(options.baseUrl);\n\n return new NodeSession(options, base, tokenManager, jwksVerifier, jar);\n}\n\n/**\n * Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node\n * counterpart to `new AxiamClient(options)` (which builds the browser\n * `SharedSession` with no cookie jar): it constructs a `NodeSession`\n * (tough-cookie jar + CSRF/refresh token sync) and adopts it via the\n * `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens\n * from login/refresh persist and every post-login REST call authenticates\n * correctly under Node.\n *\n * Lives in this Node-only module (reachable via the `axiam-sdk/node` and\n * `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`\n * entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).\n * The returned client shares the single session with any `AuthzGrpcClient`\n * built from the same `NodeSession`.\n */\nexport function createNodeClient(options: AxiamClientOptions): AxiamClient {\n return new AxiamClient(options, createNodeSession(options));\n}\n"]}
1
+ {"version":3,"sources":["../../src/grpc/interceptor.ts","../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/core/decisionMemo.ts","../../src/core/telemetry.ts","../../src/core/telemetryReporter.ts","../../src/grpc/callWithRefresh.ts","../../src/grpc/client.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/management/manifest/plan.ts","../../src/management/manifest/engine.ts","../../src/management/page.ts","../../src/management/errors.ts","../../src/management/request.ts","../../src/management/scope.ts","../../src/management/ops/organizations.ts","../../src/management/ops/tenants.ts","../../src/management/models.ts","../../src/management/ops/users.ts","../../src/management/ops/groups.ts","../../src/management/ops/roles.ts","../../src/management/ops/permissions.ts","../../src/management/ops/resources.ts","../../src/management/ops/scopes.ts","../../src/management/ops/service_accounts.ts","../../src/management/ops/certificates.ts","../../src/management/ops/ca_certificates.ts","../../src/management/ops/pgp_keys.ts","../../src/management/ops/webhooks.ts","../../src/management/ops/oauth2_clients.ts","../../src/management/ops/federation.ts","../../src/management/ops/notification_rules.ts","../../src/management/ops/email_config.ts","../../src/management/ops/settings.ts","../../src/management/ops/scim_tokens.ts","../../src/management/ops/reactors.ts","../../src/management/ops/webauthn_policy.ts","../../src/management/ops/audit.ts","../../src/management/ops/privacy.ts","../../src/management/ops/platform.ts","../../src/management/ops/index.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../../src/node/tokenManager.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/node/session.ts"],"names":["grpc","grpc2","axios","response","wire","axiosStatus","post","expose","serverMessage","statusOf","CookieJar","HttpCookieAgent","HttpsCookieAgent","timingSafeEqual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,CAAC,SAAS,QAAA,KAAa;AAC5B,IAAA,OAAO,IAASA,gBAAA,CAAA,gBAAA,CAAiB,QAAA,CAAS,OAAO,CAAA,EAAG;AAAA,MAClD,KAAA,CAAM,QAAA,EAAU,QAAA,EAAU,IAAA,EAAM;AAE9B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EAAO;AACT,MAAA,IAAA,CAAK,aAAA,GAAgB,KAAA;AAAA,IACvB;AAAA,EACF;AAAA,EAEA,MAAM,gBAAA,GAAkC;AACtC,IAAA,IAAA,CAAK,YAAY,MAAM,kBAAA,CAAmB,KAAK,IAAA,EAAM,IAAA,CAAK,SAAS,WAAW,CAAA;AAAA,EAChF;AACF;AAGO,SAAS,kBAAkB,OAAA,EAA0C;AAC1E,EAAA,MAAM,IAAA,GAAO,cAAc,OAAO,CAAA;AAClC,EAAA,MAAM,MAAM,SAAA,EAAU;AAKtB,EAAA,SAAA,CAAU,IAAA,CAAK,KAAA,EAAO,GAAA,EAAK,qBAAA,CAAsB,OAAO,CAAC,CAAA;AAEzD,EAAA,MAAM,eAAe,IAAI,YAAA,CAAa,KAAK,OAAA,CAAQ,OAAA,EAAS,KAAK,iBAAiB,CAAA;AAClF,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,CAAQ,OAAO,CAAA;AAEnD,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,IAAA,EAAM,YAAA,EAAc,cAAc,GAAG,CAAA;AACvE;AAiBO,SAAS,iBAAiB,OAAA,EAA0C;AACzE,EAAA,OAAO,IAAI,WAAA,CAAY,OAAA,EAAS,iBAAA,CAAkB,OAAO,CAAC,CAAA;AAC5D","file":"index.js","sourcesContent":["// Synchronous auth/tenant grpc-js interceptor (D-10, Pitfall 3).\n//\n// grpc-js's `start(metadata, listener, next)` callback is SYNCHRONOUS —\n// unlike tonic's async-native interceptor trait, it must call\n// `next(metadata, listener)` without ever awaiting. This interceptor\n// therefore only reads the TokenManager's non-blocking, in-memory cached\n// access token (populated by `syncFromJar()` after REST calls/refresh) —\n// it NEVER triggers a refresh itself. UNAUTHENTICATED handling belongs to\n// the async call-wrapper (callWithRefresh.ts), never here.\n//\n// Mirrors the Rust SDK's src/grpc/interceptor.rs exactly, adapted to grpc-js's\n// structurally different (non-tower) interceptor API\n// (RESEARCH.md Area 3 / grpc/proposal L5-node-client-interceptors.md).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { Interceptor } from '@grpc/grpc-js';\nimport type { NodeSession } from '../node/session.js';\n\n/**\n * Injects `authorization: Bearer <token>` (when a cached token is present)\n * and `x-tenant-id` metadata on every outgoing RPC (CONTRACT.md §5). Never\n * logs the token — `expose()` is only called at this metadata-insertion\n * boundary.\n */\nexport function authInterceptor(session: NodeSession): Interceptor {\n return (options, nextCall) => {\n return new grpc.InterceptingCall(nextCall(options), {\n start(metadata, listener, next) {\n // Non-blocking cached-token read — NEVER await here (Pitfall 3).\n const token = session.tokenManager.cachedAccessToken();\n if (token) {\n metadata.add('authorization', `Bearer ${token.expose()}`);\n }\n metadata.add('x-tenant-id', session.tenantHeaderValue);\n next(metadata, listener);\n },\n });\n };\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// 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","// UNAUTHENTICATED single-flight-retry wrapper (D-10/D-13, CONTRACT.md §9).\n//\n// The interceptor (interceptor.ts) is synchronous and never triggers a\n// refresh (Pitfall 3). This ASYNC call-site wrapper is where\n// UNAUTHENTICATED handling actually lives: on a caught error whose\n// `.code === GrpcStatus.UNAUTHENTICATED`, it awaits the session's\n// per-instance single-flight refresh guard (`session.refreshGuard` — the\n// SAME guard instance the REST transport for this session uses, D-13, but\n// NEVER shared with a different session, CR-02), resyncs the interceptor's\n// cached-token fast-path via `syncFromJar()`, then retries the call exactly\n// once. A second UNAUTHENTICATED (or any other error) maps through\n// `mapGrpcStatusToError` and rethrows — no further retry (§9.3).\n\nimport { GrpcStatus, mapGrpcStatusToError, type AxiamError } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\n\ninterface GrpcServiceErrorLike {\n code?: number;\n message?: string;\n}\n\nfunction isGrpcServiceError(err: unknown): err is GrpcServiceErrorLike {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n/**\n * Await `fn()`. On a gRPC UNAUTHENTICATED (16) error, drive the shared\n * single-flight refresh, sync the token cache from the jar, and retry `fn()`\n * exactly once. Any other error (or a second UNAUTHENTICATED) is mapped to\n * an AxiamError via `mapGrpcStatusToError` and rethrown.\n */\nexport async function callWithRefresh<T>(session: NodeSession, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (isGrpcServiceError(err) && err.code === GrpcStatus.UNAUTHENTICATED) {\n await session.refreshGuard(session.doRefresh);\n await session.tokenManager.syncFromJar();\n try {\n return await fn();\n } catch (retryErr) {\n throw toAxiamError(retryErr);\n }\n }\n throw toAxiamError(err);\n }\n}\n\nfunction toAxiamError(err: unknown): AxiamError | unknown {\n if (isGrpcServiceError(err) && typeof err.code === 'number') {\n return mapGrpcStatusToError(err.code, err.message ?? 'gRPC call failed');\n }\n return err;\n}\n","// gRPC AuthorizationService client — reused channel, checkAccess/batchCheck\n// (D-10/D-13, SC#2 Node half).\n//\n// The generated ts-proto stubs (`src/gen`, produced by `buf generate` at\n// build time — Phase 15 D-01/D-20) are NOT committed and are unavailable in\n// this sandbox (no `buf` CLI). Rather than importing from a path that does\n// not exist here, this module (a) defines local wire-shape interfaces that\n// exactly mirror `proto/axiam/v1/authorization.proto`, and (b) builds the\n// gRPC client dynamically via grpc-js's own `makeClientConstructor` (the\n// same primitive ts-proto's `outputServices=grpc-js` stubs are built on top\n// of) rather than importing a generated class. A buf-enabled build can swap\n// `buildAuthorizationServiceClient` below for the real ts-proto-generated\n// `AuthorizationServiceClient` from `../gen/...` with NO change to the\n// public `AuthzGrpcClient` surface, since both satisfy the same\n// `WireAuthorizationServiceClient` shape by construction (same .proto).\n// End-to-end wiring against real generated stubs is deferred to a\n// buf-enabled CI run (RESEARCH.md D-20; environment note in this plan).\n\nimport * as grpc from '@grpc/grpc-js';\nimport type { AccessDecision, ClientIdentity } from '../core/index.js';\nimport { AuthError, resolveClientIdentity } from '../core/index.js';\nimport type { NodeSession } from '../node/session.js';\nimport { authInterceptor } from './interceptor.js';\nimport { callWithRefresh } from './callWithRefresh.js';\n\n// Re-exported (not re-declared) so `grpc/index.ts` can still export\n// `AccessDecision` from `./client.js` — see `core/authz.ts` for the single\n// shared definition (SDK-Q10, C2).\nexport type { AccessDecision };\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/authorization.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\nexport interface WireCheckAccessRequest {\n tenant_id: string;\n // `subject_id` is a plain (non-`optional`) proto3 string\n // (`proto/axiam/v1/authorization.proto`), unlike `scope` below. As of\n // contract 1.19 (SDK-Q10) an **empty** value means \"the subject carried by\n // the verified token\" — proto3 cannot express that as absence, so empty\n // carries the meaning. It stays required on this mirrored wire shape and on\n // the public `CheckAccessRequest` below; see that type for why.\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n}\n\nexport interface WireCheckAccessResponse {\n allowed: boolean;\n /**\n * @deprecated SDK-Q10 (contract 1.19) — superseded by {@link reason} (proto\n * field 4), which is what the REST decision body has always called this.\n * Both fields carry the byte-identical string until AXIAM **2.0**, where\n * proto field 2 is removed. Read `reason` instead; see `fromWireResponse`.\n */\n deny_reason: string;\n /** B1 deny-override decision reason (proto field 3). */\n reason_code?: string;\n /**\n * SDK-Q10 (contract 1.19) — the human-readable reason under the name REST\n * already uses. Proto field 4, explicit presence: absent on an allow,\n * present on every refusal. Absent on a *refusal* means a pre-SDK-Q10\n * server, which is exactly when {@link deny_reason} is still consulted.\n */\n reason?: string;\n}\n\nexport interface WireBatchCheckAccessRequest {\n requests: WireCheckAccessRequest[];\n}\n\nexport interface WireBatchCheckAccessResponse {\n results: WireCheckAccessResponse[];\n}\n\n// ---------------------------------------------------------------------------\n// Wire shapes (proto/axiam/v1/userinfo.proto) — mirrored, not imported.\n// ---------------------------------------------------------------------------\n\n/**\n * `axiam.v1.GetUserInfoRequest` — an empty message. Identity is derived\n * entirely server-side from the `authorization: Bearer <token>` metadata\n * (CONTRACT.md §1.1), so the request carries no fields.\n */\nexport type WireGetUserInfoRequest = Record<string, never>;\n\nexport interface WireGetUserInfoResponse {\n sub: string;\n tenant_id: string;\n org_id: string;\n // proto3 `optional` fields — absent on the wire unless the access token\n // carried the gating scope (\"email\" / \"profile\" respectively).\n email?: string;\n preferred_username?: string;\n}\n\ntype UnaryCallback<T> = (error: grpc.ServiceError | null, response?: T) => void;\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `AuthorizationServiceClient` this module needs. The real generated client\n * satisfies this shape exactly (unary Node-callback methods), so a\n * buf-enabled build's generated client is a drop-in replacement here.\n */\nexport interface WireAuthorizationServiceClient {\n checkAccess(\n request: WireCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n batchCheckAccess(\n request: WireBatchCheckAccessRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireBatchCheckAccessResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * The subset of a ts-proto (`outputServices=grpc-js`) generated\n * `UserInfoServiceClient` this module needs. As with\n * {@link WireAuthorizationServiceClient}, the real generated client satisfies\n * this shape exactly (single unary Node-callback method), so a buf-enabled\n * build's generated `UserInfoServiceClient` from `../gen/...` is a drop-in\n * replacement.\n */\nexport interface WireUserInfoServiceClient {\n getUserInfo(\n request: WireGetUserInfoRequest,\n metadata: grpc.Metadata,\n callback: UnaryCallback<WireGetUserInfoResponse>,\n ): grpc.ClientUnaryCall;\n close(): void;\n}\n\n/**\n * Public (camelCase, §1) single access-check request shape.\n *\n * `subjectId` is required here, unlike REST's optional `AccessCheck.subjectId`.\n * gRPC calls typically originate from a service-mesh caller with no\n * request-scoped JWT to derive a subject from, so passing it explicitly is the\n * normal case; REST, by contrast, derives the subject from the caller's JWT\n * when `subjectId` is omitted (§5).\n *\n * As of contract 1.19 (SDK-Q10) the *wire* field is optional in the same\n * sense — an empty `subject_id` means \"the subject in the verified token\" —\n * but this public type has not been relaxed to an optional `subjectId` to\n * match. That is a breaking signature move and is tracked separately from the\n * artifact re-vendor that brought the proto in.\n */\nexport interface CheckAccessRequest {\n tenantId: string;\n subjectId: string;\n action: string;\n resourceId: string;\n scope?: string;\n}\n\nfunction toWireRequest(req: CheckAccessRequest): WireCheckAccessRequest {\n return {\n tenant_id: req.tenantId,\n subject_id: req.subjectId,\n action: req.action,\n resource_id: req.resourceId,\n scope: req.scope,\n };\n}\n\nfunction fromWireResponse(resp: WireCheckAccessResponse): AccessDecision {\n // SDK-Q10 / CONTRACT.md §11.2 rule 9 (contract 1.19): read `reason`, fall\n // back to the deprecated `deny_reason` only when `reason` is absent on a\n // refusal — that is exactly a pre-SDK-Q10 server, and it is why proto field\n // 4 has explicit presence rather than being a plain `string`. One reason\n // accessor is exposed to callers, never two. `deny_reason` disappears at\n // AXIAM 2.0 and this fallback goes with it.\n const reason = resp.reason !== undefined ? resp.reason : resp.deny_reason;\n\n return {\n allowed: resp.allowed,\n reason: reason ? reason : undefined,\n // proto3 renders an unset `string` as `\"\"`, so an older server that never\n // set field 3 is indistinguishable from one that set it empty. Both mean\n // \"no reason code\", and both map to `undefined` rather than to `\"\"`,\n // which would be a value callers could accidentally branch on.\n reasonCode: resp.reason_code ? resp.reason_code : undefined,\n };\n}\n\n/**\n * The authenticated caller's OIDC-style identity claims, returned by\n * {@link UserInfoGrpcClient.getUserInfo} (CONTRACT.md §1.1). Public (camelCase,\n * §1) counterpart of the `axiam.v1.GetUserInfoResponse` wire message.\n *\n * `sub`, `tenantId`, and `orgId` are always present. `email` is populated only\n * when the access token carries the `email` scope, and `preferredUsername` only\n * with the `profile` scope — the server gates these exactly as the REST\n * `/oauth2/userinfo` endpoint does.\n */\nexport interface UserInfo {\n /** Subject (user) UUID. Always present. */\n sub: string;\n /** Tenant UUID. Always present. */\n tenantId: string;\n /** Organization UUID. Always present. */\n orgId: string;\n /** User email — present only with the `email` scope. */\n email?: string;\n /** Preferred username — present only with the `profile` scope. */\n preferredUsername?: string;\n}\n\nfunction fromWireUserInfo(resp: WireGetUserInfoResponse): UserInfo {\n return {\n sub: resp.sub,\n tenantId: resp.tenant_id,\n orgId: resp.org_id,\n // Preserve absence: a missing (scope-gated) claim stays `undefined` rather\n // than becoming an empty string.\n email: resp.email ? resp.email : undefined,\n preferredUsername: resp.preferred_username ? resp.preferred_username : undefined,\n };\n}\n\nfunction promisifyUnary<TReq, TResp>(\n call: (req: TReq, metadata: grpc.Metadata, callback: UnaryCallback<TResp>) => grpc.ClientUnaryCall,\n request: TReq,\n): Promise<TResp> {\n return new Promise((resolve, reject) => {\n call(request, new grpc.Metadata(), (error, response) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(response as TResp);\n });\n });\n}\n\n/**\n * Build the gRPC channel credentials for `baseUrl` (§6 — TLS is always\n * strict by default; `customCa` is the ONLY certificate escape hatch, never\n * an insecure/skip-verification surface).\n *\n * A plaintext target (`http://`/`grpc://`) is REFUSED by default (X-2): it\n * would silently drop the channel to `createInsecure()`, sending bearer tokens\n * and tenant metadata in cleartext. Callers who genuinely need a local dev\n * plaintext channel must opt in explicitly with `allowInsecure: true`, which\n * emits a `console.warn`. As a convenience the opt-in is required for ANY host\n * (including loopback) — there is no silent path to an insecure channel.\n *\n * When a §6.1 mTLS client identity is configured it is applied to the secure\n * channel via `createSsl(rootCerts, privateKey, certChain)` — the SAME strict\n * verification as the default `createSsl()`, just additionally presenting a\n * client certificate. The identity never affects the plaintext-refusal path.\n */\nfunction buildCredentials(\n baseUrl: string,\n customCa: string | undefined,\n allowInsecure: boolean,\n identity: ClientIdentity | undefined,\n): grpc.ChannelCredentials {\n const isSecure = baseUrl.startsWith('https://') || baseUrl.startsWith('grpcs://');\n if (!isSecure) {\n if (!allowInsecure) {\n throw new Error(\n `AXIAM gRPC refuses to open an insecure (plaintext) channel to \"${baseUrl}\": ` +\n 'bearer tokens and tenant metadata would be sent in cleartext. Use an ' +\n 'https:// or grpcs:// target, or pass { allowInsecure: true } to opt in ' +\n 'explicitly for a trusted local/dev channel (CONTRACT.md §6).',\n );\n }\n // Explicit opt-in only — never reached without allowInsecure.\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM gRPC: opening an INSECURE (plaintext) channel to \"${baseUrl}\" because ` +\n 'allowInsecure was set. Bearer tokens and tenant metadata are transmitted in ' +\n 'cleartext — never use this outside a trusted local/dev environment.',\n );\n return grpc.ChannelCredentials.createInsecure();\n }\n const rootCerts = customCa ? Buffer.from(customCa, 'utf8') : null;\n if (identity) {\n // mTLS (§6.1): present the client cert+key. `rootCerts ?? null` keeps the\n // platform trust store (null = default roots) when no customCa is given;\n // strict server verification is unchanged.\n return grpc.ChannelCredentials.createSsl(\n rootCerts,\n Buffer.from(identity.key.expose(), 'utf8'),\n Buffer.from(identity.cert, 'utf8'),\n );\n }\n if (customCa) {\n return grpc.ChannelCredentials.createSsl(rootCerts);\n }\n // Default: verify against the platform's native trust store.\n return grpc.ChannelCredentials.createSsl();\n}\n\nfunction grpcTarget(baseUrl: string): string {\n const url = new URL(baseUrl);\n return url.port ? `${url.hostname}:${url.port}` : url.hostname;\n}\n\nconst jsonCodec = <T>() => ({\n serialize: (value: T): Buffer => Buffer.from(JSON.stringify(value)),\n deserialize: (bytes: Buffer): T => JSON.parse(bytes.toString('utf8')) as T,\n});\n\n/**\n * Construct a real `AuthorizationServiceClient` over grpc-js's own\n * `makeClientConstructor` primitive (the same primitive ts-proto's\n * `outputServices=grpc-js` codegen target uses under the hood). This\n * transport-level client encodes/decodes with JSON as a build-independent\n * stand-in for the protobuf binary codec a buf-enabled build's generated\n * serializers would use — swap this factory for the generated\n * `AuthorizationServiceClient` once `src/gen` exists (D-20).\n */\nexport function buildAuthorizationServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireAuthorizationServiceClient {\n const checkAccessCodec = jsonCodec<WireCheckAccessRequest>();\n const checkAccessRespCodec = jsonCodec<WireCheckAccessResponse>();\n const batchCodec = jsonCodec<WireBatchCheckAccessRequest>();\n const batchRespCodec = jsonCodec<WireBatchCheckAccessResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n checkAccess: {\n path: '/axiam.v1.AuthorizationService/CheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: checkAccessCodec.serialize,\n requestDeserialize: checkAccessCodec.deserialize,\n responseSerialize: checkAccessRespCodec.serialize,\n responseDeserialize: checkAccessRespCodec.deserialize,\n },\n batchCheckAccess: {\n path: '/axiam.v1.AuthorizationService/BatchCheckAccess',\n requestStream: false,\n responseStream: false,\n requestSerialize: batchCodec.serialize,\n requestDeserialize: batchCodec.deserialize,\n responseSerialize: batchRespCodec.serialize,\n responseDeserialize: batchRespCodec.deserialize,\n },\n },\n 'axiam.v1.AuthorizationService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireAuthorizationServiceClient;\n}\n\nexport type AuthorizationServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireAuthorizationServiceClient;\n\n/**\n * Construct a real `UserInfoServiceClient` the same way\n * {@link buildAuthorizationServiceClient} builds the AuthorizationService\n * client — grpc-js's own `makeClientConstructor` primitive (the primitive\n * ts-proto's `outputServices=grpc-js` codegen sits on top of), with a JSON\n * codec as a build-independent stand-in for the protobuf binary serializers a\n * buf-enabled build would generate. Swap this factory for the generated\n * `UserInfoServiceClient` from `../gen/...` once `src/gen` exists (D-20); it\n * satisfies {@link WireUserInfoServiceClient} by construction (same .proto).\n *\n * grpc-js pools subchannels by target + credentials, so a UserInfoService\n * client built against the same `baseUrl`/credentials as the co-located\n * {@link AuthzGrpcClient} shares the underlying connection rather than opening a\n * redundant one (CONTRACT.md §1.1: reuse the existing channel machinery).\n */\nexport function buildUserInfoServiceClient(\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n): WireUserInfoServiceClient {\n const reqCodec = jsonCodec<WireGetUserInfoRequest>();\n const respCodec = jsonCodec<WireGetUserInfoResponse>();\n\n const ServiceClientConstructor = grpc.makeClientConstructor(\n {\n getUserInfo: {\n path: '/axiam.v1.UserInfoService/GetUserInfo',\n requestStream: false,\n responseStream: false,\n requestSerialize: reqCodec.serialize,\n requestDeserialize: reqCodec.deserialize,\n responseSerialize: respCodec.serialize,\n responseDeserialize: respCodec.deserialize,\n },\n },\n 'axiam.v1.UserInfoService',\n );\n\n return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {\n interceptors,\n }) as unknown as WireUserInfoServiceClient;\n}\n\nexport type UserInfoServiceClientFactory = (\n baseUrl: string,\n credentials: grpc.ChannelCredentials,\n interceptors: grpc.Interceptor[],\n) => WireUserInfoServiceClient;\n\n/**\n * gRPC transport for `AuthorizationService` (`checkAccess`/`batchCheck`,\n * SC#2 Node half), reusing one long-lived client/channel per instance (D-10\n * — never reconstructed per-call) and injecting auth + tenant metadata via\n * the synchronous interceptor on every RPC.\n */\nexport class AuthzGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireAuthorizationServiceClient;\n\n constructor(\n session: NodeSession,\n options: {\n baseUrl: string;\n customCa?: string;\n allowInsecure?: boolean;\n /** PEM client-certificate chain for mutual TLS (§6.1); pair with `clientKey`. */\n clientCert?: string;\n /** PEM private key for mutual TLS (§6.1); pair with `clientCert`. Secret (§7). */\n clientKey?: string;\n },\n clientFactory: AuthorizationServiceClientFactory = buildAuthorizationServiceClient,\n ) {\n this.#session = session;\n // Validate + resolve the §6.1 identity (throws on one-of/bad-PEM, §6.1) and\n // apply it to the gRPC channel — the SAME identity the REST transport uses.\n const identity = resolveClientIdentity(options);\n const credentials = buildCredentials(\n options.baseUrl,\n options.customCa,\n options.allowInsecure ?? false,\n identity,\n );\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */\n async checkAccess(request: CheckAccessRequest): Promise<AccessDecision> {\n const wireRequest = toWireRequest(request);\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.checkAccess.bind(this.#inner), wireRequest),\n );\n return fromWireResponse(response);\n }\n\n /** `BatchCheckAccess` over gRPC — results preserve input order (§1). */\n async batchCheck(requests: CheckAccessRequest[]): Promise<AccessDecision[]> {\n const wireRequest: WireBatchCheckAccessRequest = { requests: requests.map(toWireRequest) };\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.batchCheckAccess.bind(this.#inner), wireRequest),\n );\n return response.results.map(fromWireResponse);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n\n/**\n * gRPC transport for `axiam.v1.UserInfoService` (`getUserInfo`, CONTRACT.md\n * §1.1) — the low-latency counterpart of the server's REST\n * `GET /oauth2/userinfo` endpoint.\n *\n * Reuses the SAME channel/interceptor/refresh machinery as {@link\n * AuthzGrpcClient}: one long-lived client/channel per instance (D-10 — never\n * reconstructed per-call), the shared auth + `x-tenant-id` interceptor\n * (`authInterceptor(session)`), and this session's single-flight refresh guard\n * via `callWithRefresh`. Built from the same {@link NodeSession}, it shares the\n * pooled subchannel with a co-located `AuthzGrpcClient` (no second connection).\n */\nexport class UserInfoGrpcClient {\n readonly #session: NodeSession;\n readonly #inner: WireUserInfoServiceClient;\n\n constructor(\n session: NodeSession,\n options: {\n baseUrl: string;\n customCa?: string;\n allowInsecure?: boolean;\n /** PEM client-certificate chain for mutual TLS (§6.1); pair with `clientKey`. */\n clientCert?: string;\n /** PEM private key for mutual TLS (§6.1); pair with `clientCert`. Secret (§7). */\n clientKey?: string;\n },\n clientFactory: UserInfoServiceClientFactory = buildUserInfoServiceClient,\n ) {\n this.#session = session;\n // Validate + resolve the §6.1 identity (throws on one-of/bad-PEM) and apply\n // it to the gRPC channel — the SAME identity the REST/authz transports use.\n const identity = resolveClientIdentity(options);\n const credentials = buildCredentials(\n options.baseUrl,\n options.customCa,\n options.allowInsecure ?? false,\n identity,\n );\n this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);\n }\n\n /**\n * `GetUserInfo` over gRPC (CONTRACT.md §1.1). Returns the authenticated\n * caller's identity claims; the request is empty (identity comes from the\n * bearer token in the interceptor-injected metadata).\n *\n * Pre-flight (§1.1.3): with no cached access token this raises `AuthError`\n * client-side, WITHOUT a wire call — the same synchronous cached-token view\n * the auth interceptor reads. A gRPC `UNAUTHENTICATED` response otherwise\n * drives exactly one shared-guard refresh + one retry (§9.3), identical to\n * {@link AuthzGrpcClient.checkAccess}.\n */\n async getUserInfo(): Promise<UserInfo> {\n if (this.#session.tokenManager.cachedAccessToken() === null) {\n throw new AuthError('getUserInfo requires a prior successful login() (no access token present)');\n }\n const response = await callWithRefresh(this.#session, () =>\n promisifyUnary(this.#inner.getUserInfo.bind(this.#inner), {} as WireGetUserInfoRequest),\n );\n return fromWireUserInfo(response);\n }\n\n /** Close the underlying gRPC channel. */\n close(): void {\n this.#inner.close();\n }\n}\n","// SharedSession — the object other transports (Node persona 17-03, middleware\n// 17-05) attach gRPC/JWKS/middleware state to (D-13).\n//\n// Holds: the axios instance, the tenant header value (computed once at\n// construction), a mutable csrfToken store, the base URL, and a per-instance\n// single-flight refresh guard (CR-02: NOT the module-level default guard —\n// each SharedSession gets its own via createRefreshGuard(), so two\n// independent AxiamClient/NodeSession instances never cross-wire refreshes).\n// One login() drives all transports for a given session.\n\nimport axios, { type AxiosInstance } from 'axios';\nimport type { AxiamClientOptions, 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 * True when this session was constructed with a §6.1 mTLS client identity\n * (`clientCert` + `clientKey`), and therefore presents a client certificate\n * on every request it makes.\n *\n * Read by the §12 OIDC helpers to decide whether CONTRACT.md §21.3 rule 2\n * applies: an `mtls_endpoint_aliases` entry is preferred only on a call that\n * is actually going over mutual TLS, and a session without an identity must\n * keep using the top-level endpoints.\n */\n readonly presentsClientCertificate: boolean;\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 /**\n * The tenant the signed-in principal's record *lives* in — CONTRACT.md\n * §5.2.2 — as reported by the login response.\n *\n * Distinct from `resolvedTenantId`, which is the tenant being acted on: the\n * two diverge for an organization-level principal that has selected another\n * one. Read by `opaqueEnrollmentForSelf`, which must seal a §23 record\n * against the account's own tenant rather than whichever one this client is\n * currently pointed at. `undefined` until a login completes.\n */\n resolvedPrincipalTenantId: 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 // Both halves, because §6.1 is all-or-nothing: `resolveClientIdentity`\n // rejects one without the other before this line is reached.\n this.presentsClientCertificate =\n options.clientCert !== undefined && options.clientKey !== undefined;\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 AxiamUserInfo,\n LoginResult,\n LoginSuccessResponseWire,\n LoginUserInfoWire,\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\n/**\n * Map the wire user object onto {@link AxiamUserInfo}.\n *\n * Shared by the three response paths that complete a login — password,\n * OPAQUE, and the account-lifecycle flows — which previously each carried\n * their own copy of this mapping and a comment saying \"same reading as\n * `auth.ts`\". Contract 1.34 turned that duplication into a hazard: five more\n * fields, and a copy that forwards three of them is a bug nothing catches.\n */\nexport function userInfoFromWire(user: LoginUserInfoWire): AxiamUserInfo {\n return {\n id: user.id,\n username: user.username,\n email: user.email,\n // §5.2: derived server-side and response-only. `?? false` is what makes a\n // pre-1.31 server's silence mean \"no cross-tenant action\", rather than\n // `undefined` leaking into a truthiness check somewhere downstream.\n organizationLevel: user.organization_level ?? false,\n tenantId: user.tenant_id,\n // §5.2.2 rule 1: absent means equal. A server older than contract 1.34\n // omits this and cannot switch the acting tenant either, so falling back\n // to `tenant_id` is not a guess — it is the only value it could have had.\n principalTenantId: user.principal_tenant_id ?? user.tenant_id,\n principalTenantSlug: user.principal_tenant_slug ?? undefined,\n orgId: user.org_id ?? undefined,\n // §5.2.3: absent means unrestricted, and `null` from the server means the\n // same thing — neither should surface as an empty list, which would read\n // as \"reaches nothing\".\n reachableTenantIds: user.reachable_tenant_ids ?? undefined,\n };\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire, client?: AxiamClient): LoginResult {\n const user = userInfoFromWire(wire.user);\n // §5.2.2: remember where this principal lives, so a later\n // `opaqueEnrollmentForSelf` seals against the account's own tenant without\n // a second round trip.\n if (client && user.principalTenantId) {\n client.session.resolvedPrincipalTenantId = user.principalTenantId;\n }\n return {\n status: 'authenticated',\n user,\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, client);\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, client);\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 { userInfoFromWire } from './auth.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: userInfoFromWire(wire.user),\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\n/**\n * Build a registration record for `password`, sealed against the tenant this\n * client is **acting on**.\n *\n * That is the right tenant when the record is for an account being created in\n * it — §27 `users.create`, and the reset-completion flow, which names its own\n * tenant. It is the **wrong** tenant for the caller's own password change\n * once an organization-level principal has selected another one to act on:\n * the account's credentials live where the account does. Use\n * {@link opaqueEnrollmentForSelf} there — CONTRACT.md §5.2.2 rule 2.\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 return enroll(client, password, undefined);\n}\n\n/**\n * Build a registration record for the **caller's own** new password, sealed\n * against the tenant the caller's account lives in.\n *\n * CONTRACT.md §5.2.2 rule 2. `POST /auth/password/change` and the record that\n * accompanies it are about the account, not about whatever tenant the client\n * is currently pointed at, and a record sealed against the acting tenant is\n * refused with *\"the OPAQUE session was issued for a different tenant\"*.\n *\n * The distinction only bites for an organization-level principal that has\n * selected another tenant to act on; for everyone else the two tenants are the\n * same value and this behaves identically to {@link opaqueEnrollment}. It is\n * still the function to call for a self-service password change, because which\n * principal is signed in is not something the call site usually knows.\n *\n * @throws NetworkError when no login has completed on this client yet — the\n * principal tenant is reported by the login response, so there is nothing to\n * seal against before then.\n */\nexport async function opaqueEnrollmentForSelf(\n client: AxiamClient,\n password: string,\n): Promise<OpaqueEnrollment> {\n const principalTenantId = client.session.resolvedPrincipalTenantId;\n if (!principalTenantId) {\n throw new NetworkError(\n 'OPAQUE: no principal tenant is known yet — sign in before building a '\n + 'registration record for your own password',\n );\n }\n return enroll(client, password, principalTenantId);\n}\n\n/**\n * The shared body of the two enrolment functions; they differ only in the\n * tenant the record is sealed against.\n */\nasync function enroll(\n client: AxiamClient,\n password: string,\n principalTenantId: string | undefined,\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 if (principalTenantId !== undefined) {\n // Name the principal tenant by id and drop the slug: a slug that named the\n // acting tenant would otherwise out-vote the id server-side, which is the\n // exact confusion this path exists to avoid.\n body.tenant_id = principalTenantId;\n delete body.tenant_slug;\n }\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 { userInfoFromWire } from './auth.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 RESEND_OWN_VERIFICATION = '/api/v1/users/me/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: userInfoFromWire(wire.user),\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/**\n * `POST /api/v1/auth/resend-verification` (§25.1) — the **unauthenticated**\n * resend, for a caller with no session.\n *\n * **Resolves whatever the outcome.** The address may not exist, may already be\n * verified, or may be over the daily limit, and this answers identically in all\n * of them, because it takes an address from an anonymous caller and anything\n * else is an oracle for which addresses have accounts (§25.7).\n *\n * A caller that *is* signed in wants {@link resendOwnVerification}, which says\n * which of those happened. Do not reach for this one because it is the name you\n * already knew.\n */\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 * `POST /api/v1/users/me/resend-verification` (§25.1, §25.7) — resend the\n * **signed-in caller's own** verification mail, and say what happened.\n *\n * Takes no address. The server reads it off the caller's own record, and this\n * signature deliberately offers no way to name a different one: a parameter\n * here would let an authenticated session mail an arbitrary address.\n *\n * Unlike {@link resendVerification} this reports the outcome, because the\n * caller is signed in to the account it is asking about and none of the\n * outcomes tells it anything it did not already know:\n *\n * - resolves — a token was minted and the mail **enqueued**. Delivery is\n * asynchronous and can still fail at the provider; a queue that accepts\n * everything in front of one that rejects it looks exactly like this working.\n * - `ConflictError` (from `409`) — already verified, or the account is in a\n * state that must not be sent a live token.\n * - `NetworkError` (from `429`) — the daily resend limit.\n *\n * §25.7 rule 2 forbids falling back to the unauthenticated endpoint on either\n * of those, and this SDK does not: the fallback would turn both failures back\n * into a resolved promise and restore the bug this operation exists to fix,\n * with an extra round-trip.\n */\nexport async function resendOwnVerification(client: AxiamClient): Promise<void> {\n client.ensureOpen();\n await post<void>(client, RESEND_OWN_VERIFICATION, {}, 'resendOwnVerification');\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","/**\n * The plan a manifest reconciles to — CONTRACT.md §27.6.\n */\n\nimport { NetworkError } from '../../core/errors.js';\nimport type { ManagementManifest } from './spec.js';\n\n/** What reconciling one spec would do. */\nexport type Change = 'create' | 'update' | 'no-change';\n\n/** Which part of the manifest an action came from. */\nexport type Target =\n | 'resource'\n | 'scope'\n | 'permission'\n | 'role'\n | 'role-grant'\n | 'group'\n | 'group-role'\n | 'user'\n | 'user-role'\n | 'group-member';\n\n/** One step of a plan. */\nexport interface PlannedAction {\n /** Whether this step creates, updates, or does nothing. */\n change: Change;\n /** What kind of thing it acts on. */\n target: Target;\n /** The manifest key it came from, for a human reading the plan. */\n key: string;\n /** A one-line description, stable across runs so plans can be diffed. */\n summary: string;\n}\n\n/**\n * The ordered set of actions that would reconcile a manifest.\n *\n * Ordering is derived, not incidental: resources (parents before children),\n * then scopes, permissions, roles, role grants, groups, group bindings, users,\n * and finally the user bindings that need all of the above to exist. Two plans\n * over unchanged state are equal, in the same order (§27.6 rule 8) — a plan\n * that reorders between runs cannot be diffed, and diffing it is most of the\n * reason it exists.\n */\nexport interface ManagementPlan {\n /** Every step, including the no-ops. */\n actions: PlannedAction[];\n}\n\n/** The steps of `plan` that would actually change something. */\nexport function changes(plan: ManagementPlan): PlannedAction[] {\n return plan.actions.filter((a) => a.change !== 'no-change');\n}\n\n/**\n * Whether applying `plan` would change nothing.\n *\n * This is the §27.6 rule 6 acceptance test: `apply` then `plan` must land\n * here, or the SDK has a drift-detection bug.\n */\nexport function isConverged(plan: ManagementPlan): boolean {\n return changes(plan).length === 0;\n}\n\n/**\n * What actually happened to one planned step.\n *\n * Named `StepOutcome` rather than `Outcome` because `core/telemetry` already\n * exports an `Outcome` — the success/failure of a single request — and two\n * exported types of that name in one package is one too many.\n */\nexport type StepOutcome =\n | {\n /** The step ran and the thing now exists. */\n status: 'created';\n }\n | {\n /** The step ran and the thing was updated. */\n status: 'updated';\n }\n | {\n /** A no-op step; nothing was sent. */\n status: 'unchanged';\n }\n | {\n /** The step failed. Everything before it has already happened. */\n status: 'failed';\n /** The error the server or transport gave. */\n message: string;\n }\n | {\n /** Never attempted, because an earlier step failed. */\n status: 'not-attempted';\n };\n\n/** One planned step paired with what became of it. */\nexport interface AppliedStep {\n /** The step, exactly as `plan` reported it. */\n action: PlannedAction;\n /** What actually happened when it ran — or did not. */\n outcome: StepOutcome;\n}\n\n/** The step that stopped an apply, and why. */\nexport interface ManifestFailure {\n /** The step that failed. Everything before it has already happened. */\n action: PlannedAction;\n /** The error the server or transport gave. */\n message: string;\n}\n\n/**\n * The result of applying a manifest.\n *\n * **There is no transaction here and this type does not pretend there is**\n * (§27.6 rule 7). These are independent HTTP endpoints; nothing spans them. If\n * step 12 of 30 fails, steps 1–11 have happened and will not be undone — so\n * every step's outcome is reported, execution stops at the first failure\n * rather than continuing blindly, and there is no `rollback` because this SDK\n * could not honour one. Fix the cause and re-apply: rule 6's idempotence is\n * what makes that safe.\n */\nexport interface ApplyReport {\n /** Each planned step paired with what became of it, in plan order. */\n steps: AppliedStep[];\n}\n\n/** The failing step, if the apply stopped early. */\nexport function failure(report: ApplyReport): ManifestFailure | undefined {\n const found = report.steps.find((s) => s.outcome.status === 'failed');\n return found ? { action: found.action, message: (found.outcome as { message: string }).message } : undefined;\n}\n\n/** Whether every step that was meant to run did. */\nexport function isComplete(report: ApplyReport): boolean {\n return failure(report) === undefined;\n}\n\n/** How many steps actually changed something. */\nexport function changedCount(report: ApplyReport): number {\n return report.steps.filter(\n (s) => s.outcome.status === 'created' || s.outcome.status === 'updated',\n ).length;\n}\n\n/**\n * Reject a manifest that cannot be reconciled, before any request is made.\n *\n * §27.6 rules 2 and 5 both land here. Every failure this catches would\n * otherwise surface halfway through an apply, with part of the tenant already\n * changed — which is the expensive moment to learn that a role refers to a\n * permission nobody declared.\n *\n * @internal\n */\nexport function validate(manifest: ManagementManifest): void {\n const problems: string[] = [];\n const resources = manifest.resources ?? [];\n const permissions = manifest.permissions ?? [];\n const roles = manifest.roles ?? [];\n const groups = manifest.groups ?? [];\n const users = manifest.users ?? [];\n\n const resourceKeys = new Set(resources.map((r) => r.key));\n const scopeKeys = new Set(resources.flatMap((r) => (r.scopes ?? []).map((s) => s.key)));\n const permissionKeys = new Set(permissions.map((p) => p.key));\n const roleKeys = new Set(roles.map((r) => r.key));\n const groupKeys = new Set(groups.map((g) => g.key));\n\n duplicates('resource', resources.map((r) => r.key), problems);\n duplicates('scope', resources.flatMap((r) => (r.scopes ?? []).map((s) => s.key)), problems);\n duplicates('permission', permissions.map((p) => p.key), problems);\n duplicates('role', roles.map((r) => r.key), problems);\n duplicates('group', groups.map((g) => g.key), problems);\n duplicates('user', users.map((u) => u.key), problems);\n\n for (const resource of resources) {\n if (resource.parent && !resourceKeys.has(resource.parent)) {\n problems.push(\n `resource ${q(resource.key)} names parent ${q(resource.parent)}, which no resource declares`,\n );\n }\n }\n for (const role of roles) {\n for (const grant of role.grants ?? []) {\n if (!permissionKeys.has(grant.permission)) {\n problems.push(\n `role ${q(role.key)} grants permission ${q(grant.permission)}, which no permission declares`,\n );\n }\n for (const scope of grant.scopes ?? []) {\n if (!scopeKeys.has(scope)) {\n problems.push(`role ${q(role.key)} scopes a grant to ${q(scope)}, which no scope declares`);\n }\n }\n }\n }\n for (const group of groups) {\n for (const role of group.roles ?? []) {\n if (!roleKeys.has(role)) {\n problems.push(`group ${q(group.key)} is assigned role ${q(role)}, which no role declares`);\n }\n }\n }\n for (const user of users) {\n for (const role of user.roles ?? []) {\n if (!roleKeys.has(role)) {\n problems.push(`user ${q(user.key)} is assigned role ${q(role)}, which no role declares`);\n }\n }\n for (const group of user.groups ?? []) {\n if (!groupKeys.has(group)) {\n problems.push(`user ${q(user.key)} is in group ${q(group)}, which no group declares`);\n }\n }\n }\n\n try {\n topologicalOrder(manifest);\n } catch (err) {\n problems.push((err as Error).message);\n }\n\n if (problems.length) {\n throw new NetworkError(\n `manifest is not reconcilable (${problems.length} problem(s)): ${problems.join('; ')}`,\n );\n }\n}\n\nconst q = (s: string) => JSON.stringify(s);\n\nfunction duplicates(kind: string, keys: string[], problems: string[]): void {\n const seen = new Set<string>();\n for (const key of keys) {\n if (seen.has(key)) problems.push(`${kind} key ${q(key)} is declared more than once`);\n seen.add(key);\n }\n}\n\n/**\n * Resource keys ordered so a parent always precedes its children.\n *\n * Throws on a cycle rather than looping: a resource graph with a cycle has no\n * valid creation order, and discovering that by hanging is worse than\n * discovering it by message.\n *\n * @internal\n */\nexport function topologicalOrder(manifest: ManagementManifest): string[] {\n const resources = manifest.resources ?? [];\n const parents = new Map(resources.map((r) => [r.key, r.parent]));\n const order: string[] = [];\n const placed = new Set<string>();\n\n // Iterate the manifest's own order so the result is stable run to run\n // (§27.6 rule 8), rather than a map traversal order that is not.\n for (const resource of resources) {\n const chain: string[] = [];\n const guard = new Set<string>();\n let cursor: string | undefined = resource.key;\n while (cursor !== undefined && !placed.has(cursor)) {\n if (guard.has(cursor)) {\n throw new NetworkError(\n `resource parent graph has a cycle through ${q(cursor)}; there is no order in which ` +\n `these can be created`,\n );\n }\n guard.add(cursor);\n chain.push(cursor);\n cursor = parents.get(cursor);\n }\n for (const key of chain.reverse()) {\n if (!placed.has(key)) {\n placed.add(key);\n order.push(key);\n }\n }\n }\n return order;\n}\n","/**\n * Reconciling a manifest against a live tenant — CONTRACT.md §27.6.\n */\n\nimport { NetworkError } from '../../core/errors.js';\nimport type { AxiamClient } from '../../rest/client.js';\nimport type * as models from '../models.js';\nimport type {\n ApplyReport,\n ManagementPlan,\n StepOutcome,\n PlannedAction,\n Target,\n} from './plan.js';\nimport { topologicalOrder, validate } from './plan.js';\nimport type { ManagementManifest, ResourceSpec } from './spec.js';\n\n/** How many items a planning read asks for per page. */\nconst PLAN_PAGE = 200;\n\n/** Manifest keys resolved to server ids, built during planning. */\ninterface Resolved {\n resources: Map<string, string>;\n scopes: Map<string, string>;\n permissions: Map<string, string>;\n roles: Map<string, string>;\n groups: Map<string, string>;\n users: Map<string, string>;\n}\n\nconst emptyResolved = (): Resolved => ({\n resources: new Map(),\n scopes: new Map(),\n permissions: new Map(),\n roles: new Map(),\n groups: new Map(),\n users: new Map(),\n});\n\n/** One executable step, carrying manifest keys rather than ids. */\ntype Step =\n | { kind: 'noop' }\n | { kind: 'create-resource'; key: string; name: string; resourceType: string; parent?: string }\n | { kind: 'update-resource'; key: string; resourceType: string }\n | { kind: 'create-scope'; resource: string; key: string; name: string; description: string }\n | { kind: 'create-permission'; key: string; action: string; description: string }\n | { kind: 'update-permission'; key: string; description: string }\n | { kind: 'create-role'; key: string; name: string; description: string; isGlobal: boolean }\n | { kind: 'update-role'; key: string; description: string; isGlobal: boolean }\n | {\n kind: 'grant-permission';\n role: string;\n permission: string;\n effect?: models.PermissionEffect;\n scopes: string[];\n }\n | { kind: 'create-group'; key: string; name: string; description: string }\n | { kind: 'update-group'; key: string; description: string }\n | { kind: 'assign-role-to-group'; role: string; group: string }\n | {\n kind: 'create-user';\n key: string;\n username: string;\n email: string;\n password: models.CreateUserRequest['password'];\n }\n | { kind: 'update-user'; key: string; email: string }\n | { kind: 'assign-role-to-user'; role: string; user: string }\n | { kind: 'add-group-member'; group: string; user: string };\n\n/** The current state a plan is computed against. */\ninterface Snapshot {\n resources: models.Resource[];\n scopes: Map<string, models.Scope[]>;\n permissions: models.Permission[];\n roles: models.Role[];\n groups: models.Group[];\n users: models.UserResponse[];\n roleGrants: Map<string, string[]>;\n roleUsers: Map<string, string[]>;\n roleGroups: Map<string, string[]>;\n groupMembers: Map<string, string[]>;\n}\n\n/** The declarative-management handle, reached as `client.manifest`. */\nexport class ManifestApi {\n readonly #client: AxiamClient;\n\n /** @internal — reached through `client.manifest`, never constructed directly. */\n constructor(client: AxiamClient) {\n this.#client = client;\n }\n\n /** What reconciling `manifest` would do. **Issues no writes.** */\n async plan(manifest: ManagementManifest): Promise<ManagementPlan> {\n validate(manifest);\n const snapshot = await this.#read(manifest);\n return { actions: this.#compute(manifest, snapshot).map((s) => s.action) };\n }\n\n /**\n * Reconcile `manifest`, stopping at the first failure.\n *\n * Re-running after fixing the cause is the recovery path, and is safe:\n * applying twice converges (§27.6 rule 6).\n */\n async apply(manifest: ManagementManifest): Promise<ApplyReport> {\n validate(manifest);\n const snapshot = await this.#read(manifest);\n const steps = this.#compute(manifest, snapshot);\n const resolved = this.#resolvedFrom(manifest, snapshot);\n return this.#execute(steps, resolved);\n }\n\n // -------------------------------------------------------------------\n // Read\n // -------------------------------------------------------------------\n\n async #read(manifest: ManagementManifest): Promise<Snapshot> {\n const c = this.#client;\n const start = { limit: PLAN_PAGE };\n const resources = await c.resources.listAll(start);\n const permissions = await c.permissions.listAll(start);\n const roles = await c.roles.listAll(start);\n const groups = await c.groups.listAll(start);\n const users = await c.users.listAll(start);\n\n // Only the resources, roles and groups the manifest could match: a tenant\n // with a thousand resources should not cost a thousand scope reads to plan\n // five.\n const scopes = new Map<string, models.Scope[]>();\n for (const resource of resources) {\n if ((manifest.resources ?? []).some((s) => s.name === resource.name)) {\n scopes.set(resource.id, await c.scopes.list(resource.id));\n }\n }\n const roleGrants = new Map<string, string[]>();\n const roleUsers = new Map<string, string[]>();\n const roleGroups = new Map<string, string[]>();\n for (const role of roles) {\n if (!(manifest.roles ?? []).some((s) => s.name === role.name)) continue;\n roleGrants.set(role.id, (await c.roles.listPermissions(role.id)).map((g) => g.permission.id));\n roleUsers.set(role.id, (await c.roles.listUsers(role.id)).map((a) => a.user.id));\n roleGroups.set(role.id, (await c.roles.listGroups(role.id)).map((a) => a.group.id));\n }\n const groupMembers = new Map<string, string[]>();\n for (const group of groups) {\n if (!(manifest.groups ?? []).some((s) => s.name === group.name)) continue;\n groupMembers.set(group.id, (await c.groups.listMembersAll(group.id, start)).map((u) => u.id));\n }\n\n return {\n resources,\n scopes,\n permissions,\n roles,\n groups,\n users,\n roleGrants,\n roleUsers,\n roleGroups,\n groupMembers,\n };\n }\n\n // -------------------------------------------------------------------\n // Plan\n // -------------------------------------------------------------------\n\n #resolvedFrom(manifest: ManagementManifest, snapshot: Snapshot): Resolved {\n const resolved = emptyResolved();\n this.#compute(manifest, snapshot, resolved);\n return resolved;\n }\n\n #compute(\n manifest: ManagementManifest,\n snapshot: Snapshot,\n into: Resolved = emptyResolved(),\n ): Array<{ action: PlannedAction; step: Step }> {\n const resolved = into;\n const out: Array<{ action: PlannedAction; step: Step }> = [];\n const push = (change: PlannedAction['change'], target: Target, key: string, summary: string, step: Step) =>\n out.push({ action: { change, target, key, summary }, step });\n\n const specs = new Map((manifest.resources ?? []).map((r) => [r.key, r] as const));\n // `topologicalOrder` already rejected a cycle during validation.\n for (const key of topologicalOrder(manifest)) {\n const spec = specs.get(key) as ResourceSpec;\n const parentPending = spec.parent !== undefined && !resolved.resources.has(spec.parent);\n const parentId = spec.parent ? resolved.resources.get(spec.parent) : undefined;\n // A child whose parent is itself pending cannot already exist, so\n // matching it against a root of the same name would be wrong.\n const existing = parentPending\n ? undefined\n : snapshot.resources.find(\n (r) => r.name === spec.name && (r.parent_id ?? undefined) === parentId,\n );\n const summary = `resource ${JSON.stringify(spec.name)} (${spec.resourceType})`;\n if (existing) {\n resolved.resources.set(spec.key, existing.id);\n const drifted = existing.resource_type !== spec.resourceType;\n push(\n drifted ? 'update' : 'no-change',\n 'resource',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-resource', key: spec.key, resourceType: spec.resourceType }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'resource', spec.key, summary, {\n kind: 'create-resource',\n key: spec.key,\n name: spec.name,\n resourceType: spec.resourceType,\n parent: spec.parent,\n });\n }\n }\n\n for (const key of topologicalOrder(manifest)) {\n const spec = specs.get(key) as ResourceSpec;\n const resourceId = resolved.resources.get(spec.key);\n const existingScopes = (resourceId && snapshot.scopes.get(resourceId)) || [];\n for (const scope of spec.scopes ?? []) {\n const found = existingScopes.find((s) => s.name === scope.name);\n const summary = `scope ${JSON.stringify(scope.name)} on ${JSON.stringify(spec.name)}`;\n if (found) {\n resolved.scopes.set(scope.key, found.id);\n push('no-change', 'scope', scope.key, summary, { kind: 'noop' });\n } else {\n push('create', 'scope', scope.key, summary, {\n kind: 'create-scope',\n resource: spec.key,\n key: scope.key,\n name: scope.name,\n description: scope.description,\n });\n }\n }\n }\n\n for (const spec of manifest.permissions ?? []) {\n const found = snapshot.permissions.find((p) => p.action === spec.action);\n const summary = `permission ${JSON.stringify(spec.action)}`;\n if (found) {\n resolved.permissions.set(spec.key, found.id);\n const drifted = found.description !== spec.description;\n push(\n drifted ? 'update' : 'no-change',\n 'permission',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-permission', key: spec.key, description: spec.description }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'permission', spec.key, summary, {\n kind: 'create-permission',\n key: spec.key,\n action: spec.action,\n description: spec.description,\n });\n }\n }\n\n for (const spec of manifest.roles ?? []) {\n const found = snapshot.roles.find((r) => r.name === spec.name);\n const summary = `role ${JSON.stringify(spec.name)}`;\n const isGlobal = spec.isGlobal ?? false;\n if (found) {\n resolved.roles.set(spec.key, found.id);\n const drifted = found.description !== spec.description || found.is_global !== isGlobal;\n push(\n drifted ? 'update' : 'no-change',\n 'role',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-role', key: spec.key, description: spec.description, isGlobal }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'role', spec.key, summary, {\n kind: 'create-role',\n key: spec.key,\n name: spec.name,\n description: spec.description,\n isGlobal,\n });\n }\n }\n\n // Role grants. Present-or-absent only: a grant this manifest does not\n // mention is left alone (§27.6 rule 3), which is why there is no revoke.\n for (const spec of manifest.roles ?? []) {\n const roleId = resolved.roles.get(spec.key);\n const held = roleId ? snapshot.roleGrants.get(roleId) : undefined;\n for (const grant of spec.grants ?? []) {\n const permissionId = resolved.permissions.get(grant.permission);\n const present = !!held && !!permissionId && held.includes(permissionId);\n push(\n present ? 'no-change' : 'create',\n 'role-grant',\n spec.key,\n `role ${JSON.stringify(spec.name)} grants ${JSON.stringify(grant.permission)}`,\n present\n ? { kind: 'noop' }\n : {\n kind: 'grant-permission',\n role: spec.key,\n permission: grant.permission,\n effect: grant.effect,\n scopes: grant.scopes ?? [],\n },\n );\n }\n }\n\n for (const spec of manifest.groups ?? []) {\n const found = snapshot.groups.find((g) => g.name === spec.name);\n const summary = `group ${JSON.stringify(spec.name)}`;\n if (found) {\n resolved.groups.set(spec.key, found.id);\n const drifted = found.description !== spec.description;\n push(\n drifted ? 'update' : 'no-change',\n 'group',\n spec.key,\n summary,\n drifted\n ? { kind: 'update-group', key: spec.key, description: spec.description }\n : { kind: 'noop' },\n );\n } else {\n push('create', 'group', spec.key, summary, {\n kind: 'create-group',\n key: spec.key,\n name: spec.name,\n description: spec.description,\n });\n }\n }\n\n for (const spec of manifest.groups ?? []) {\n const groupId = resolved.groups.get(spec.key);\n for (const roleKey of spec.roles ?? []) {\n const roleId = resolved.roles.get(roleKey);\n const present =\n !!roleId && !!groupId && (snapshot.roleGroups.get(roleId) ?? []).includes(groupId);\n push(\n present ? 'no-change' : 'create',\n 'group-role',\n spec.key,\n `group ${JSON.stringify(spec.name)} holds role ${JSON.stringify(roleKey)}`,\n present ? { kind: 'noop' } : { kind: 'assign-role-to-group', role: roleKey, group: spec.key },\n );\n }\n }\n\n for (const spec of manifest.users ?? []) {\n const found = snapshot.users.find((u) => u.username === spec.username);\n const summary = `user ${JSON.stringify(spec.username)}`;\n if (found) {\n resolved.users.set(spec.key, found.id);\n const drifted = found.email !== spec.email;\n push(\n drifted ? 'update' : 'no-change',\n 'user',\n spec.key,\n summary,\n drifted ? { kind: 'update-user', key: spec.key, email: spec.email } : { kind: 'noop' },\n );\n } else {\n // §27.6 rule 1: catch this here, before anything has been written,\n // rather than halfway through an apply.\n if (!spec.initialPassword) {\n throw new NetworkError(\n `user ${JSON.stringify(spec.username)} does not exist and would be created, but the ` +\n `spec carries no initialPassword`,\n );\n }\n push('create', 'user', spec.key, summary, {\n kind: 'create-user',\n key: spec.key,\n username: spec.username,\n email: spec.email,\n password: spec.initialPassword,\n });\n }\n }\n\n for (const spec of manifest.users ?? []) {\n const userId = resolved.users.get(spec.key);\n for (const roleKey of spec.roles ?? []) {\n const roleId = resolved.roles.get(roleKey);\n const present =\n !!roleId && !!userId && (snapshot.roleUsers.get(roleId) ?? []).includes(userId);\n push(\n present ? 'no-change' : 'create',\n 'user-role',\n spec.key,\n `user ${JSON.stringify(spec.username)} holds role ${JSON.stringify(roleKey)}`,\n present ? { kind: 'noop' } : { kind: 'assign-role-to-user', role: roleKey, user: spec.key },\n );\n }\n for (const groupKey of spec.groups ?? []) {\n const groupId = resolved.groups.get(groupKey);\n const present =\n !!groupId && !!userId && (snapshot.groupMembers.get(groupId) ?? []).includes(userId);\n push(\n present ? 'no-change' : 'create',\n 'group-member',\n spec.key,\n `user ${JSON.stringify(spec.username)} is in group ${JSON.stringify(groupKey)}`,\n present ? { kind: 'noop' } : { kind: 'add-group-member', group: groupKey, user: spec.key },\n );\n }\n }\n\n return out;\n }\n\n // -------------------------------------------------------------------\n // Apply\n // -------------------------------------------------------------------\n\n async #execute(\n steps: Array<{ action: PlannedAction; step: Step }>,\n resolved: Resolved,\n ): Promise<ApplyReport> {\n const out: ApplyReport['steps'] = [];\n let stopped = false;\n for (const { action, step } of steps) {\n if (stopped) {\n out.push({ action, outcome: { status: 'not-attempted' } });\n continue;\n }\n if (step.kind === 'noop') {\n out.push({ action, outcome: { status: 'unchanged' } });\n continue;\n }\n try {\n await this.#run(step, resolved);\n const outcome: StepOutcome =\n action.change === 'create' ? { status: 'created' } : { status: 'updated' };\n out.push({ action, outcome });\n } catch (err) {\n stopped = true;\n out.push({\n action,\n outcome: { status: 'failed', message: err instanceof Error ? err.message : String(err) },\n });\n }\n }\n return { steps: out };\n }\n\n async #run(step: Step, resolved: Resolved): Promise<void> {\n const c = this.#client;\n switch (step.kind) {\n case 'noop':\n return;\n case 'create-resource': {\n const created = await c.resources.create({\n name: step.name,\n resource_type: step.resourceType,\n parent_id: step.parent ? lookup(resolved.resources, step.parent, 'resource') : undefined,\n });\n resolved.resources.set(step.key, created.id);\n return;\n }\n case 'update-resource':\n await c.resources.update(lookup(resolved.resources, step.key, 'resource'), {\n resource_type: step.resourceType,\n });\n return;\n case 'create-scope': {\n const created = await c.scopes.create(\n lookup(resolved.resources, step.resource, 'resource'),\n { name: step.name, description: step.description },\n );\n resolved.scopes.set(step.key, created.id);\n return;\n }\n case 'create-permission': {\n const created = await c.permissions.create({\n action: step.action,\n description: step.description,\n });\n resolved.permissions.set(step.key, created.id);\n return;\n }\n case 'update-permission':\n await c.permissions.update(lookup(resolved.permissions, step.key, 'permission'), {\n description: step.description,\n });\n return;\n case 'create-role': {\n const created = await c.roles.create({\n name: step.name,\n description: step.description,\n is_global: step.isGlobal,\n });\n resolved.roles.set(step.key, created.id);\n return;\n }\n case 'update-role':\n await c.roles.update(lookup(resolved.roles, step.key, 'role'), {\n description: step.description,\n is_global: step.isGlobal,\n });\n return;\n case 'grant-permission':\n await c.roles.grantPermission(lookup(resolved.roles, step.role, 'role'), {\n permission_id: lookup(resolved.permissions, step.permission, 'permission'),\n effect: step.effect,\n scope_ids: step.scopes.length\n ? step.scopes.map((s) => lookup(resolved.scopes, s, 'scope'))\n : undefined,\n });\n return;\n case 'create-group': {\n const created = await c.groups.create({ name: step.name, description: step.description });\n resolved.groups.set(step.key, created.id);\n return;\n }\n case 'update-group':\n await c.groups.update(lookup(resolved.groups, step.key, 'group'), {\n description: step.description,\n });\n return;\n case 'assign-role-to-group':\n await c.roles.assignToGroup(lookup(resolved.roles, step.role, 'role'), {\n group_id: lookup(resolved.groups, step.group, 'group'),\n });\n return;\n case 'create-user': {\n const created = await c.users.create({\n username: step.username,\n email: step.email,\n password: step.password,\n });\n resolved.users.set(step.key, created.id);\n return;\n }\n case 'update-user':\n await c.users.update(lookup(resolved.users, step.key, 'user'), { email: step.email });\n return;\n case 'assign-role-to-user':\n await c.roles.assignToUser(lookup(resolved.roles, step.role, 'role'), {\n user_id: lookup(resolved.users, step.user, 'user'),\n });\n return;\n case 'add-group-member':\n await c.groups.addMember(lookup(resolved.groups, step.group, 'group'), {\n user_id: lookup(resolved.users, step.user, 'user'),\n });\n return;\n }\n }\n}\n\n/**\n * Resolve a manifest key to the id an earlier step recorded.\n *\n * A miss here is an SDK bug, not a user error — validation already rejected\n * dangling references and the plan orders producers before consumers — so it\n * says so rather than blaming the manifest.\n */\nfunction lookup(map: Map<string, string>, key: string, kind: string): string {\n const id = map.get(key);\n if (id === undefined) {\n throw new NetworkError(\n `internal: ${kind} key ${JSON.stringify(key)} was consumed before the step that creates it ran`,\n );\n }\n return id;\n}\n","/**\n * Pagination for the §27 management surface.\n *\n * Twenty of the 147 operations take `offset`/`limit` and answer with the\n * envelope `{ items, total, offset, limit }`. The other thirteen collection\n * reads answer with a bare array and are **not** paginated — §27.4 rule 4\n * forbids modelling those as a page, because a `Page` reporting\n * `total === items.length` is indistinguishable from a real one right up to\n * the moment a caller relies on `total`.\n */\n\n/**\n * Where a paginated read starts, and how much of it to take.\n *\n * `limit` is deliberately optional with no SDK-side default: §27.4 rule 4\n * forbids silently truncating, and a client-side default does exactly that\n * while leaving the caller no way to tell a short page from a complete one.\n */\nexport interface PageRequest {\n /** How many items to skip. Defaults to `0`. */\n offset?: number;\n /** How many items to take. Omitted lets the server decide. */\n limit?: number;\n /**\n * Free-text filter applied by the **server**, before `offset`/`limit`.\n *\n * Matched case-insensitively against the identifying fields of whatever is\n * being listed — a name or username, plus the record id, so a UUID out of a\n * log line pastes in as-is. `total` on the resulting {@link Page} counts\n * *matches*, not rows, which is what lets a pager built on it show a page\n * count belonging to the result set it is paging.\n *\n * It lives here rather than as a third argument on each of the twenty\n * generated `list` methods (§27.4 rule 4), and that is what makes the\n * auto-paging `listAll` form carry it across every request of the walk — a\n * walk that filtered its first request and not the rest would return the\n * matches followed by the unfiltered tail.\n *\n * Omitted sends no `search` parameter. An empty or whitespace-only term is\n * treated as omitted: a box that fires on every keystroke sends `?search=`\n * the moment it is cleared, and \"rows containing the empty string\" is a\n * different question.\n *\n * The server caps the term's length. This SDK deliberately does not\n * re-implement that cap — a client-side truncation the server would not have\n * made is a silently different query.\n */\n search?: string;\n}\n\n/** One page of a paginated management read. */\nexport interface Page<T> {\n /** The items on this page. */\n items: T[];\n /** How many items exist in the whole set, across every page. */\n total: number;\n /** The offset this page starts at. */\n offset: number;\n /** The page size the server applied. */\n limit: number;\n}\n\n/**\n * The query parameters a {@link PageRequest} contributes.\n *\n * `limit` is omitted entirely when unset rather than sent as `0` — the server\n * reads `limit=0` as \"none\", which would return an empty page.\n *\n * @internal\n */\nexport function pageQuery(page: PageRequest): Record<string, string | undefined> {\n return {\n offset: String(page.offset ?? 0),\n limit: page.limit === undefined ? undefined : String(page.limit),\n search: normalizeSearch(page.search),\n };\n}\n\n/**\n * The trimmed term, or `undefined` when there is nothing to filter on.\n *\n * Mirrors the server's own normalisation minus the length cap, which is the\n * server's to apply — see {@link PageRequest.search}.\n *\n * @internal\n */\nexport function normalizeSearch(term: string | undefined): string | undefined {\n const trimmed = term?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/** Whether another page follows `page`. */\nexport function hasMore<T>(page: Page<T>): boolean {\n return page.items.length > 0 && page.offset + page.items.length < page.total;\n}\n\n/**\n * Walk a paginated read to exhaustion, concatenating every page.\n *\n * The `list_all` shape §27.4 rule 4 requires. The walk stops on an empty page\n * even when `total` disagrees, so a misreporting server costs one wasted\n * request rather than an unbounded loop.\n *\n * @internal — each generated `list` exposes this as its own `…All` method.\n */\nexport async function collectPages<T>(\n start: PageRequest,\n fetch: (page: PageRequest) => Promise<Page<T>>,\n): Promise<T[]> {\n let request: PageRequest = {\n offset: start.offset ?? 0,\n limit: start.limit,\n search: start.search,\n };\n const out: T[] = [];\n for (;;) {\n const page = await fetch(request);\n out.push(...page.items);\n const next = page.offset + page.items.length;\n if (page.items.length === 0 || next >= page.total) return out;\n // `search` is carried, not dropped (§27.4 rule 4). A walk that filtered\n // only its first request would concatenate the matches with the\n // unfiltered remainder, which reads as a server bug from the caller's side.\n request = { offset: next, limit: request.limit, search: request.search };\n }\n}\n","/**\n * The §27.4 rule 7 error sub-types.\n *\n * §2 fixes the taxonomy at three error types and §27 does not widen it. What\n * it adds is a *classification* inside two of them, because a management\n * surface produces refusals §2 never had to describe — §2 has no 404 row at\n * all, since nothing before §27 could return one.\n *\n * TypeScript has real subclassing, so these are subclasses: every\n * `catch (e) { if (e instanceof AuthzError) … }` written before §27 keeps\n * working, and a caller who needs the distinction narrows further.\n */\n\nimport { AuthzError, NetworkError } from '../core/errors.js';\n\n/** One field-level complaint inside a {@link ValidationError}. */\nexport interface FieldError {\n /** The offending field's name, as the server names it. */\n field: string;\n /** What is wrong with it. */\n message: string;\n}\n\n/**\n * HTTP 404 — the resource does not exist, **or** belongs to another tenant.\n *\n * The server answers identically in both cases on purpose: a distinguishable\n * \"exists but not yours\" lets a caller enumerate another tenant's ids. That is\n * why this is an {@link AuthzError} rather than a category of its own — in a\n * multi-tenant IAM the two really are one outcome.\n */\nexport class NotFoundError extends AuthzError {\n /** The registry operation that found nothing, e.g. `\"users.get\"`. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'NotFoundError';\n this.operation = operation;\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * HTTP 409 — a uniqueness or state conflict, such as a role name already taken.\n *\n * Never retried (§27.4 rule 8): a 409 is the server telling the truth, not a\n * transient fault, and a retry produces the identical answer one round-trip\n * later.\n */\nexport class ConflictError extends AuthzError {\n /** The registry operation that conflicted. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'ConflictError';\n this.operation = operation;\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * HTTP 400/422 — the request was rejected.\n *\n * §2 maps 400 to `NetworkError`, described as an \"SDK programming error\". That\n * description was written when nothing but the SDK itself could produce a 400.\n * On this surface a 400 is usually a *user's* invalid input — an email that is\n * not an email, a slug already taken — and an application needs to tell that\n * from a broken socket without matching on message text. The parent type is\n * inherited from §2 rather than chosen here.\n */\nexport class ValidationError extends NetworkError {\n /** The HTTP status the server answered with — 400 or 422. */\n readonly status: number;\n /** The registry operation that was rejected. */\n readonly operation: string;\n /** Per-field detail, where the server sent any. Empty is normal. */\n readonly fields: FieldError[];\n\n constructor(operation: string, status: number, message: string, fields: FieldError[]) {\n super(message);\n this.name = 'ValidationError';\n this.status = status;\n this.operation = operation;\n this.fields = fields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Pull field-level detail out of an error body, on a best-effort basis.\n *\n * Two shapes are recognised — an array of `{field, message}` and an object\n * keyed by field name. A body in neither shape yields no fields rather than an\n * error: failing to parse an error body would replace a useful message with a\n * useless one.\n *\n * @internal\n */\nexport function parseFieldErrors(body: unknown): FieldError[] {\n if (!body || typeof body !== 'object') return [];\n const errors = (body as { errors?: unknown }).errors;\n if (Array.isArray(errors)) {\n return errors.filter(\n (e): e is FieldError =>\n !!e && typeof e === 'object' && typeof (e as FieldError).field === 'string',\n );\n }\n if (errors && typeof errors === 'object') {\n return Object.entries(errors as Record<string, unknown>)\n .filter(([, v]) => typeof v === 'string')\n .map(([field, message]) => ({ field, message: message as string }));\n }\n return [];\n}\n","/**\n * The one request path every §27 management operation goes through.\n *\n * §27.8 is explicit that the generated layer MUST sit on the SDK's existing\n * request path and MUST NOT build its own. That is what this module is: 147\n * generated operations all funnel into {@link sendManagement}, so they inherit\n * §3 (CSRF), §4 (the cookie jar), §5 (`X-Tenant-ID`), §6 (TLS), §9 (the\n * reactive single-flight refresh the response interceptor already performs),\n * §16 (retry) and §19 (telemetry) by construction rather than by 147\n * opportunities to forget one.\n */\n\nimport type { AxiosResponse } from 'axios';\n\nimport { AuthError, mapHttpStatusToError } from '../core/index.js';\nimport { withRetry } from '../rest/retry.js';\nimport type { AxiamClient } from '../rest/client.js';\nimport { ConflictError, NotFoundError, ValidationError, parseFieldErrors } from './errors.js';\n\n/** The HTTP verbs this surface uses. */\nexport type ManagementMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** One management call, fully resolved. */\nexport interface ManagementCall {\n /** `\"users.create\"` — the registry's namespace-qualified operation name. */\n operation: string;\n /** The HTTP verb. Only `GET` is retry-eligible (§27.4 rule 8). */\n method: ManagementMethod;\n /** `\"/api/v1/users/{user_id}\"`, ids **not** substituted — the §19.1 label. */\n pathTemplate: string;\n /** The same path with ids substituted, ready to send. */\n path: string;\n /** Query parameters; `undefined` values are dropped rather than sent empty. */\n query?: Record<string, string | undefined>;\n /** The request body, already converted to its wire shape. */\n body?: unknown;\n}\n\n/**\n * Issue a management request and return its parsed body.\n *\n * @internal — reached through the generated namespace handles.\n */\nexport async function sendManagement<T>(client: AxiamClient, call: ManagementCall): Promise<T> {\n // §18.1 rule 4: use-after-close is an error, never a silent reconnect.\n client.ensureOpen();\n\n // §27.4 rule 1: no session, no wire call. Letting the request go out trades\n // a clear local error for a 401 that then enters the §9 refresh guard and\n // fails there, two indirections from the actual mistake.\n if (!client.session.authenticated) {\n throw new AuthError(\n `${call.operation}: no active session — call login() before using the management API`,\n );\n }\n\n const params = Object.fromEntries(\n Object.entries(call.query ?? {}).filter(([, v]) => v !== undefined),\n );\n\n const attempt = async (n: number): Promise<T> => {\n const done = client.telemetry.startRequest(call.operation, call.method, call.pathTemplate, n);\n try {\n const response: AxiosResponse<T> = await client.session.axios.request<T>({\n method: call.method,\n url: call.path,\n params,\n data: call.body,\n });\n done(response.status, 'success');\n return response.data;\n } catch (err) {\n done(statusOf(err), 'failure');\n throw mapManagementError(call.operation, err);\n }\n };\n\n // §16.2 and §27.4 rule 8: only reads are retried, and only through the\n // shared runner so the backoff, jitter and `Retry-After` floor are the\n // contract's rather than this module's. No write here is retriable, not even\n // the ones that look idempotent — generating a certificate twice mints two,\n // and rotating a secret twice invalidates the one the caller already stored.\n return withRetry(attempt, {\n ...client.retryOptions(call.operation),\n idempotent: call.method === 'GET',\n });\n}\n\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 bodyOf(err: unknown): unknown {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { data?: unknown } }).response?.data;\n }\n return undefined;\n}\n\n/**\n * Map a failed management response onto the §2 taxonomy.\n *\n * Delegates to the shared `mapHttpStatusToError` for everything §27 does not\n * classify, so the two mappers cannot drift: this function's whole job is the\n * three statuses §27.4 rule 7 names, and 404 is the one §2 genuinely lacks.\n */\nfunction mapManagementError(operation: string, err: unknown): unknown {\n const status = statusOf(err);\n if (status === undefined) {\n // No response at all — a transport failure. The shared mapper owns it.\n return mapHttpStatusToError(0, `${operation}: request failed`, { cause: err });\n }\n const body = bodyOf(err);\n const detail = describe(body);\n\n if (status === 404) {\n return new NotFoundError(\n operation,\n `${operation}: not found (or not visible to this tenant)${detail}`,\n );\n }\n if (status === 409) {\n return new ConflictError(operation, `${operation}: conflict${detail}`);\n }\n if (status === 400 || status === 422) {\n return new ValidationError(\n operation,\n status,\n `${operation}: request rejected${detail}`,\n parseFieldErrors(body),\n );\n }\n return mapHttpStatusToError(status, `${operation}${detail}`, { cause: err });\n}\n\nfunction describe(body: unknown): string {\n if (typeof body === 'string' && body) return `: ${body}`;\n if (body && typeof body === 'object') {\n const message = (body as { message?: unknown; error?: unknown }).message\n ?? (body as { error?: unknown }).error;\n if (typeof message === 'string') return `: ${message}`;\n }\n return '';\n}\n","/**\n * Where `{org_id}` and `{tenant_id}` come from — CONTRACT §27.4 rule 3.\n *\n * Thirty-one of the 147 routes carry one or both, and in almost every call they\n * are the client's own. Making the caller restate them every time is ceremony\n * that gets wrapped in a helper anyway; making them impossible to override is\n * worse, because a platform-admin token legitimately administers a tenant\n * other than the one its client was built with. So they default from the\n * client, and every handle that needs one exposes an override.\n */\n\nimport { NetworkError } from '../core/errors.js';\nimport type { AxiamClient } from '../rest/client.js';\n\n/**\n * Per-handle overrides for the two implicit path parameters.\n *\n * Named `NamespaceScope` rather than `Scope` because the server's schema set\n * already has a `Scope` — the sub-resource kind §27.1's `scopes` namespace\n * administers — and two exported types of that name is one too many.\n */\nexport interface NamespaceScope {\n /** Override for `{org_id}`. Absent means \"the client's\". */\n orgId?: string;\n /** Override for `{tenant_id}`. Absent means \"the client's\". */\n tenantId?: string;\n}\n\n/**\n * Resolve `{org_id}`: the handle's override, else the client's.\n *\n * A client built with `orgSlug` and no `orgId` fails **here**, with no wire\n * call. §27.4 rule 3 forbids resolving the slug behind the caller's back: a\n * silent extra round-trip on an admin path is what §12.1 rule 2 refuses for\n * `/oauth2/*`, and for the same reason — the caller cannot see it, cannot\n * cache it, and pays for it on every call.\n *\n * @internal\n */\nexport function resolveOrg(client: AxiamClient, scope: NamespaceScope, operation: string): string {\n if (scope.orgId) return scope.orgId;\n const configured = client.session.orgId;\n if (configured) return configured;\n const slug = client.session.orgSlug;\n throw new NetworkError(\n slug\n ? `${operation}: this route needs an organization UUID, but the client was built with ` +\n `orgSlug ${JSON.stringify(slug)}. Rebuild it with orgId, or name one on the handle ` +\n `with .inOrg(...).`\n : `${operation}: this route needs an organization UUID and the client has none. Build ` +\n `the client with orgId, or name one on the handle with .inOrg(...).`,\n );\n}\n\n/**\n * Resolve `{tenant_id}` where it names the *context*, not the object.\n *\n * Namespaces where `{tenant_id}` names the thing being acted on — `tenants`,\n * and the signing CAs under `ca_certificates` — take it as an ordinary\n * argument instead and never reach this.\n *\n * @internal\n */\nexport function resolveTenant(client: AxiamClient, scope: NamespaceScope, operation: string): string {\n if (scope.tenantId) return scope.tenantId;\n const configured = client.session.tenantId ?? client.session.resolvedTenantId;\n if (configured) return configured;\n throw new NetworkError(\n `${operation}: this route needs a tenant UUID, but the client was built with ` +\n `tenantSlug ${JSON.stringify(client.session.tenantSlug)}. Rebuild it with tenantId, or ` +\n `name one on the handle with .forTenant(...).`,\n );\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `organizations` management namespace (CONTRACT §27.1).\n *\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `organizations` namespace handle.\n *\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class OrganizationsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): OrganizationsApi {\n return new OrganizationsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations` */\n async list(page: PageRequest = {}): Promise<Page<models.Organization>> {\n const wire = await sendManagement<Page<models.Organization>>(this.#client, {\n operation: 'organizations.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations',\n path: '/api/v1/organizations',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `organizations.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Organization[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /** `GET /api/v1/organizations/{org_id}` */\n async get(): Promise<models.Organization> {\n const orgId = resolveOrg(this.#client, this.#scope, \"organizations.get\");\n const wire = await sendManagement<models.Organization>(this.#client, {\n operation: 'organizations.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}',\n path: `/api/v1/organizations/${orgId}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(body: models.UpdateOrganizationRequest): Promise<models.Organization> {\n const orgId = resolveOrg(this.#client, this.#scope, \"organizations.update\");\n const wire = await sendManagement<models.Organization>(this.#client, {\n operation: 'organizations.update',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}',\n path: `/api/v1/organizations/${orgId}`,\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `tenants` management namespace (CONTRACT §27.1).\n *\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `tenants` namespace handle.\n *\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class TenantsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): TenantsApi {\n return new TenantsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants` */\n async list(page: PageRequest = {}): Promise<Page<models.Tenant>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.list\");\n const wire = await sendManagement<Page<models.Tenant>>(this.#client, {\n operation: 'tenants.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants',\n path: `/api/v1/organizations/${orgId}/tenants`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `tenants.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Tenant[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateTenantRequest): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.create\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.create',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants',\n path: `/api/v1/organizations/${orgId}/tenants`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants/{tenant_id}` */\n async get(tenantId: string): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.get\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/tenants/{tenant_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(tenantId: string, body: models.UpdateTenant): Promise<models.Tenant> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.update\");\n const wire = await sendManagement<models.Tenant>(this.#client, {\n operation: 'tenants.update',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/organizations/{org_id}/tenants/{tenant_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(tenantId: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.delete\");\n await sendManagement<void>(this.#client, {\n operation: 'tenants.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants/{tenant_id}/audit-export`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async exportAudit(tenantId: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"tenants.export_audit\");\n await sendManagement<void>(this.#client, {\n operation: 'tenants.export_audit',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/audit-export',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/audit-export`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n\n/**\n * Request and response types for the CONTRACT §27 management surface.\n *\n * Three shapes recur and are worth knowing before reading:\n *\n * - **Sparse update bodies.** Every field is optional, and an omitted field is\n * *absent from the wire body* rather than sent as `null` — so a body\n * carrying one field changes one field (§27.4 rule 5). This SDK cannot\n * express \"set this field to null\", which is the safe direction to be\n * inexpressive in.\n * - **Replacement bodies.** `SetOrgSettings`, the organization email config,\n * `WebauthnAttestationPolicy` and `SetMtlsTrustAnchor` have required\n * fields, because a `PUT` on those routes replaces rather than patches.\n * TypeScript will not let you build one half-filled, which is the point.\n * - **Types carrying a secret.** These hold a {@link Sensitive} and come with\n * a private wire twin, because `Sensitive.toJSON()` returns\n * `\"[SENSITIVE]\"` — serializing the public type directly would send the\n * placeholder to the server, and deserializing into it would leave the\n * secret an ordinary string.\n */\nimport { Sensitive } from '../core/sensitive.js';\n\n/**\n * Drops a `tenant_scope` that names no tenants.\n *\n * CONTRACT.md §5.2.3 rule 1: the server refuses `tenant_scope: []` with\n * `400`. An assignment reaching no tenant contributes nothing anywhere, so it\n * is a grant that does not exist rather than a restriction, and the server\n * declines to guess which was meant.\n *\n * `JSON.stringify` already drops `undefined`, so the absent case needs no\n * help. `[]` is the one that does: the natural way to build the field is to\n * collect into an array and pass it, which yields `[]` for \"no tenants named\"\n * and would put the refused shape on the wire. Both spellings of absent\n * therefore travel the same way — by not appearing.\n *\n * Returns the body unchanged when there is nothing to drop, so the common\n * path allocates nothing.\n */\nexport function omitEmptyTenantScope<T>(body: T): T {\n if (\n body\n && typeof body === 'object'\n && 'tenant_scope' in body\n && Array.isArray((body as { tenant_scope?: unknown }).tenant_scope)\n && (body as { tenant_scope: unknown[] }).tenant_scope.length === 0\n ) {\n const { tenant_scope: _dropped, ...rest } = body as Record<string, unknown>;\n return rest as T;\n }\n return body;\n}\n\n/**\n * `ActorType` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ActorType =\n | \"User\"\n | \"ServiceAccount\"\n | \"System\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `AddMemberRequest` (generated from openapi.json). */\nexport interface AddMemberRequest {\n /** `user_id`. */\n user_id: string;\n}\n\n/** `AddServiceAccountMemberRequest` (generated from openapi.json). */\nexport interface AddServiceAccountMemberRequest {\n /** `service_account_id`. */\n service_account_id: string;\n}\n\n/**\n * API-based provider configuration (SendGrid, Postmark, Resend, Brevo).\n *\n * `api_key` follows the same write-only + omit-preserving contract as\n * [`SmtpConfig::password`] (D-01/D-02).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface ApiProviderConfig {\n /** Override base URL (useful for testing / self-hosted instances). */\n api_url?: string | null;\n}\n\n/** `AssignRoleToGroupRequest` (generated from openapi.json). */\nexport interface AssignRoleToGroupRequest {\n /** `group_id`. */\n group_id: string;\n /** `resource_id`. */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n}\n\n/** `AssignRoleToServiceAccountRequest` (generated from openapi.json). */\nexport interface AssignRoleToServiceAccountRequest {\n /** `resource_id`. */\n resource_id?: string | null;\n /** `service_account_id`. */\n service_account_id: string;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n}\n\n/** `AssignRoleToUserRequest` (generated from openapi.json). */\nexport interface AssignRoleToUserRequest {\n /** `resource_id`. */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches.\n *\n * Only meaningful for an assignment made in an organization's scope, whose\n * global roles otherwise reach every tenant of the organization; naming\n * tenants here confines the assignment to those and to nothing else, the\n * organization's own scope included. Omitted — the default — reaches\n * wherever the role does.\n *\n * Refused with 400 outside an organization scope, when empty, and when it\n * names a tenant of another organization or the organization's own scope\n * tenant.\n */\n tenant_scope?: string[] | null;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * What attestation conveyance a registration ceremony requests, and whether\n * the policy is enforced at all.\n *\n * `None` is the default and reproduces today's behavior byte-for-byte:\n * `evaluate` allows every registration unconditionally, with no MDS lookup\n * (D8 step 1).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AttestationMode =\n | \"none\"\n | \"indirect\"\n | \"direct_required\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `AuditLogEntry` (generated from openapi.json). */\nexport interface AuditLogEntry {\n /** `action`. */\n action: string;\n /** `actor_id`. */\n actor_id: string;\n /** `actor_type`. */\n actor_type: ActorType;\n /** `id`. */\n id: string;\n /** `ip_address`. */\n ip_address?: string | null;\n /** `metadata`. */\n metadata: unknown;\n /** `outcome`. */\n outcome: AuditOutcome;\n /** `resource_id`. */\n resource_id?: string | null;\n /** `tenant_id`. */\n tenant_id: string;\n /** `timestamp`. */\n timestamp: string;\n}\n\n/**\n * `AuditOutcome` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AuditOutcome =\n | \"Success\"\n | \"Failure\"\n | \"Denied\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Whether this client's authorization requests may carry OpenID Connect's\n * authentication-request parameters, or whether they are ignored (X7.1).\n *\n * The bundle this governs is `prompt`, `max_age`, `acr_values`, `claims`,\n * `id_token_hint`, `login_hint`, `display`, `ui_locales` and\n * `claims_locales`. It is **one** field rather than nine booleans for the\n * same reason [`ClientProfile`] is one field rather than a dozen: a client\n * that honours `max_age` but ignores `prompt=none` is not \"mostly\n * conformant\", it is a client a relying party cannot reason about.\n *\n * [`Ignore`](Self::Ignore) is the serde default and is exactly what AXIAM\n * has always done — unknown authorization-request parameters are dropped by\n * the query deserialiser and never reach a decision. Every row written\n * before schema v54 therefore decodes to the behaviour it already had.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type AuthnRequestParamsMode =\n | \"ignore\"\n | \"honour\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Request to bind a certificate to a service account. */\nexport interface BindCertificate {\n /** `certificate_id`. */\n certificate_id: string;\n}\n\n/**\n * A CA (Certificate Authority) certificate at the organization level.\n *\n * CA certificates are the root of trust for all tenant certificates within\n * the organization. Private keys for signing CAs are encrypted with\n * AES-256-GCM and stored separately; non-signing CAs only store the public\n * certificate.\n */\nexport interface CaCertificate {\n /**\n * The issuers above [`Self::public_cert_pem`], concatenated PEM, nearest\n * issuer first and the root last.\n *\n * `None` for a CA that is its own root, which is every CA AXIAM generated\n * before Vault's PKI engine was an option. Present for a `vault_pki` CA,\n * where it is the only copy of the root certificate anything outside Vault\n * will ever see — a relying party cannot validate an AXIAM-issued leaf\n * without it, and `root/generate/internal` returns it exactly once.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /**\n * Which custodian holds this CA's signing key.\n *\n * Recorded per CA rather than read from configuration, so adopting a new\n * custodian does not strand the CAs that already exist. Not secret — an\n * operator needs to see it, and it discloses only where a key is kept.\n */\n key_custody?: string;\n /**\n * Where the custodian put the key. A Vault path under its mount; `None` for\n * database custody, whose locator is the row itself.\n */\n key_locator?: string | null;\n /**\n * Whether this CA is offered as a trust anchor for mutual TLS.\n *\n * When set, the server exports this CA's **public** certificate to the\n * bundle named by `AXIAM__SERVER__TLS__CLIENT_CA_BUNDLE_PATH` at startup and\n * turns client-certificate authentication on (`optional`) if the operator\n * has not configured it explicitly. A client presenting a certificate that\n * chains to this CA is then verified by the TLS layer itself, which is what\n * `axiam_pki::mtls` needs to authenticate an IoT device or a service account\n * by certificate rather than by secret.\n *\n * # What is and is not copied\n *\n * Only `public_cert_pem` — the certificate. The **private key stays where\n * its custodian put it** (Vault, or sealed into the row) and is never\n * written to the server volume. A trust anchor is public by construction: it\n * is what the server hands every client during the TLS handshake, and every\n * device that has to validate the chain already holds a copy.\n *\n * # Why a restart\n *\n * rustls builds its `RootCertStore` once, when the listener is constructed,\n * and actix-web binds that config for the process's life. Toggling this\n * changes what the *next* boot trusts, and the API says so in its response\n * rather than pretending the change took effect.\n *\n * Defaults to `false`, so a deployment that never touches this keeps exactly\n * the TLS posture it has today.\n */\n mtls_trust_anchor?: boolean;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** The organization this CA belongs to. */\n organization_id: string;\n /**\n * The CA in this organization that signed this one.\n *\n * `None` for an organization-level CA, which is either self-signed or\n * imported and has no parent inside AXIAM.\n */\n parent_ca_id?: string | null;\n /**\n * PEM-encoded public certificate.\n *\n * The certificate that *signs*, which under `vault_pki` custody is the\n * intermediate rather than the root beneath which it was created.\n */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=ACME Corp Root CA`). */\n subject: string;\n /**\n * The tenant this CA signs for, when it is a tenant signing CA.\n *\n * `None` for an organization-level CA — the trust anchor, and the only kind\n * that existed before tenant signing CAs. `Some` for an intermediate created\n * under one, which exists so a tenant's user, service and device\n * certificates chain through a CA that can be revoked and replaced without\n * touching the anchor the rest of the estate trusts.\n */\n tenant_id?: string | null;\n}\n\n/**\n * A tenant-level certificate for users, services, or IoT devices.\n *\n * Certificates are signed by the organization's CA. The private key is\n * returned once on generation and never stored by AXIAM.\n */\nexport interface Certificate {\n /**\n * Resolved by the list projection only.\n *\n * The server resolves this for a whole page in one query, so it is populated\n * by the `list` operation and is absent from `get` (CONTRACT §27.11 rule 4).\n * Absent there means \"this read does not carry it\", not \"there is nothing\n * bound\" — the SDK does not issue a second request to fill it in.\n */\n bound_service_account_id?: string | null;\n /** `cert_type`. */\n cert_type: CertificateType;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** The CA certificate that signed this certificate. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** Arbitrary key-value metadata (e.g., device serial, user ID binding). */\n metadata: unknown;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** PEM-encoded public certificate. */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=device-001`). */\n subject: string;\n /** The tenant this certificate belongs to. */\n tenant_id: string;\n}\n\n/** Certificate issuance constraints. */\nexport interface CertificatePolicy {\n /** `default_cert_validity_days`. */\n default_cert_validity_days: number;\n /** `max_cert_validity_days`. */\n max_cert_validity_days: number;\n}\n\n/**\n * Status of a certificate in its lifecycle.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificateStatus =\n | \"Active\"\n | \"Revoked\"\n | \"Expired\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * The purpose for which a certificate was issued.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificateType =\n | \"User\"\n | \"Service\"\n | \"Device\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * FIDO certification level, as recorded in an MDS `statusReports` entry's\n * `FIDO_CERTIFIED*` status.\n *\n * Variant order is significant: `derive(PartialOrd, Ord)` gives `L1 < L1Plus\n * < L2 < L2Plus < L3 < L3Plus`, which `WebauthnAttestationPolicy::evaluate`\n * (D8 step 9) relies on directly for the `min_certification` boundary check\n * (`entry_level >= policy_min`).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type CertificationLevel =\n | \"L1\"\n | \"L1Plus\"\n | \"L2\"\n | \"L2Plus\"\n | \"L3\"\n | \"L3Plus\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * How a client proves its identity at the token endpoint (RFC 8705 §2, OIDC\n * Core §9 naming).\n *\n * Only the methods AXIAM actually implements are representable. There is\n * deliberately no `none` variant: every AXIAM client is confidential today\n * (see `handle_authorization_code`), and adding a public-client value here\n * before the rest of the server understands one would let an operator\n * register a client whose authentication is silently skipped.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ClientAuthMethod =\n | \"client_secret_post\"\n | \"client_secret_basic\"\n | \"tls_client_auth\"\n | \"self_signed_tls_client_auth\"\n | \"private_key_jwt\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Which security posture a client is registered under (X5.1).\n *\n * This is the FAPI \"one switch\". FAPI 2.0 is not a single feature but a\n * bundle of constraints — mandatory PAR, mandatory PKCE with `S256`,\n * mandatory strong client authentication, mandatory sender-constrained\n * tokens, and a refusal of every relaxation the base specs permit. Encoding\n * them as one profile rather than a dozen independent booleans means an\n * operator cannot register a client that is *nearly* FAPI, and a reviewer\n * can answer \"is this client financial-grade?\" by reading one field.\n *\n * The same philosophy as the rate-limit postures: ordinary clients see no\n * behaviour change at all, because [`Standard`](Self::Standard) is the serde\n * default and every row written before schema v38 decodes to it.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ClientProfile =\n | \"standard\"\n | \"fapi2\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** One credential's compliance outcome (D9). */\nexport interface ComplianceReportEntry {\n /** `aaguid`. */\n aaguid?: string | null;\n /** `authenticator_name`. */\n authenticator_name?: string | null;\n /**\n * `false` only for a genuine policy violation\n * ([`ComplianceStatus::NonCompliant`]) — a credential with no recorded\n * AAGUID ([`ComplianceStatus::Unknown`], D9's pre-X3 case) is always `true`\n * here, never reported as a violation.\n */\n compliant: boolean;\n /** `credential_id`. */\n credential_id: string;\n /**\n * The credential's user-assigned name (`WebauthnCredential::name`), not the\n * owning user's account name.\n */\n name: string;\n /**\n * `None` only when `compliant` and the credential has a recorded AAGUID; set\n * for every non-compliant *and* every \"unknown\" (pre-X3) credential.\n */\n reason?: string | null;\n /** `user_id`. */\n user_id: string;\n}\n\n/** One consent record, as the subject sees it. */\nexport interface ConsentView {\n /** `accepted_at`. */\n accepted_at: string;\n /**\n * What was consented to, e.g. `terms_of_service` or\n * `oidc_scope_release:<client_id>`.\n */\n consent_type: string;\n /** The document version or, for a scope release, the consented scopes. */\n version: string;\n /**\n * Whether this record can be withdrawn here.\n *\n * `false` for `terms_of_service`: withdrawing it is not a consent operation\n * but an erasure, and it has its own endpoint with its own grace period.\n * Reported rather than silently absent so the self-service page can show the\n * record and explain it.\n */\n withdrawable: boolean;\n}\n\n/** `CreateCaCertificateRequest` (generated from openapi.json). */\nexport interface CreateCaCertificateRequest {\n /**\n * Common name for the signing intermediate — `vault_pki` custody only.\n *\n * Under that custodian Vault generates a root and an intermediate beneath\n * it, and this names the second. Defaults to the root's subject with\n * `Intermediate Authority` appended. Ignored by every other custodian, which\n * produces one self-signed CA and has no second certificate to name.\n */\n intermediate_subject?: string | null;\n /** Validity of the signing intermediate, in days. Defaults to the root's. */\n intermediate_validity_days?: number | null;\n /**\n * Issue leaves straight from the generated root instead of creating an\n * intermediate. `vault_pki` custody only, and off by default.\n *\n * The default is the safer one: a root that signs only an intermediate can\n * have that intermediate revoked and replaced without redistributing the\n * trust anchor, and a root that signs leaves cannot.\n */\n issue_from_root?: boolean;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** `subject`. */\n subject: string;\n /** Validity duration in days. */\n validity_days: number;\n}\n\n/** `CreateCertificateRequest` (generated from openapi.json). */\nexport interface CreateCertificateRequest {\n /** `cert_type`. */\n cert_type: CertificateType;\n /** `issuer_ca_id`. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** `metadata`. */\n metadata?: unknown;\n /** `subject`. */\n subject: string;\n /** Validity duration in days. */\n validity_days: number;\n}\n\n/** `CreateFederationConfigRequest` (generated from openapi.json). */\nexport interface CreateFederationConfigRequest {\n /**\n * Whether tenants of this organization may inherit this provider. Only\n * meaningful on a config in the organization-scope tenant.\n */\n allow_tenant_inheritance?: boolean | null;\n /**\n * Accepted JWT signing algorithms (OIDC) or signature algorithms (SAML).\n * Defaults to `[\"RS256\"]` when not provided (CQ-B40/REQ-14 AC-5).\n */\n allowed_algorithms?: string[] | null;\n /**\n * External IdP tenant identifiers accepted when the provider publishes a\n * templated issuer (Entra ID's `{tenantid}`).\n */\n allowed_issuer_tenants?: string[] | null;\n /**\n * Apple Key ID of the `.p8` signing key (10 characters). With both Apple\n * identifiers set, `client_secret` is the `.p8` key itself and AXIAM mints a\n * fresh five-minute client secret per token exchange.\n */\n apple_key_id?: string | null;\n /** Apple Team ID (10 characters). */\n apple_team_id?: string | null;\n /** Maps external IdP attributes to AXIAM user fields. */\n attribute_map?: unknown;\n /** OAuth2-variant authorization endpoint. Required for `OAuth2`. */\n authorization_endpoint?: string | null;\n /**\n * Sign-in-button icon for a **generic** provider, as a base64 raster data\n * URL (`data:image/png;base64,…`), already cropped to\n * `PROVIDER_ICON_SIZE_PX` square by the client.\n *\n * Refused for the branded kinds: Google, Apple and Microsoft all publish\n * sign-in-button rules that require their own mark, so substituting a\n * picture would produce a button that breaks the guidelines it exists to\n * follow.\n */\n button_icon?: string | null;\n /** OAuth2 client ID registered with the external IdP. */\n client_id: string;\n /**\n * OAuth2 client secret registered with the external IdP.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /**\n * PEM-encoded X.509 certificate for verifying SAML assertions or OIDC\n * signatures (CQ-B40/REQ-14 AC-5). Required for SAML configs.\n */\n idp_signing_cert_pem?: string | null;\n /** OIDC discovery URL or SAML metadata URL. */\n metadata_url?: string | null;\n /** Federation protocol: \"OidcConnect\" or \"Saml\". */\n protocol: string;\n /** Display name for the identity provider (e.g., \"Google\", \"Okta\"). */\n provider: string;\n /**\n * Which provider this is: `google`, `github`, `facebook`, `apple`,\n * `microsoft`, `generic_oidc`, `generic_oauth2` or `generic_saml`.\n *\n * Selects the sign-in button's branding, the per-kind defaults, and the key\n * on which a tenant config overrides an inherited organization one. Omitted\n * ⇒ derived from `protocol`, which is what every config written before this\n * field existed means.\n */\n provider_kind?: string | null;\n /**\n * Operator-chosen identifier, **required** for the `generic_*` kinds and\n * refused for the branded ones.\n */\n provider_slug?: string | null;\n /** Send PKCE on the authorization request. Forced on for `OAuth2`. */\n require_pkce?: boolean | null;\n /** Scopes to request. Omitted or empty ⇒ the per-kind default. */\n scopes?: string[] | null;\n /** OAuth2-variant token endpoint. Required for `OAuth2`. */\n token_endpoint?: string | null;\n /** `token_exchange`. */\n token_exchange?: TokenExchangeTrustRequest | null;\n /** OAuth2-variant userinfo endpoint. Required for `OAuth2`. */\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Wire twin of {@link CreateFederationConfigRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateFederationConfigRequestWire {\n allow_tenant_inheritance?: boolean | null;\n allowed_algorithms?: string[] | null;\n allowed_issuer_tenants?: string[] | null;\n apple_key_id?: string | null;\n apple_team_id?: string | null;\n attribute_map?: unknown;\n authorization_endpoint?: string | null;\n button_icon?: string | null;\n client_id: string;\n client_secret: string;\n idp_signing_cert_pem?: string | null;\n metadata_url?: string | null;\n protocol: string;\n provider: string;\n provider_kind?: string | null;\n provider_slug?: string | null;\n require_pkce?: boolean | null;\n scopes?: string[] | null;\n token_endpoint?: string | null;\n token_exchange?: TokenExchangeTrustRequest | null;\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Unwrap a `CreateFederationConfigRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createFederationConfigRequestToWire(v: CreateFederationConfigRequest): CreateFederationConfigRequestWire {\n return {\n ...v,\n client_secret: v.client_secret.expose(),\n };\n}\n\n/** `CreateGroupRequest` (generated from openapi.json). */\nexport interface CreateGroupRequest {\n /** `description`. */\n description: string;\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n}\n\n/** Body of `POST .../tenants/{tenant_id}/signing-cas`. */\nexport interface CreateIntermediateCaRequest {\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** The organization CA that signs it. */\n parent_ca_id: string;\n /** Subject for the signing CA, e.g. `CN=ACME R&D Signing CA`. */\n subject: string;\n /** Validity duration in days, capped to the parent's own expiry. */\n validity_days: number;\n}\n\n/** `CreateNotificationRuleRequest` (generated from openapi.json). */\nexport interface CreateNotificationRuleRequest {\n /** Description of what this rule monitors. */\n description: string;\n /** Event types that trigger this rule. */\n events: NotificationEventType[];\n /** Human-readable name for the rule. */\n name: string;\n /** Email addresses to notify. */\n recipient_emails: string[];\n}\n\n/** `CreateOAuth2ClientRequest` (generated from openapi.json). */\nexport interface CreateOAuth2ClientRequest {\n /**\n * X7.1 — whether this client's authorization requests may carry the OpenID\n * Connect authentication-request parameters (`prompt`, `max_age`,\n * `acr_values`, `claims`, `id_token_hint`, `login_hint`, `display`,\n * `ui_locales`, `claims_locales`).\n *\n * `\"ignore\"` (the default) is what every AXIAM client has always done: they\n * are dropped and reach no decision. `\"honour\"` opts in, and is **refused on\n * a `fapi2` client** at both this gate and the authorization endpoint — the\n * two are different answers to the same question about what a request from\n * this client means.\n */\n authn_request_params?: AuthnRequestParamsMode;\n /**\n * B5 — where OIDC back-channel logout tokens are delivered. Omit for a\n * client that does not participate.\n */\n backchannel_logout_uri?: string | null;\n /**\n * X7.3 — whether an unauthenticated authorization request from this client\n * may be answered with a redirect to the login page rather than the `401`\n * AXIAM answers today.\n *\n * Accepted and stored, but **nothing reads it yet**: the login hop it gates\n * is a later wave. Unlike `authn_request_params` it is permitted on a\n * `fapi2` client, because it relaxes nothing — it decides only how an\n * anonymous browser is answered.\n */\n browser_sso?: boolean;\n /**\n * RFC 9449 §5.2 — issue DPoP-bound (sender-constrained) access tokens to\n * this client. Independent of both the authentication method and\n * `tls_client_certificate_bound_access_tokens`; a client may ask for both\n * constraints, and a token carrying both must satisfy both.\n */\n dpop_bound_access_tokens?: boolean;\n /**\n * RFC 9449 §8 — require this client's DPoP proofs to carry a server-issued\n * nonce.\n *\n * **Not implemented in this build (SEC-097).** `true` is refused with `400`;\n * only `false` (the default) is accepted. Nothing reads the stored value, so\n * accepting `true` would persist and echo back a security switch that does\n * nothing. DPoP proofs are made single-use at the token endpoint by `jti`\n * replay detection instead — see `docs/security-profiles.md`.\n */\n dpop_require_nonce?: boolean;\n /** Grant types this client is authorized to use. */\n grant_types: string[];\n /**\n * RFC 7591 §2 — the client's public key set, inline, for `private_key_jwt`.\n * Exactly one of `jwks` and `jwks_uri` may be set.\n */\n jwks?: string | null;\n /**\n * RFC 7591 §2 — where the client publishes its public key set. Must be an\n * absolute `https` URL, and is fetched through the SSRF-guarded JWKS cache,\n * which refuses private and loopback addresses.\n */\n jwks_uri?: string | null;\n /** Human-readable name for the client. */\n name: string;\n /**\n * B5 — allow-list for RP-initiated logout's `post_logout_redirect_uri`.\n * Separate from `redirect_uris` on purpose: that list receives authorization\n * codes, this one receives a browser after logout.\n */\n post_logout_redirect_uris?: string[];\n /**\n * X5.1 — the security posture this client is registered under.\n *\n * `\"standard\"` (the default) is every AXIAM client that has ever existed.\n * `\"fapi2\"` turns on the whole FAPI 2.0 constraint bundle at once, and the\n * registration is refused unless it also sets `require_par`, a strong\n * `token_endpoint_auth_method` (either mTLS method or `private_key_jwt`),\n * and at least one sender-constraining mechanism\n * (`tls_client_certificate_bound_access_tokens` or\n * `dpop_bound_access_tokens`). See the FAPI operator guide.\n */\n profile?: ClientProfile;\n /**\n * Allowed redirect URIs (must be HTTPS, except localhost for dev). SEC-089:\n * this list doubles as the token-exchange audience allow-list — adding a URI\n * here also authorises it as a token audience for this client, so review\n * additions on exchange-capable clients with that in mind (see\n * `docs/api/token-exchange.md#audience`).\n */\n redirect_uris: string[];\n /**\n * B5 — require this client to push its authorization parameters to\n * `/oauth2/par` (RFC 9126) rather than sending them through the browser.\n */\n require_par?: boolean;\n /** Scopes the client may request. */\n scopes: string[];\n /**\n * Accepted certificate thumbprints for `self_signed_tls_client_auth`, as\n * base64url-unpadded SHA-256 digests of the DER certificate (the same\n * `x5t#S256` encoding as the `cnf` claim). More than one permits an\n * overlapping rotation.\n */\n self_signed_tls_client_auth_thumbprints?: string[];\n /** RFC 8705 §2.1.2 — expected `dNSName` SAN. */\n tls_client_auth_san_dns?: string | null;\n /** RFC 8705 §2.1.2 — expected `uniformResourceIdentifier` SAN. */\n tls_client_auth_san_uri?: string | null;\n /**\n * RFC 8705 §2.1.2 — expected certificate subject DN, RFC 4514 form. Exactly\n * one of the three `tls_client_auth_*` parameters may be set.\n */\n tls_client_auth_subject_dn?: string | null;\n /**\n * RFC 8705 §3.4 — issue certificate-bound (sender-constrained) access tokens\n * to this client. Independent of the authentication method.\n */\n tls_client_certificate_bound_access_tokens?: boolean;\n /**\n * X5.1 — how this client authenticates at the token endpoint (RFC 8705 §2).\n * Defaults to `client_secret_post`.\n */\n token_endpoint_auth_method?: ClientAuthMethod;\n}\n\n/** `CreatePermissionRequest` (generated from openapi.json). */\nexport interface CreatePermissionRequest {\n /** `action`. */\n action: string;\n /** `description`. */\n description: string;\n}\n\n/** `CreatePgpKeyRequest` (generated from openapi.json). */\nexport interface CreatePgpKeyRequest {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** Email for the OpenPGP User ID. */\n email: string;\n /** `name`. */\n name: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n}\n\n/** `CreateReactorRequest` (generated from openapi.json). */\nexport interface CreateReactorRequest {\n /** `description`. */\n description?: string;\n /** `enabled`. */\n enabled?: boolean;\n /** Event names from the registry (`GET /api/v1/reactors/events`). */\n events: string[];\n /** `failure_policy`. */\n failure_policy?: FailurePolicy | null;\n /** `mode`. */\n mode: ReactorMode;\n /** `name`. */\n name: string;\n /** `priority`. */\n priority?: number;\n /** Omit to take the 500 ms default. Capped at 5 000 ms. */\n timeout_ms?: number | null;\n}\n\n/** `CreateResourceRequest` (generated from openapi.json). */\nexport interface CreateResourceRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n /** `parent_id`. */\n parent_id?: string | null;\n /** `resource_type`. */\n resource_type: string;\n}\n\n/** `CreateRoleRequest` (generated from openapi.json). */\nexport interface CreateRoleRequest {\n /** `description`. */\n description: string;\n /** `is_global`. */\n is_global: boolean;\n /** `name`. */\n name: string;\n}\n\n/** `CreateScimTokenRequest` (generated from openapi.json). */\nexport interface CreateScimTokenRequest {\n /**\n * Lifetime in days. Defaults to the deployment maximum, and is refused above\n * it.\n */\n expires_in_days?: number | null;\n /** Operator-facing label, e.g. `\"okta-production\"`. */\n name: string;\n /**\n * The tenant user the token authenticates as. Must already hold\n * `scim:provision` — see [`create`].\n */\n user_id: string;\n}\n\n/**\n * The one-time reveal. Same shape as service-account creation: the secret is\n * returned once and only its hash is kept.\n */\nexport interface CreateScimTokenResponse {\n /** `created_at`. */\n created_at: string;\n /** `created_by`. */\n created_by: string;\n /** `expires_at`. */\n expires_at: string;\n /** `id`. */\n id: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `name`. */\n name: string;\n /**\n * The plaintext handle — shown once, never retrievable again.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n provisioning_token: Sensitive<string>;\n /** `revoked_at`. */\n revoked_at?: string | null;\n /** `status`. */\n status: ScimTokenStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Wire twin of {@link CreateScimTokenResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateScimTokenResponseWire {\n created_at: string;\n created_by: string;\n expires_at: string;\n id: string;\n last_used_at?: string | null;\n name: string;\n provisioning_token: string;\n revoked_at?: string | null;\n status: ScimTokenStatus;\n tenant_id: string;\n user_id: string;\n}\n\n/**\n * Wrap the secret fields a `CreateScimTokenResponse` response carries\n * (§27.5).\n */\nexport function createScimTokenResponseFromWire(w: CreateScimTokenResponseWire): CreateScimTokenResponse {\n return {\n ...w,\n provisioning_token: new Sensitive(w.provisioning_token),\n };\n}\n\n/** `CreateScopeRequest` (generated from openapi.json). */\nexport interface CreateScopeRequest {\n /** `description`. */\n description: string;\n /** `name`. */\n name: string;\n}\n\n/** `CreateServiceAccountRequest` (generated from openapi.json). */\nexport interface CreateServiceAccountRequest {\n /** Optional human-readable description of the account's purpose. */\n description?: string | null;\n /** `name`. */\n name: string;\n}\n\n/**\n * Request body for tenant creation (organization_id comes from the URL\n * path).\n */\nexport interface CreateTenantRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name: string;\n /** `slug`. */\n slug: string;\n}\n\n/** `CreateUserRequest` (generated from openapi.json). */\nexport interface CreateUserRequest {\n /** `email`. */\n email: string;\n /** `metadata`. */\n metadata?: unknown;\n /** `opaque`. */\n opaque?: OpaqueEnrollmentPayload | null;\n /**\n * `password`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n password: Sensitive<string>;\n /** `username`. */\n username: string;\n}\n\n/**\n * Wire twin of {@link CreateUserRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateUserRequestWire {\n email: string;\n metadata?: unknown;\n opaque?: OpaqueEnrollmentPayload | null;\n password: string;\n username: string;\n}\n\n/**\n * Unwrap a `CreateUserRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createUserRequestToWire(v: CreateUserRequest): CreateUserRequestWire {\n return {\n ...v,\n password: v.password.expose(),\n };\n}\n\n/** `CreateWebhookRequest` (generated from openapi.json). */\nexport interface CreateWebhookRequest {\n /** Event types to subscribe to (e.g. `[\"user.created\", \"auth.login\"]`). */\n events: string[];\n /** `retry_policy`. */\n retry_policy?: RetryPolicy | null;\n /**\n * HMAC-SHA256 shared secret for signing payloads.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n secret: Sensitive<string>;\n /** The HTTPS URL to deliver events to. */\n url: string;\n}\n\n/**\n * Wire twin of {@link CreateWebhookRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface CreateWebhookRequestWire {\n events: string[];\n retry_policy?: RetryPolicy | null;\n secret: string;\n url: string;\n}\n\n/**\n * Unwrap a `CreateWebhookRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function createWebhookRequestToWire(v: CreateWebhookRequest): CreateWebhookRequestWire {\n return {\n ...v,\n secret: v.secret.expose(),\n };\n}\n\n/** Fully resolved email configuration (all fields present). */\nexport interface EmailConfig {\n /** `created_at`. */\n created_at: string;\n /** `enabled`. */\n enabled: boolean;\n /** `from_email`. */\n from_email: string;\n /** `from_name`. */\n from_name: string;\n /** `id`. */\n id: string;\n /** `provider`. */\n provider: ProviderConfig;\n /** `reply_to`. */\n reply_to?: string | null;\n /** `scope`. */\n scope: SettingsScope;\n /** The org_id or tenant_id this config belongs to. */\n scope_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Partial tenant overrides for email configuration. `None` = inherit from\n * org baseline.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface EmailConfigOverride {\n /** `enabled`. */\n enabled?: boolean | null;\n /** `from_email`. */\n from_email?: string | null;\n /** `from_name`. */\n from_name?: string | null;\n /** `provider`. */\n provider?: ProviderConfig | null;\n /** `Some(None)` explicitly clears reply-to; `None` inherits. */\n reply_to?: string | null;\n}\n\n/** What a test send did. */\nexport interface EmailTestResult {\n /** The provider's message id, when it returns one. */\n message_id?: string | null;\n /** Which provider the effective configuration resolved to. */\n provider: string;\n /** Where the message went — always the caller's own address. */\n to: string;\n}\n\n/** Email verification requirements. */\nexport interface EmailVerificationPolicy {\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours: number;\n /** `email_verification_required`. */\n email_verification_required: boolean;\n}\n\n/** Request body for encrypting data. */\nexport interface EncryptRequest {\n /** Base64-encoded plaintext to encrypt. */\n data_base64: string;\n}\n\n/** Result of encrypting data with a PGP public key. */\nexport interface EncryptedExport {\n /** ASCII-armored PGP encrypted data. */\n ciphertext_armored: string;\n /** `recipient_key_id`. */\n recipient_key_id: string;\n}\n\n/**\n * What the server does when an interceptor does not produce a usable reply —\n * timeout, transport failure, bad signature, stale nonce, or a patch the\n * allow-list rejects.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type FailurePolicy =\n | \"fail_closed\"\n | \"fail_open\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Federation config response -- omits client_secret. */\nexport interface FederationConfigResponse {\n /** Whether tenants of this organization may inherit this provider. */\n allow_tenant_inheritance: boolean;\n /**\n * Accepted signing algorithms. Returned for OIDC and SAML; meaningless, and\n * therefore empty, for the OAuth2 variant.\n */\n allowed_algorithms: string[];\n /** Accepted external IdP tenants for a templated issuer. */\n allowed_issuer_tenants: string[];\n /** Apple Key ID. */\n apple_key_id?: string | null;\n /** Apple Team ID. Not secret — the `.p8` key is, and it is never returned. */\n apple_team_id?: string | null;\n /** `attribute_map`. */\n attribute_map: unknown;\n /** OAuth2-variant authorization endpoint. */\n authorization_endpoint?: string | null;\n /** Custom sign-in-button icon, when one is set. */\n button_icon?: string | null;\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /**\n * The per-kind default that an empty `scopes` resolves to. Returned so the\n * admin UI can show what will actually be requested without duplicating the\n * table.\n */\n effective_scopes: string[];\n /** `enabled`. */\n enabled: boolean;\n /**\n * Whether AXIAM ships this provider's own mark. When true the button uses it\n * and `button_icon` is refused; when false the button reads \"Sign in with\n * <provider>\" and may carry a custom icon.\n */\n has_bundled_mark: boolean;\n /** `id`. */\n id: string;\n /** `metadata_url`. */\n metadata_url?: string | null;\n /**\n * Whether AXIAM mints this provider's client secret itself, per exchange,\n * rather than sending a stored one. True only for an Apple config with both\n * identifiers set.\n */\n mints_client_secret: boolean;\n /**\n * Whether PKCE is sent on the authorization request. Always true for the\n * OAuth2 variant regardless of the stored flag.\n */\n pkce_required: boolean;\n /** `protocol`. */\n protocol: string;\n /** `provider`. */\n provider: string;\n /**\n * Which provider this is. Derived from `protocol` for a config written\n * before the field existed.\n */\n provider_kind: string;\n /** Operator-chosen identifier for a `generic_*` kind. */\n provider_slug?: string | null;\n /**\n * Scopes as stored. Empty means \"use the per-kind default\"; see\n * `effective_scopes`.\n */\n scopes: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** OAuth2-variant token endpoint. */\n token_endpoint?: string | null;\n /** X4 external token-exchange trust. */\n token_exchange: TokenExchangeTrustResponse;\n /** `updated_at`. */\n updated_at: string;\n /** OAuth2-variant userinfo endpoint. */\n userinfo_endpoint?: string | null;\n}\n\n/** `FederationLinkResponse` (generated from openapi.json). */\nexport interface FederationLinkResponse {\n /** `created_at`. */\n created_at: string;\n /** `external_email`. */\n external_email?: string | null;\n /** `external_subject`. */\n external_subject: string;\n /** `federation_config_id`. */\n federation_config_id: string;\n /** `id`. */\n id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Response returned when a CA certificate is generated.\n *\n * Includes the private key PEM, which is returned **once** and never stored\n * or retrievable again — when the custodian produced one at all. Under\n * `vault_pki` custody the key was born inside Vault and there is nothing to\n * return, which is the point of that custodian rather than a shortcoming of\n * this response.\n */\nexport interface GeneratedCaCertificate {\n /**\n * The issuers above [`Self::public_cert_pem`], concatenated PEM, nearest\n * issuer first and the root last.\n *\n * `None` for a CA that is its own root, which is every CA AXIAM generated\n * before Vault's PKI engine was an option. Present for a `vault_pki` CA,\n * where it is the only copy of the root certificate anything outside Vault\n * will ever see — a relying party cannot validate an AXIAM-issued leaf\n * without it, and `root/generate/internal` returns it exactly once.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /**\n * Which custodian holds this CA's signing key.\n *\n * Recorded per CA rather than read from configuration, so adopting a new\n * custodian does not strand the CAs that already exist. Not secret — an\n * operator needs to see it, and it discloses only where a key is kept.\n */\n key_custody?: string;\n /**\n * Where the custodian put the key. A Vault path under its mount; `None` for\n * database custody, whose locator is the row itself.\n */\n key_locator?: string | null;\n /**\n * Whether this CA is offered as a trust anchor for mutual TLS.\n *\n * When set, the server exports this CA's **public** certificate to the\n * bundle named by `AXIAM__SERVER__TLS__CLIENT_CA_BUNDLE_PATH` at startup and\n * turns client-certificate authentication on (`optional`) if the operator\n * has not configured it explicitly. A client presenting a certificate that\n * chains to this CA is then verified by the TLS layer itself, which is what\n * `axiam_pki::mtls` needs to authenticate an IoT device or a service account\n * by certificate rather than by secret.\n *\n * # What is and is not copied\n *\n * Only `public_cert_pem` — the certificate. The **private key stays where\n * its custodian put it** (Vault, or sealed into the row) and is never\n * written to the server volume. A trust anchor is public by construction: it\n * is what the server hands every client during the TLS handshake, and every\n * device that has to validate the chain already holds a copy.\n *\n * # Why a restart\n *\n * rustls builds its `RootCertStore` once, when the listener is constructed,\n * and actix-web binds that config for the process's life. Toggling this\n * changes what the *next* boot trusts, and the API says so in its response\n * rather than pretending the change took effect.\n *\n * Defaults to `false`, so a deployment that never touches this keeps exactly\n * the TLS posture it has today.\n */\n mtls_trust_anchor?: boolean;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /** The organization this CA belongs to. */\n organization_id: string;\n /**\n * The CA in this organization that signed this one.\n *\n * `None` for an organization-level CA, which is either self-signed or\n * imported and has no parent inside AXIAM.\n */\n parent_ca_id?: string | null;\n /**\n * PEM-encoded private key — returned only on generation, and only when there\n * is one to return.\n *\n * Absent under `vault_pki` custody, where the key was generated inside Vault\n * and no API exports it. The field is omitted rather than sent as `null` so\n * a client that has always read it keeps working unchanged for every\n * custodian that does produce a key.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem?: Sensitive<string>;\n /**\n * PEM-encoded public certificate.\n *\n * The certificate that *signs*, which under `vault_pki` custody is the\n * intermediate rather than the root beneath which it was created.\n */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=ACME Corp Root CA`). */\n subject: string;\n /**\n * The tenant this CA signs for, when it is a tenant signing CA.\n *\n * `None` for an organization-level CA — the trust anchor, and the only kind\n * that existed before tenant signing CAs. `Some` for an intermediate created\n * under one, which exists so a tenant's user, service and device\n * certificates chain through a CA that can be revoked and replaced without\n * touching the anchor the rest of the estate trusts.\n */\n tenant_id?: string | null;\n}\n\n/**\n * Wire twin of {@link GeneratedCaCertificate} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedCaCertificateWire {\n chain_pem?: string | null;\n created_at: string;\n fingerprint: string;\n id: string;\n key_algorithm: KeyAlgorithm;\n key_custody?: string;\n key_locator?: string | null;\n mtls_trust_anchor?: boolean;\n not_after: string;\n not_before: string;\n organization_id: string;\n parent_ca_id?: string | null;\n private_key_pem?: string;\n public_cert_pem: string;\n status: CertificateStatus;\n subject: string;\n tenant_id?: string | null;\n}\n\n/**\n * Wrap the secret fields a `GeneratedCaCertificate` response carries\n * (§27.5).\n */\nexport function generatedCaCertificateFromWire(w: GeneratedCaCertificateWire): GeneratedCaCertificate {\n return {\n ...w,\n private_key_pem: w.private_key_pem === undefined ? undefined : new Sensitive(w.private_key_pem),\n };\n}\n\n/**\n * Response returned when a tenant certificate is generated.\n *\n * Includes the private key PEM, returned **once** and never stored.\n */\nexport interface GeneratedCertificate {\n /** `cert_type`. */\n cert_type: CertificateType;\n /**\n * The issuing chain, concatenated PEM, nearest issuer first.\n *\n * Present only when the signer returned one — which is the `vault_pki` case,\n * where the root's certificate exists nowhere a client could fetch it from.\n * For a CA AXIAM signed with itself the chain is the CA certificate, which\n * `GET .../ca-certificates/{id}` already serves, so the field is omitted\n * rather than restating it.\n */\n chain_pem?: string | null;\n /** `created_at`. */\n created_at: string;\n /** SHA-256 fingerprint of the certificate. */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** The CA certificate that signed this certificate. */\n issuer_ca_id: string;\n /** `key_algorithm`. */\n key_algorithm: KeyAlgorithm;\n /** Arbitrary key-value metadata (e.g., device serial, user ID binding). */\n metadata: unknown;\n /** Validity end. */\n not_after: string;\n /** Validity start. */\n not_before: string;\n /**\n * PEM-encoded private key — returned only on generation.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem: Sensitive<string>;\n /** PEM-encoded public certificate. */\n public_cert_pem: string;\n /** `status`. */\n status: CertificateStatus;\n /** The certificate subject (e.g., `CN=device-001`). */\n subject: string;\n /** The tenant this certificate belongs to. */\n tenant_id: string;\n}\n\n/**\n * Wire twin of {@link GeneratedCertificate} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedCertificateWire {\n cert_type: CertificateType;\n chain_pem?: string | null;\n created_at: string;\n fingerprint: string;\n id: string;\n issuer_ca_id: string;\n key_algorithm: KeyAlgorithm;\n metadata: unknown;\n not_after: string;\n not_before: string;\n private_key_pem: string;\n public_cert_pem: string;\n status: CertificateStatus;\n subject: string;\n tenant_id: string;\n}\n\n/** Wrap the secret fields a `GeneratedCertificate` response carries (§27.5). */\nexport function generatedCertificateFromWire(w: GeneratedCertificateWire): GeneratedCertificate {\n return {\n ...w,\n private_key_pem: new Sensitive(w.private_key_pem),\n };\n}\n\n/** Response returned when a PGP key is generated. */\nexport interface GeneratedPgpKey {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** `created_at`. */\n created_at: string;\n /** OpenPGP key fingerprint (hex). */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /**\n * ASCII-armored private key — returned only on generation for `Export` keys.\n * For `AuditSigning` keys this is `None` (private key is server-side only).\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_armored?: Sensitive<string>;\n /** `public_key_armored`. */\n public_key_armored: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n /** `status`. */\n status: PgpKeyStatus;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * Wire twin of {@link GeneratedPgpKey} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface GeneratedPgpKeyWire {\n algorithm: PgpKeyAlgorithm;\n created_at: string;\n fingerprint: string;\n id: string;\n name: string;\n private_key_armored?: string;\n public_key_armored: string;\n purpose: PgpKeyPurpose;\n status: PgpKeyStatus;\n tenant_id: string;\n}\n\n/** Wrap the secret fields a `GeneratedPgpKey` response carries (§27.5). */\nexport function generatedPgpKeyFromWire(w: GeneratedPgpKeyWire): GeneratedPgpKey {\n return {\n ...w,\n private_key_armored: w.private_key_armored === undefined ? undefined : new Sensitive(w.private_key_armored),\n };\n}\n\n/** `GrantPermissionRequest` (generated from openapi.json). */\nexport interface GrantPermissionRequest {\n /**\n * B1: `\"allow\"` (the default) or `\"deny\"`.\n *\n * A deny grant **overrides every allow**, at any depth of the resource\n * hierarchy and at equal specificity — it is not most-specific-wins. See\n * `claude_dev/deny-override-design.md` for the precedence table and for why\n * that trade was made.\n *\n * Omitting the field means `\"allow\"`, so every existing client keeps working\n * unchanged and no migration is required.\n */\n effect?: PermissionEffect;\n /** `permission_id`. */\n permission_id: string;\n /** `scope_ids`. */\n scope_ids?: string[];\n}\n\n/** Body for recording an OIDC scope-release consent. */\nexport interface GrantScopeConsent {\n /** The relying party the claims would be released to. */\n client_id: string;\n /**\n * The sensitive scopes being consented to. Order does not matter; the record\n * is written in the canonical order so that the same consent has one name.\n */\n scopes: string[];\n}\n\n/** A scope named by a grant, resolved to something a human can read. */\nexport interface GrantedScope {\n /** The scope's id, as it appears in the grant's `scope_ids`. */\n id: string;\n /** The scope's name, e.g. `invoices`. */\n name: string;\n /** The resource the scope belongs to. */\n resource_id: string;\n}\n\n/**\n * A group of users that can access resources based on their roles and\n * permissions. Groups simplify role management by allowing roles to be\n * assigned to a group rather than individual users.\n */\nexport interface Group {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `metadata`. */\n metadata: unknown;\n /** `name`. */\n name: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `HealthResponse` (generated from openapi.json). */\nexport interface HealthResponse {\n /** `status`. */\n status: string;\n}\n\n/**\n * Body of `POST /api/v1/organizations/{org_id}/ca-certificates/import`.\n *\n * Deliberately carries no subject, validity window or key algorithm: all\n * three are read out of the certificate itself. A caller that could name\n * them separately could name a subject the certificate does not have, and\n * AXIAM would enforce the claim while every relying party read the\n * certificate.\n */\nexport interface ImportCaCertificateRequest {\n /**\n * PEM-encoded private key, if AXIAM is to take custody of it.\n *\n * Omit it to register the certificate as a trust anchor only. Write-only: it\n * goes to the configured custodian on the way in and no endpoint returns it.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n private_key_pem?: Sensitive<string>;\n /** PEM-encoded CA certificate. */\n public_cert_pem: string;\n}\n\n/**\n * Wire twin of {@link ImportCaCertificateRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface ImportCaCertificateRequestWire {\n private_key_pem?: string;\n public_cert_pem: string;\n}\n\n/**\n * Unwrap a `ImportCaCertificateRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function importCaCertificateRequestToWire(v: ImportCaCertificateRequest): ImportCaCertificateRequestWire {\n return {\n ...v,\n private_key_pem: v.private_key_pem === undefined ? undefined : v.private_key_pem.expose(),\n };\n}\n\n/**\n * The type of key algorithm used for a certificate.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type KeyAlgorithm =\n | \"Rsa4096\"\n | \"Ed25519\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Account lockout rules. */\nexport interface LockoutPolicy {\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier: number;\n /** `lockout_duration_secs`. */\n lockout_duration_secs: number;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts: number;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs: number;\n}\n\n/**\n * `POST /api/v1/mds/refresh` response — the outcome of one ingestion attempt\n * (mirrors `axiam_db::mds_ingest::MdsIngestOutcome`).\n */\nexport type MdsRefreshOutcome =\n | {\n /** Discriminator: always `initial`. */\n outcome: \"initial\";\n /** `entry_count`. */\n entry_count: number;\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `replaced`. */\n outcome: \"replaced\";\n /** `entry_count`. */\n entry_count: number;\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `no_op_refresh`. */\n outcome: \"no_op_refresh\";\n /** `no`. */\n no: number;\n }\n | {\n /** Discriminator: always `rollback_rejected`. */\n outcome: \"rollback_rejected\";\n /** `attempted_no`. */\n attempted_no: number;\n /** `stored_no`. */\n stored_no: number;\n };\n\n/**\n * `GET /api/v1/mds/status` response. `no`/`next_update`/`last_refreshed_at`\n * are `None` and `stale` is `false` when MDS has never been ingested — a\n * meaningful, valid answer (\"nothing ingested yet\"), not an error.\n */\nexport interface MdsStatusResponse {\n /** `entry_count`. */\n entry_count: number;\n /** `last_refreshed_at`. */\n last_refreshed_at?: string | null;\n /** `next_update`. */\n next_update?: string | null;\n /** `no`. */\n no?: number | null;\n /** `stale`. */\n stale: boolean;\n}\n\n/** `MfaMethodResponse` (generated from openapi.json). */\nexport interface MfaMethodResponse {\n /** `created_at`. */\n created_at: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `method_id`. */\n method_id: string;\n /** `method_type`. */\n method_type: MfaMethodType;\n /** `name`. */\n name: string;\n}\n\n/**\n * Type of MFA method.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type MfaMethodType =\n | \"Totp\"\n | \"Passkey\"\n | \"SecurityKey\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Multi-factor authentication policy. */\nexport interface MfaPolicy {\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs: number;\n /** `mfa_enforced`. */\n mfa_enforced: boolean;\n}\n\n/** What a custody migration did. */\nexport interface MigrateCustodyResponse {\n /** The CA whose key moved. */\n ca_certificate_id: string;\n /** Where it is now. */\n key_custody: string;\n /** Where the new custodian filed it, when the custodian has a path. */\n key_locator?: string | null;\n /** Where the key was. */\n previous_custody: string;\n}\n\n/** The acknowledgement, which is mostly about the restart. */\nexport interface MtlsTrustAnchorResponse {\n /** The CA this is about. */\n ca_certificate_id: string;\n /** A sentence an operator can act on, rather than a bare boolean. */\n message: string;\n /** The flag as now stored. */\n mtls_trust_anchor: boolean;\n /**\n * Whether the change still needs a restart to take effect.\n *\n * `false` when the live listener accepted the new anchor set — the ordinary\n * case on a TLS deployment. `true` only when there was no listener to reload\n * into (plaintext, or `client_auth = off`), where the flag is stored and\n * applies at the next start.\n */\n restart_required: boolean;\n /**\n * How many CAs the listener now trusts for client authentication, when it\n * was reloaded. `None` when nothing was reloaded.\n */\n trusted_anchors?: number | null;\n}\n\n/**\n * Events that can trigger an admin notification.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type NotificationEventType =\n | \"login_failure\"\n | \"account_locked\"\n | \"mfa_enrollment_changed\"\n | \"password_changed\"\n | \"password_reset_requested\"\n | \"role_assigned\"\n | \"role_unassigned\"\n | \"permission_granted\"\n | \"permission_revoked\"\n | \"certificate_issued\"\n | \"certificate_revoked\"\n | \"ca_certificate_revoked\"\n | \"user_created\"\n | \"user_deleted\"\n | \"user_updated\"\n | \"service_account_created\"\n | \"service_account_deleted\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Admin notification preferences. */\nexport interface NotificationPolicy {\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled: boolean;\n}\n\n/** Notification rule response. */\nexport interface NotificationRuleResponse {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: NotificationEventType[];\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `recipient_emails`. */\n recipient_emails: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Response for client creation -- includes the one-time plaintext secret. */\nexport interface OAuth2ClientCreatedResponse {\n /** `client_id`. */\n client_id: string;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /** `created_at`. */\n created_at: string;\n /** `grant_types`. */\n grant_types: string[];\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `redirect_uris`. */\n redirect_uris: string[];\n /** `scopes`. */\n scopes: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Wire twin of {@link OAuth2ClientCreatedResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface OAuth2ClientCreatedResponseWire {\n client_id: string;\n client_secret: string;\n created_at: string;\n grant_types: string[];\n id: string;\n name: string;\n redirect_uris: string[];\n scopes: string[];\n tenant_id: string;\n updated_at: string;\n}\n\n/**\n * Wrap the secret fields a `OAuth2ClientCreatedResponse` response carries\n * (§27.5).\n */\nexport function oAuth2ClientCreatedResponseFromWire(w: OAuth2ClientCreatedResponseWire): OAuth2ClientCreatedResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/** OAuth2 client response -- omits client_secret_hash. */\nexport interface OAuth2ClientResponse {\n /**\n * X7.1 — echoed so an operator can audit which clients act on the OIDC\n * authentication-request parameters, from this endpoint rather than from the\n * database.\n */\n authn_request_params: AuthnRequestParamsMode;\n /** X7.3 — echoed for the same reason. */\n browser_sso: boolean;\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /** `dpop_bound_access_tokens`. */\n dpop_bound_access_tokens: boolean;\n /** `dpop_require_nonce`. */\n dpop_require_nonce: boolean;\n /** `grant_types`. */\n grant_types: string[];\n /** `id`. */\n id: string;\n /**\n * X5.1 — echoed so an operator can confirm which key source is registered.\n * The document itself is public key material, so returning it leaks nothing;\n * a `jwks_uri` is likewise public by construction.\n */\n jwks?: string | null;\n /** `jwks_uri`. */\n jwks_uri?: string | null;\n /** `name`. */\n name: string;\n /**\n * X5.1 — the registered posture and mTLS credentials. Read-back matters: an\n * operator auditing which clients are financial-grade should be able to\n * answer it from this endpoint rather than from the database.\n */\n profile: ClientProfile;\n /** `redirect_uris`. */\n redirect_uris: string[];\n /** `require_par`. */\n require_par: boolean;\n /** `scopes`. */\n scopes: string[];\n /** `self_signed_tls_client_auth_thumbprints`. */\n self_signed_tls_client_auth_thumbprints: string[];\n /** `tenant_id`. */\n tenant_id: string;\n /** `tls_client_auth_san_dns`. */\n tls_client_auth_san_dns?: string | null;\n /** `tls_client_auth_san_uri`. */\n tls_client_auth_san_uri?: string | null;\n /** `tls_client_auth_subject_dn`. */\n tls_client_auth_subject_dn?: string | null;\n /** `tls_client_certificate_bound_access_tokens`. */\n tls_client_certificate_bound_access_tokens: boolean;\n /** `token_endpoint_auth_method`. */\n token_endpoint_auth_method: ClientAuthMethod;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `OidcAuthorizeRequest` (generated from openapi.json). */\nexport interface OidcAuthorizeRequest {\n /** ID of the federation config to use. */\n config_id: string;\n /** Nonce for replay protection (generated by the caller). */\n nonce: string;\n /** Redirect URI the external IdP should return the user to. */\n redirect_uri: string;\n /** CSRF state value (generated by the caller). */\n state: string;\n}\n\n/** `OidcAuthorizeResponse` (generated from openapi.json). */\nexport interface OidcAuthorizeResponse {\n /** The full authorization URL to redirect the user to. */\n url: string;\n}\n\n/** `OidcCallbackRequest` (generated from openapi.json). */\nexport interface OidcCallbackRequest {\n /** Authorization code returned by the external IdP. */\n code: string;\n /** ID of the federation config used in the authorization request. */\n config_id: string;\n /**\n * Client-supplied nonce (SECHRD-07/D-04: retained for backward compatibility\n * with older callers, but IGNORED for verification — `expected_nonce` always\n * comes from the server-side `FederationLoginState` row looked up via\n * `state`, never from this field).\n */\n nonce: string;\n /** Redirect URI that was used in the authorization request. */\n redirect_uri: string;\n /**\n * CSRF state value from the authorization request. Used to look up the\n * server-side `FederationLoginState` row that holds the real nonce\n * (SECHRD-07/D-04) — required so the callback can find its login state.\n */\n state: string;\n}\n\n/** `OidcCallbackResponse` (generated from openapi.json). */\nexport interface OidcCallbackResponse {\n /** `federation_link_id`. */\n federation_link_id: string;\n /** `newly_provisioned`. */\n newly_provisioned: boolean;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * OpenID Connect surface controls (X7 G8, plan §4.6/§4.8).\n *\n * Two settings that are not password rules, and are here because this is the\n * org-baseline-plus-tenant-override surface every other per-tenant control\n * lives on. They are also the two settings in this model that are *not* of\n * the same kind as each other, so it is worth saying which is which:\n *\n * * [`Self::sensitive_scopes_enabled`] **is** ordered. Releasing personal\n * data is the less-restrictive direction, so it is validated disable-only —\n * the mirror image of `mfa_enforced` — and a tenant can turn its\n * organization's decision off but never on. * [`Self::default_locale`] is\n * **not** ordered, and no ordering is invented for it. A language is a\n * presentation preference; there is no sense in which Italian is stricter\n * than French. [`validate_tenant_override`] therefore does not check it and\n * [`clamp_overrides_to_org`] never clears it. The model's rule is \"a tenant\n * may only be more restrictive\", which binds every field that *has* a\n * restrictiveness; a field that has none cannot violate it.\n */\nexport interface OidcPolicy {\n /**\n * The BCP 47 tag the sign-in page falls back to when the relying party's\n * `ui_locales` selects nothing (W5's chain, plan §4.6).\n *\n * `None` means \"no tenant preference\", which lands on the deployment default\n * (`en`) — the behaviour every deployment had before this field existed. A\n * tag this build does not ship also lands there: the parse is exact rather\n * than a language lookup, so a stored `fr-CA` reads as \"somebody wrote\n * something this binary does not ship\" rather than as a guess at French.\n *\n * Stored as a string rather than as the `Locale` enum because that enum\n * lives in `axiam-oauth2`, four layers above this crate, and the crate\n * layering points inward.\n */\n default_locale?: string | null;\n /**\n * Whether `address` and `phone` may be registered on a client, requested at\n * the authorization endpoint, and released at UserInfo (X7 G8).\n *\n * **Off unless an organization turns it on.** The two scopes release a\n * postal address and a telephone number — categories of personal data AXIAM\n * has no other use for — so the deployment that has never thought about them\n * releases nothing, and the operator who has thought about them says so\n * once, at the organization level, where the lawful basis for holding the\n * data was decided.\n *\n * The switch is a *capability*, not a grant: with it on, a client still has\n * to register the scope, the request still has to ask for it, and the user\n * still has to have consented. It is the first of four gates, and it is the\n * only one an operator can close for everybody at once.\n */\n sensitive_scopes_enabled: boolean;\n}\n\n/**\n * The client-supplied half of an OPAQUE enrolment, as it appears inside\n * registration / change-password / reset-completion / bootstrap request\n * bodies.\n *\n * There is no standalone `register/finish` endpoint, deliberately. A record\n * can only be created at a moment when the plaintext password legitimately\n * exists on the client, and every one of those moments is already an\n * endpoint that takes a password. A free-standing finish would be an\n * endpoint whose only job is to attach a credential to an account, which is\n * a thing worth not having.\n *\n * Kept separate from [`CreateOpaqueCredential`] because the tenant, the user\n * and the credential identifier are all decided by the server — a client\n * that could name them could enrol a record against somebody else's account.\n */\nexport interface OpaqueEnrollmentPayload {\n /** The `opaque_session` from the register/start response, echoed verbatim. */\n opaque_session: string;\n /** Lowercase-hex serialized RFC 9807 `RegistrationRecord`. */\n registration_record: string;\n}\n\n/**\n * Secure Remote Password policy.\n *\n * `suite` and `ksf` are the parameters a *new* registration record is\n * enrolled with. They deliberately do not apply retroactively: an existing\n * record is only valid under the suite and KSF it was created with, so\n * tightening these takes effect as users next set a password rather than\n * invalidating everybody at once.\n */\nexport interface OpaquePolicy {\n /**\n * Key-stretching function new records are enrolled under. Both variants are\n * memory-hard; see [`opaque_ksf_is_at_least`] for the tighten-only ordering.\n */\n opaque_ksf: string;\n /** Whether OPAQUE is offered, and whether password login is still accepted. */\n opaque_mode: string;\n /** RFC 9807 ciphersuite new records are enrolled under. */\n opaque_suite: string;\n}\n\n/**\n * An organization groups multiple tenants under a single administrative\n * entity.\n *\n * Organizations represent companies, departments, or business units. CA\n * certificates are registered at the organization level, enabling a\n * hierarchical trust model across all tenants.\n */\nexport interface Organization {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /** Arbitrary key-value metadata. */\n metadata: unknown;\n /** Human-readable name. */\n name: string;\n /** URL-safe unique identifier (e.g., `acme-corp`). */\n slug: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Password complexity and history requirements. */\nexport interface PasswordPolicy {\n /** `hibp_check_enabled`. */\n hibp_check_enabled: boolean;\n /** `min_length`. */\n min_length: number;\n /** `password_history_count`. */\n password_history_count: number;\n /** `require_digits`. */\n require_digits: boolean;\n /** `require_lowercase`. */\n require_lowercase: boolean;\n /** `require_symbols`. */\n require_symbols: boolean;\n /** `require_uppercase`. */\n require_uppercase: boolean;\n}\n\n/** `Permission` (generated from openapi.json). */\nexport interface Permission {\n /** The action this permission represents (e.g., `read`, `write`, `delete`). */\n action: string;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Whether a grant permits an action or refuses it (B1, deny-override).\n *\n * # Precedence\n *\n * Default deny -> an [`PermissionEffect::Allow`] grant permits -> a\n * [`PermissionEffect::Deny`] grant refuses, **and beats every allow**,\n * wherever either sits in the resource hierarchy. Deny wins; there is no\n * most-specific-wins tie-break.\n *\n * That choice is deliberate and is argued in full in\n * `claude_dev/deny-override-design.md` §2.1. The short version:\n * deny-override buys one checkable property — **adding a deny rule can never\n * widen access, and can never be undone by adding allows** — and\n * most-specific-wins buys expressiveness at the cost of making \"is X\n * denied?\" unanswerable without enumerating every other rule that might\n * out-specify it.\n *\n * [`PermissionEffect::Allow`] is the default, so data written before this\n * existed, and clients that send no `effect`, both mean \"allow\". No\n * migration.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PermissionEffect =\n | \"allow\"\n | \"deny\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** An OpenPGP key stored by AXIAM. */\nexport interface PgpKey {\n /** `algorithm`. */\n algorithm: PgpKeyAlgorithm;\n /** `created_at`. */\n created_at: string;\n /** OpenPGP key fingerprint (hex). */\n fingerprint: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `public_key_armored`. */\n public_key_armored: string;\n /** `purpose`. */\n purpose: PgpKeyPurpose;\n /** `status`. */\n status: PgpKeyStatus;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * Key algorithm for OpenPGP keys.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyAlgorithm =\n | \"Rsa4096\"\n | \"Ed25519\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * The purpose of an OpenPGP key.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyPurpose =\n | \"AuditSigning\"\n | \"Export\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Status of an OpenPGP key.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type PgpKeyStatus =\n | \"Active\"\n | \"Revoked\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * `GET` response: the stored policy plus the unknown-AAGUID action it\n * currently *resolves to*.\n *\n * `unknown_aaguid` is nullable, where `null` means \"use this mode's default\"\n * (deny under `direct_required`, allow otherwise). A client that only saw\n * the stored `null` would have to re-derive that rule itself to display what\n * the policy actually does — and a security rule implemented twice is a\n * security rule that will eventually disagree with itself. So the server\n * resolves it once, here, and reports both: the admin's stored intent and\n * its effect.\n */\nexport interface PolicyResponse {\n /**\n * `None` = every AAGUID is allowed except `blocked_aaguids`.\n *\n * `Some(vec![])` is a deliberate \"nothing may register\" policy and is\n * accepted as such: `evaluate` denies every AAGUID against an empty\n * allow-list. Nothing rejects it, precisely because the failure direction is\n * safe — a client that sends `[]` when it meant `null` gets a locked-down\n * tenant, which is visible immediately, rather than an open one, which is\n * not.\n */\n allowed_aaguids?: string[] | null;\n /**\n * Deny registration if the MDS entry has ever reported `REVOKED` or any\n * `*_COMPROMISE` status (sticky — D8 step 7).\n */\n block_revoked_status: boolean;\n /** `blocked_aaguids`. */\n blocked_aaguids?: string[];\n /**\n * The action actually applied to an AAGUID with no MDS metadata, with\n * `unknown_aaguid: null` resolved against `mode`. Read-only — `PUT` ignores\n * it.\n */\n effective_unknown_aaguid: UnknownAaguidAction;\n /** `min_certification`. */\n min_certification?: CertificationLevel | null;\n /** `mode`. */\n mode: AttestationMode;\n /**\n * Require *some* `FIDO_CERTIFIED*` status, any level. Independent of (and\n * checked before) `min_certification`.\n */\n require_fido_certified: boolean;\n /** `unknown_aaguid`. */\n unknown_aaguid?: UnknownAaguidAction | null;\n}\n\n/** Data-retention rules that apply after a subject asks to be erased. */\nexport interface PrivacyPolicy {\n /**\n * How long a requested account erasure stays cancellable before the purge\n * runs, in days.\n *\n * The window exists so an erasure triggered by mistake, or under coercion,\n * can be undone — `POST /api/v1/auth/account/delete/cancel` works for\n * exactly this long. It was fixed at 30 days in the handler, which meant the\n * \"cancel a pending deletion\" control in the admin UI referred to a duration\n * no operator could see or change.\n *\n * Shorter is the more restrictive direction, so a tenant may lower it and\n * not raise it: it is time spent holding data the subject has already asked\n * to have erased, and GDPR Art. 17(1) asks for that to be \"without undue\n * delay\". The upper bound of 90 days is where Art. 12(3)'s one-month\n * response deadline plus its two-month extension for complex cases runs out;\n * anything past 30 wants a reason recorded.\n */\n deletion_grace_period_days: number;\n}\n\n/** Provider-specific connection details. */\nexport type ProviderConfig =\n | ({\n /** Discriminator: always `smtp`. */\n kind: \"smtp\";\n } & SmtpConfig)\n | ({\n /** Discriminator: always `send_grid`. */\n kind: \"send_grid\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `postmark`. */\n kind: \"postmark\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `resend`. */\n kind: \"resend\";\n } & ApiProviderConfig)\n | ({\n /** Discriminator: always `brevo`. */\n kind: \"brevo\";\n } & ApiProviderConfig);\n\n/** One hookable event, as the registry describes it. */\nexport interface ReactorEventDescriptor {\n /** `default_failure_policy`. */\n default_failure_policy: FailurePolicy;\n /** `description`. */\n description: string;\n /** `interceptable`. */\n interceptable: boolean;\n /** `mutable`. */\n mutable: boolean;\n /**\n * Exact field names, or a namespace prefix ending in `.` — `ext.` admits\n * `ext.department` and nothing outside the namespace.\n */\n mutable_fields: string[];\n /** `name`. */\n name: string;\n}\n\n/**\n * How a reactor participates in an event.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ReactorMode =\n | \"intercept\"\n | \"listen\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `ReactorResponse` (generated from openapi.json). */\nexport interface ReactorResponse {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: string[];\n /** `failure_policy`. */\n failure_policy: FailurePolicy;\n /** `id`. */\n id: string;\n /**\n * When this reactor last consumed from its queue. `null` means it has never\n * connected — which the admin UI shows differently from \"connected once,\n * silent since\".\n */\n last_seen_at?: string | null;\n /** `mode`. */\n mode: ReactorMode;\n /** `name`. */\n name: string;\n /** `priority`. */\n priority: number;\n /**\n * R2.3: dispatch failures against this registration in the last 24h whose\n * cause was a timeout (as opposed to a rejected reply, a transport failure,\n * or overload), capped at 100 — a health signal read from the audit trail\n * R2.2 started writing, not a replacement for the audit log itself (`GET\n * /api/v1/audit-log` is that).\n */\n recent_timeout_count: number;\n /**\n * R2.3: operations this reactor's own reply *denied* in the last 24h, capped\n * at 100. Distinct from `recent_timeout_count`: a veto is the reactor\n * working as designed; a timeout is the reactor not answering.\n */\n recent_veto_count: number;\n /** `tenant_id`. */\n tenant_id: string;\n /** `timeout_ms`. */\n timeout_ms: number;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** `ReadyResponse` (generated from openapi.json). */\nexport interface ReadyResponse {\n /** `database`. */\n database: string;\n /** `status`. */\n status: string;\n}\n\n/**\n * A permission grant with its scopes resolved.\n *\n * A superset of [`PermissionGrant`]: `scope_ids` is still present and still\n * authoritative, so a client written before `scopes` existed is unaffected.\n */\nexport interface ResolvedPermissionGrant {\n /** Whether the grant permits or refuses. */\n effect: PermissionEffect;\n /** The permission this grant is about. */\n permission: Permission;\n /** The scope ids the grant is constrained to. Empty is the wildcard. */\n scope_ids: string[];\n /**\n * The scopes `scope_ids` names, in the same order where resolvable.\n *\n * A scope that cannot be resolved is **omitted** rather than represented by\n * a placeholder, so this can be shorter than `scope_ids`. That happens when\n * a scope was deleted while a grant still referenced it, and showing a name\n * for something that no longer exists would be worse than showing one fewer\n * chip beside a count that still says how many ids the grant carries.\n */\n scopes: GrantedScope[];\n}\n\n/** `Resource` (generated from openapi.json). */\nexport interface Resource {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /** `metadata`. */\n metadata: unknown;\n /** `name`. */\n name: string;\n /**\n * Parent resource ID for hierarchical organization. `None` for root\n * resources.\n */\n parent_id?: string | null;\n /** The type of resource (e.g., `project`, `service`, `endpoint`). */\n resource_type: string;\n /** `tenant_id`. */\n tenant_id: string;\n /**\n * The `client_id` that registered this resource through the UMA Protection\n * API (X2), or `None` for a resource created any other way.\n *\n * Read-only from every ordinary path: [`UpdateResource`] cannot set it and\n * [`CreateResource`] cannot either, so the only writer is the\n * resource-registration handler. That is deliberate — the field backs a\n * provenance badge in the admin UI, and a provenance marker anyone can write\n * is decoration that reads like evidence.\n */\n uma_registered_by?: string | null;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Retry policy for failed webhook deliveries. */\nexport interface RetryPolicy {\n /** Multiplier for exponential backoff. */\n backoff_multiplier: number;\n /** Initial delay between retries in seconds. */\n initial_delay_secs: number;\n /** Maximum number of retry attempts. */\n max_retries: number;\n}\n\n/** `Role` (generated from openapi.json). */\nexport interface Role {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** Global roles grant permissions across all resources. */\n is_global: boolean;\n /** `name`. */\n name: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * A role together with its assignment context (the resource it is scoped\n * to).\n */\nexport interface RoleAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /** `role`. */\n role: Role;\n /** The tenants this assignment reaches. See [`TenantScope`]. */\n tenant_scope?: string[] | null;\n}\n\n/** A group together with the resource scope of its assignment of this role. */\nexport interface RoleGroupAssignment {\n /** The assigned group. */\n group: Group;\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n}\n\n/** A service account together with the resource scope of its assignment. */\nexport interface RoleServiceAccountAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The assigned service account. Carries no secret — the client secret is\n * returned once, at creation, and never again.\n */\n service_account: ServiceAccountResponse;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n}\n\n/** A user together with the resource scope of their assignment of this role. */\nexport interface RoleUserAssignment {\n /** `None` means the role was assigned globally (no resource scope). */\n resource_id?: string | null;\n /**\n * The tenants this assignment reaches, or omitted for \"wherever the role\n * does\". Shown next to the assignment so an operator can tell a deliberately\n * narrowed grant from an organization-wide one.\n */\n tenant_scope?: string[] | null;\n /** The assigned user. */\n user: UserResponse;\n}\n\n/** Response for secret rotation. */\nexport interface RotateSecretResponse {\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n}\n\n/**\n * Wire twin of {@link RotateSecretResponse} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface RotateSecretResponseWire {\n client_secret: string;\n}\n\n/** Wrap the secret fields a `RotateSecretResponse` response carries (§27.5). */\nexport function rotateSecretResponseFromWire(w: RotateSecretResponseWire): RotateSecretResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/**\n * Metadata only. The handle is never in a list response — it exists in\n * plaintext exactly once, in [`CreateScimTokenResponse`].\n */\nexport interface ScimTokenResponse {\n /** `created_at`. */\n created_at: string;\n /** `created_by`. */\n created_by: string;\n /** `expires_at`. */\n expires_at: string;\n /** `id`. */\n id: string;\n /** `last_used_at`. */\n last_used_at?: string | null;\n /** `name`. */\n name: string;\n /** `revoked_at`. */\n revoked_at?: string | null;\n /** `status`. */\n status: ScimTokenStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `user_id`. */\n user_id: string;\n}\n\n/**\n * Why a token is or is not currently usable — for display only. The\n * authentication path never surfaces this distinction on the wire.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type ScimTokenStatus =\n | \"active\"\n | \"expired\"\n | \"revoked\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** `Scope` (generated from openapi.json). */\nexport interface Scope {\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description: string;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** The resource this scope belongs to. */\n resource_id: string;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** Fully resolved security settings (all fields present). */\nexport interface SecuritySettings {\n /** `certificate`. */\n certificate: CertificatePolicy;\n /** `created_at`. */\n created_at: string;\n /** `email`. */\n email: EmailVerificationPolicy;\n /** `id`. */\n id: string;\n /** `lockout`. */\n lockout: LockoutPolicy;\n /** `mfa`. */\n mfa: MfaPolicy;\n /** `notification`. */\n notification: NotificationPolicy;\n /** `oidc`. */\n oidc: OidcPolicy;\n /** `opaque`. */\n opaque: OpaquePolicy;\n /** `password`. */\n password: PasswordPolicy;\n /** `privacy`. */\n privacy: PrivacyPolicy;\n /** `scope`. */\n scope: SettingsScope;\n /** `scope_id`. */\n scope_id: string;\n /** `token`. */\n token: TokenPolicy;\n /** `updated_at`. */\n updated_at: string;\n /** `webauthn`. */\n webauthn: WebauthnPolicy;\n}\n\n/**\n * Response for service account creation — includes the one-time plaintext\n * secret.\n */\nexport interface ServiceAccountCreatedResponse {\n /** `client_id`. */\n client_id: string;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret: Sensitive<string>;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description?: string | null;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * Wire twin of {@link ServiceAccountCreatedResponse} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface ServiceAccountCreatedResponseWire {\n client_id: string;\n client_secret: string;\n created_at: string;\n description?: string | null;\n id: string;\n name: string;\n status: UserStatus;\n tenant_id: string;\n updated_at: string;\n}\n\n/**\n * Wrap the secret fields a `ServiceAccountCreatedResponse` response carries\n * (§27.5).\n */\nexport function serviceAccountCreatedResponseFromWire(w: ServiceAccountCreatedResponseWire): ServiceAccountCreatedResponse {\n return {\n ...w,\n client_secret: new Sensitive(w.client_secret),\n };\n}\n\n/** Public-safe service account representation. */\nexport interface ServiceAccountResponse {\n /** `client_id`. */\n client_id: string;\n /** `created_at`. */\n created_at: string;\n /** `description`. */\n description?: string | null;\n /** `id`. */\n id: string;\n /** `name`. */\n name: string;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/** One of a user's sessions, as an administrator sees it. */\nexport interface SessionResponse {\n /** RFC 8176 method references for that authentication. */\n amr: string[];\n /**\n * X7.2 — when the end user actually authenticated, which is not `created_at`\n * on a session produced by refresh rotation.\n */\n authenticated_at: string;\n /** `created_at`. */\n created_at: string;\n /** `expires_at`. */\n expires_at: string;\n /** `id`. */\n id: string;\n /** `ip_address`. */\n ip_address?: string | null;\n /**\n * T-254 — when a refresh token of this session was last presented after it\n * had already been rotated. `None` if that has never happened.\n */\n refresh_replay_at?: string | null;\n /**\n * T-254 — replays accepted under the FAPI 2.0 §5.3.2.1-9 grace window. Only\n * ever non-zero for a client registered `profile: fapi2`.\n */\n refresh_replay_grace_accepted: number;\n /**\n * T-254 — replays refused because there was no window to accept them in.\n * Nothing a conformant client does.\n */\n refresh_replay_refused: number;\n /**\n * T-254 — the badge: `none`, `fapi_grace_retry` or `refused`.\n *\n * Derived from the two counters below rather than stored, so it cannot\n * disagree with them. A refusal outranks an accepted grace retry however the\n * counts compare.\n */\n refresh_replay_verdict: string;\n /** `user_agent`. */\n user_agent?: string | null;\n}\n\n/** Body for `PUT .../ca-certificates/{id}/mtls-trust-anchor`. */\nexport interface SetMtlsTrustAnchor {\n /** Whether this CA should be trusted for client-certificate authentication. */\n enabled: boolean;\n}\n\n/** Input for setting organization-level email config. */\nexport interface SetOrgEmailConfig {\n /** `enabled`. */\n enabled: boolean;\n /** `from_email`. */\n from_email: string;\n /** `from_name`. */\n from_name: string;\n /** `provider`. */\n provider: ProviderConfig;\n /** `reply_to`. */\n reply_to?: string | null;\n}\n\n/** Input for setting organization-level security settings. */\nexport interface SetOrgSettings {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs: number;\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled: boolean;\n /** `default_cert_validity_days`. */\n default_cert_validity_days: number;\n /** `default_locale`. */\n default_locale?: string | null;\n /** `deletion_grace_period_days`. */\n deletion_grace_period_days?: number;\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours: number;\n /** `email_verification_required`. */\n email_verification_required: boolean;\n /** `hibp_check_enabled`. */\n hibp_check_enabled: boolean;\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier: number;\n /** `lockout_duration_secs`. */\n lockout_duration_secs: number;\n /** `max_cert_validity_days`. */\n max_cert_validity_days: number;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts: number;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs: number;\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs: number;\n /** `mfa_enforced`. */\n mfa_enforced: boolean;\n /** `min_length`. */\n min_length: number;\n /** `opaque_ksf`. */\n opaque_ksf?: string;\n /** `opaque_mode`. */\n opaque_mode?: string;\n /** `opaque_suite`. */\n opaque_suite?: string;\n /** `password_history_count`. */\n password_history_count: number;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs: number;\n /** `require_digits`. */\n require_digits: boolean;\n /** `require_lowercase`. */\n require_lowercase: boolean;\n /** `require_symbols`. */\n require_symbols: boolean;\n /** `require_uppercase`. */\n require_uppercase: boolean;\n /** `sensitive_scopes_enabled`. */\n sensitive_scopes_enabled?: boolean;\n /** `webauthn_user_verification`. */\n webauthn_user_verification?: string;\n}\n\n/**\n * Whether a settings row belongs to an organization or a tenant.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type SettingsScope =\n | \"Org\"\n | \"Tenant\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Request body for signing an audit batch. */\nexport interface SignAuditBatchRequest {\n /** `entry_ids`. */\n entry_ids: string[];\n}\n\n/**\n * Body of `POST .../tenants/{tenant_id}/signing-cas/sign-csr`.\n *\n * Deliberately carries no key algorithm: it is the CSR's, read out of the\n * request, because a caller who could state it separately could state one\n * the key does not have.\n */\nexport interface SignIntermediateCsrRequest {\n /** PEM-encoded PKCS#10 certificate signing request. */\n csr_pem: string;\n /** The organization CA that signs it. */\n parent_ca_id: string;\n /** Validity duration in days, capped to the parent's own expiry. */\n validity_days: number;\n}\n\n/** A signed batch of audit log entries. */\nexport interface SignedAuditBatch {\n /** `batch_id`. */\n batch_id: string;\n /** `entry_ids`. */\n entry_ids: string[];\n /** ASCII-armored PGP signed message containing the audit batch payload. */\n signature_armored: string;\n /** `signed_at`. */\n signed_at: string;\n /** `signing_key_id`. */\n signing_key_id: string;\n /** `tenant_id`. */\n tenant_id: string;\n}\n\n/**\n * SMTP-specific configuration.\n *\n * `password` is write-only (D-01): `#[serde(skip_serializing)]` means it is\n * never emitted in a GET/serialized response. On the write path (D-02),\n * `#[serde(default)]` lets a caller omit the field entirely (deserializing\n * to `\"\"`); an empty string is the sentinel for \"no new secret supplied —\n * preserve whatever is already stored\" (see `SurrealEmailConfigRepository::\n * set_org_config`). A non-empty value is a real secret to encrypt+replace.\n */\nexport interface SmtpConfig {\n /** `host`. */\n host: string;\n /** `port`. */\n port: number;\n /** Use STARTTLS (true) or implicit TLS (false). */\n starttls: boolean;\n /** `username`. */\n username: string;\n}\n\n/**\n * A tenant is an isolated context within an organization.\n *\n * Each tenant has its own set of users, roles, permissions, resources,\n * certificates, and configuration. Tenants can represent environments\n * (dev/staging/prod) or separate business contexts.\n */\nexport interface Tenant {\n /** `created_at`. */\n created_at: string;\n /** `id`. */\n id: string;\n /**\n * Whether this is an ordinary tenant or the organization's own scope.\n *\n * `#[serde(default)]` so every row written before organization scope existed\n * reads back as [`TenantKind::Standard`], which is what it is.\n */\n kind?: TenantKind;\n /** Arbitrary key-value metadata. */\n metadata: unknown;\n /** Human-readable name. */\n name: string;\n /** The organization this tenant belongs to. */\n organization_id: string;\n /** URL-safe unique identifier within the organization (e.g., `production`). */\n slug: string;\n /** Lifecycle status. New tenants default to [`TenantStatus::Active`]. */\n status: TenantStatus;\n /** `updated_at`. */\n updated_at: string;\n}\n\n/**\n * What a tenant *is*, as distinct from what state it is in.\n *\n * Reserved rather than inferred: an organization has exactly one tenant of\n * kind [`Self::Organization`], enforced by a unique index rather than by\n * convention. Deriving it from a magic slug or from \"the oldest tenant\"\n * would make the organization scope something an operator could rename or\n * delete by accident, and it is the scope the super-admin lives in.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type TenantKind =\n | \"standard\"\n | \"organization\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Partial tenant overrides. `None` = inherit from org baseline.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface TenantSettingsOverride {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs?: number | null;\n /** `admin_notifications_enabled`. */\n admin_notifications_enabled?: boolean | null;\n /** `default_cert_validity_days`. */\n default_cert_validity_days?: number | null;\n /**\n * The tenant's fallback UI language. Not ordered, therefore not validated\n * against the baseline and never clamped — see [`OidcPolicy`].\n */\n default_locale?: string | null;\n /** `deletion_grace_period_days`. */\n deletion_grace_period_days?: number | null;\n /** `email_verification_grace_period_hours`. */\n email_verification_grace_period_hours?: number | null;\n /** `email_verification_required`. */\n email_verification_required?: boolean | null;\n /** `hibp_check_enabled`. */\n hibp_check_enabled?: boolean | null;\n /** `lockout_backoff_multiplier`. */\n lockout_backoff_multiplier?: number | null;\n /** `lockout_duration_secs`. */\n lockout_duration_secs?: number | null;\n /** `max_cert_validity_days`. */\n max_cert_validity_days?: number | null;\n /** `max_failed_login_attempts`. */\n max_failed_login_attempts?: number | null;\n /** `max_lockout_duration_secs`. */\n max_lockout_duration_secs?: number | null;\n /** `mfa_challenge_lifetime_secs`. */\n mfa_challenge_lifetime_secs?: number | null;\n /** `mfa_enforced`. */\n mfa_enforced?: boolean | null;\n /** `min_length`. */\n min_length?: number | null;\n /** `opaque_ksf`. */\n opaque_ksf?: string | null;\n /** `opaque_mode`. */\n opaque_mode?: string | null;\n /** `opaque_suite`. */\n opaque_suite?: string | null;\n /** `password_history_count`. */\n password_history_count?: number | null;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs?: number | null;\n /** `require_digits`. */\n require_digits?: boolean | null;\n /** `require_lowercase`. */\n require_lowercase?: boolean | null;\n /** `require_symbols`. */\n require_symbols?: boolean | null;\n /** `require_uppercase`. */\n require_uppercase?: boolean | null;\n /** `sensitive_scopes_enabled`. */\n sensitive_scopes_enabled?: boolean | null;\n /** `webauthn_user_verification`. */\n webauthn_user_verification?: string | null;\n}\n\n/**\n * Lifecycle status of a tenant.\n *\n * A `Suspended` tenant remains stored and its data isolated, but is treated\n * as administratively disabled. New tenants are `Active` by default.\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type TenantStatus =\n | \"Active\"\n | \"Suspended\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * X4 trust for exchanging this provider's tokens (RFC 8693, external\n * issuer).\n *\n * Mirrors [`TokenExchangeTrust`] on the wire rather than reusing it directly\n * so the API surface can carry its own defaults: an admin PUTting a partial\n * block gets the documented default for anything they omitted, instead of a\n * deserialization error listing fields they have never heard of.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface TokenExchangeTrustRequest {\n /**\n * Audiences an incoming subject token may name. Required (non-empty) when\n * `enabled`; there is deliberately no accept-all value.\n */\n accepted_audiences?: string[];\n /**\n * Off unless explicitly enabled. Configuring a provider for *login* is not\n * agreement to accept its tokens as API credentials.\n */\n enabled?: boolean;\n /** Per-provider ceiling on the issued AXIAM token's lifetime. */\n max_lifetime_secs?: number | null;\n /** Bound on `now - iat`, independent of the token's own `exp`. */\n max_token_age_secs?: number | null;\n /**\n * External asserted value -> AXIAM scopes. Deny-by-default: an external\n * value with no entry contributes nothing.\n */\n scope_map?: Record<string, unknown>;\n /** `linked_only` (default) or `jit_provision`. */\n subject_mapping?: string | null;\n}\n\n/**\n * X4 trust as returned. Same shape as the request; nothing here is secret —\n * an operator reading a provider needs to see exactly what it trusts.\n */\nexport interface TokenExchangeTrustResponse {\n /** `accepted_audiences`. */\n accepted_audiences: string[];\n /** `enabled`. */\n enabled: boolean;\n /** `max_lifetime_secs`. */\n max_lifetime_secs?: number | null;\n /** `max_token_age_secs`. */\n max_token_age_secs: number;\n /** `scope_map`. */\n scope_map: Record<string, unknown>;\n /** `subject_mapping`. */\n subject_mapping: string;\n}\n\n/** Token lifetime configuration. */\nexport interface TokenPolicy {\n /** `access_token_lifetime_secs`. */\n access_token_lifetime_secs: number;\n /** `refresh_token_lifetime_secs`. */\n refresh_token_lifetime_secs: number;\n}\n\n/**\n * What to do with an AAGUID that has no MDS entry (i.e. FIDO Alliance has no\n * metadata for it — not necessarily malicious, MDS coverage is incomplete\n * for some legitimate authenticators).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type UnknownAaguidAction =\n | \"allow\"\n | \"deny\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * `UpdateFederationConfigRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateFederationConfigRequest {\n /** Whether tenants may inherit this organization-level provider. */\n allow_tenant_inheritance?: boolean | null;\n /** Accepted signature algorithms (CQ-B40/REQ-14 AC-5). */\n allowed_algorithms?: string[] | null;\n /** Accepted external IdP tenants for a templated issuer. Replaced wholesale. */\n allowed_issuer_tenants?: string[] | null;\n /** Apple Key ID. `Some(None)` clears it. */\n apple_key_id?: string | null;\n /** Apple Team ID. `Some(None)` clears it. */\n apple_team_id?: string | null;\n /** `attribute_map`. */\n attribute_map?: unknown;\n /** OAuth2-variant authorization endpoint. `Some(None)` clears it. */\n authorization_endpoint?: string | null;\n /** Sign-in-button icon for a generic provider. `Some(None)` clears it. */\n button_icon?: string | null;\n /** `client_id`. */\n client_id?: string | null;\n /**\n * `client_secret`.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n client_secret?: Sensitive<string>;\n /** `enabled`. */\n enabled?: boolean | null;\n /**\n * PEM-encoded X.509 certificate for verifying SAML assertions (CQ-B40/REQ-14\n * AC-5). `Some(None)` clears the stored cert.\n */\n idp_signing_cert_pem?: string | null;\n /** `metadata_url`. */\n metadata_url?: string | null;\n /** `provider`. */\n provider?: string | null;\n /** Operator-chosen identifier for a `generic_*` kind. `Some(None)` clears it. */\n provider_slug?: string | null;\n /** Send PKCE on the authorization request. */\n require_pkce?: boolean | null;\n /**\n * Scopes to request. Replaced wholesale; empty restores the per-kind\n * default.\n */\n scopes?: string[] | null;\n /** OAuth2-variant token endpoint. `Some(None)` clears it. */\n token_endpoint?: string | null;\n /** `token_exchange`. */\n token_exchange?: TokenExchangeTrustRequest | null;\n /** OAuth2-variant userinfo endpoint. `Some(None)` clears it. */\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Wire twin of {@link UpdateFederationConfigRequest} — plain strings, never\n * logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface UpdateFederationConfigRequestWire {\n allow_tenant_inheritance?: boolean | null;\n allowed_algorithms?: string[] | null;\n allowed_issuer_tenants?: string[] | null;\n apple_key_id?: string | null;\n apple_team_id?: string | null;\n attribute_map?: unknown;\n authorization_endpoint?: string | null;\n button_icon?: string | null;\n client_id?: string | null;\n client_secret?: string;\n enabled?: boolean | null;\n idp_signing_cert_pem?: string | null;\n metadata_url?: string | null;\n provider?: string | null;\n provider_slug?: string | null;\n require_pkce?: boolean | null;\n scopes?: string[] | null;\n token_endpoint?: string | null;\n token_exchange?: TokenExchangeTrustRequest | null;\n userinfo_endpoint?: string | null;\n}\n\n/**\n * Unwrap a `UpdateFederationConfigRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function updateFederationConfigRequestToWire(v: UpdateFederationConfigRequest): UpdateFederationConfigRequestWire {\n return {\n ...v,\n client_secret: v.client_secret === undefined ? undefined : v.client_secret.expose(),\n };\n}\n\n/**\n * `UpdateGroup` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateGroup {\n /** `description`. */\n description?: string | null;\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateNotificationRuleRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateNotificationRuleRequest {\n /** `description`. */\n description?: string | null;\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: NotificationEventType[] | null;\n /** `name`. */\n name?: string | null;\n /** `recipient_emails`. */\n recipient_emails?: string[] | null;\n}\n\n/**\n * `UpdateOAuth2ClientRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateOAuth2ClientRequest {\n /** `authn_request_params`. */\n authn_request_params?: AuthnRequestParamsMode | null;\n /**\n * Pass an empty string to clear a previously registered URI — the one edit\n * an operator makes when an RP is decommissioned.\n */\n backchannel_logout_uri?: string | null;\n /** X7.3 — see [`CreateOAuth2ClientRequest::browser_sso`]. */\n browser_sso?: boolean | null;\n /** `dpop_bound_access_tokens`. */\n dpop_bound_access_tokens?: boolean | null;\n /** `dpop_require_nonce`. */\n dpop_require_nonce?: boolean | null;\n /** `grant_types`. */\n grant_types?: string[] | null;\n /**\n * X5.1 — see the create DTO. `Some(\"\")` clears, so a client can be migrated\n * from an inline key set to a published one.\n */\n jwks?: string | null;\n /** X5.1 — see the create DTO. `Some(\"\")` clears. */\n jwks_uri?: string | null;\n /** `name`. */\n name?: string | null;\n /** `post_logout_redirect_uris`. */\n post_logout_redirect_uris?: string[] | null;\n /** `profile`. */\n profile?: ClientProfile | null;\n /** `redirect_uris`. */\n redirect_uris?: string[] | null;\n /** `require_par`. */\n require_par?: boolean | null;\n /** `scopes`. */\n scopes?: string[] | null;\n /** `self_signed_tls_client_auth_thumbprints`. */\n self_signed_tls_client_auth_thumbprints?: string[] | null;\n /** `tls_client_auth_san_dns`. */\n tls_client_auth_san_dns?: string | null;\n /** `tls_client_auth_san_uri`. */\n tls_client_auth_san_uri?: string | null;\n /** Pass an empty string to clear, as with `backchannel_logout_uri`. */\n tls_client_auth_subject_dn?: string | null;\n /** `tls_client_certificate_bound_access_tokens`. */\n tls_client_certificate_bound_access_tokens?: boolean | null;\n /** `token_endpoint_auth_method`. */\n token_endpoint_auth_method?: ClientAuthMethod | null;\n}\n\n/**\n * `UpdateOrganizationRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateOrganizationRequest {\n /** Free-form metadata (the admin UI stores `description` here). */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `slug`. */\n slug?: string | null;\n}\n\n/**\n * `UpdatePermissionRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdatePermissionRequest {\n /** `action`. */\n action?: string | null;\n /** `description`. */\n description?: string | null;\n}\n\n/**\n * `UpdateReactorRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateReactorRequest {\n /** `description`. */\n description?: string | null;\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: string[] | null;\n /** `failure_policy`. */\n failure_policy?: FailurePolicy | null;\n /** `mode`. */\n mode?: ReactorMode | null;\n /** `name`. */\n name?: string | null;\n /** `priority`. */\n priority?: number | null;\n /** `timeout_ms`. */\n timeout_ms?: number | null;\n}\n\n/**\n * `UpdateResourceRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateResourceRequest {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `parent_id`. */\n parent_id?: string | null;\n /** `resource_type`. */\n resource_type?: string | null;\n}\n\n/**\n * `UpdateRole` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateRole {\n /** `description`. */\n description?: string | null;\n /** `is_global`. */\n is_global?: boolean | null;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateScopeRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateScopeRequest {\n /** `description`. */\n description?: string | null;\n /** `name`. */\n name?: string | null;\n}\n\n/**\n * `UpdateServiceAccount` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateServiceAccount {\n /** `description`. */\n description?: string | null;\n /** `name`. */\n name?: string | null;\n /** `status`. */\n status?: UserStatus | null;\n}\n\n/**\n * Fields that can be updated on an existing tenant.\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateTenant {\n /** `metadata`. */\n metadata?: unknown;\n /** `name`. */\n name?: string | null;\n /** `slug`. */\n slug?: string | null;\n /** `status`. */\n status?: TenantStatus | null;\n}\n\n/**\n * `UpdateUserRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateUserRequest {\n /** `email`. */\n email?: string | null;\n /** `metadata`. */\n metadata?: unknown;\n /** `status`. */\n status?: UserStatus | null;\n /** `username`. */\n username?: string | null;\n}\n\n/**\n * `UpdateWebhookRequest` (generated from openapi.json).\n *\n * Every field is optional, so this is a **sparse** body: what you leave out\n * is left unchanged, and is omitted from the wire request entirely rather\n * than sent as `null` (§27.4 rule 5).\n */\nexport interface UpdateWebhookRequest {\n /** `enabled`. */\n enabled?: boolean | null;\n /** `events`. */\n events?: string[] | null;\n /** `retry_policy`. */\n retry_policy?: RetryPolicy | null;\n /**\n * New HMAC-SHA256 shared secret (D-02 secret rotation). Encrypted\n * server-side with AES-256-GCM before storage; omit to leave the existing\n * secret untouched.\n *\n * **Secret.** Redacted from every string, log and JSON rendering; call\n * `.expose()` to read it.\n */\n secret?: Sensitive<string>;\n /** `url`. */\n url?: string | null;\n}\n\n/**\n * Wire twin of {@link UpdateWebhookRequest} — plain strings, never logged.\n *\n * @internal — it exists because `Sensitive` cannot be serialized, not\n * because a consumer should read it.\n */\nexport interface UpdateWebhookRequestWire {\n enabled?: boolean | null;\n events?: string[] | null;\n retry_policy?: RetryPolicy | null;\n secret?: string;\n url?: string | null;\n}\n\n/**\n * Unwrap a `UpdateWebhookRequest` for the wire.\n *\n * One of the two places a §27 secret is unwrapped, so that \"put a secret on\n * the socket\" stays a single greppable call rather than fourteen (§7 rule\n * 4).\n */\nexport function updateWebhookRequestToWire(v: UpdateWebhookRequest): UpdateWebhookRequestWire {\n return {\n ...v,\n secret: v.secret === undefined ? undefined : v.secret.expose(),\n };\n}\n\n/** Public-safe user representation (no password_hash, no mfa_secret). */\nexport interface UserResponse {\n /** `created_at`. */\n created_at: string;\n /** `email`. */\n email: string;\n /**\n * True when the user's email address has been verified (`email_verified_at`\n * is set). Exposed for the admin UI / profile.\n */\n email_verified: boolean;\n /** Number of consecutive failed login attempts. */\n failed_login_attempts: number;\n /** `id`. */\n id: string;\n /** Whether the account is currently locked (locked_until is in the future). */\n is_locked: boolean;\n /** Timestamp until which the account is locked, if any. */\n locked_until?: string | null;\n /** `metadata`. */\n metadata: unknown;\n /** `mfa_enabled`. */\n mfa_enabled: boolean;\n /** `status`. */\n status: UserStatus;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `username`. */\n username: string;\n}\n\n/**\n * `UserStatus` (generated from openapi.json).\n *\n * An **open** enum. The final `(string & {})` arm accepts a value this SDK's\n * copy of the spec does not list, so the next one the server adds reaches a\n * caller as itself rather than failing the response it arrived in (CONTRACT\n * §27.11 rule 1). The named arms still autocomplete and still narrow; what\n * the extra arm removes is the illusion that a value outside them cannot\n * occur, which is what an exhaustive `switch` over the named ones quietly\n * assumes.\n */\nexport type UserStatus =\n | \"Active\"\n | \"Inactive\"\n | \"Locked\"\n | \"PendingVerification\"\n | \"Anonymized\"\n | \"Deleted\"\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/**\n * Per-tenant WebAuthn attestation policy (D5). One row per tenant; an absent\n * row means [`WebauthnAttestationPolicy::default`], which is today's\n * behavior unchanged.\n */\nexport interface WebauthnAttestationPolicy {\n /**\n * `None` = every AAGUID is allowed except `blocked_aaguids`.\n *\n * `Some(vec![])` is a deliberate \"nothing may register\" policy and is\n * accepted as such: `evaluate` denies every AAGUID against an empty\n * allow-list. Nothing rejects it, precisely because the failure direction is\n * safe — a client that sends `[]` when it meant `null` gets a locked-down\n * tenant, which is visible immediately, rather than an open one, which is\n * not.\n */\n allowed_aaguids?: string[] | null;\n /**\n * Deny registration if the MDS entry has ever reported `REVOKED` or any\n * `*_COMPROMISE` status (sticky — D8 step 7).\n */\n block_revoked_status: boolean;\n /** `blocked_aaguids`. */\n blocked_aaguids?: string[];\n /** `min_certification`. */\n min_certification?: CertificationLevel | null;\n /** `mode`. */\n mode: AttestationMode;\n /**\n * Require *some* `FIDO_CERTIFIED*` status, any level. Independent of (and\n * checked before) `min_certification`.\n */\n require_fido_certified: boolean;\n /** `unknown_aaguid`. */\n unknown_aaguid?: UnknownAaguidAction | null;\n}\n\n/**\n * WebAuthn ceremony policy.\n *\n * One field today. It is a struct rather than a bare field on\n * [`SecuritySettings`] so that the next WebAuthn control has an obvious\n * home, and so the admin UI can group them.\n *\n * The *attestation* policy is deliberately not here: it lives in\n * [`crate::models::webauthn_policy::WebauthnAttestationPolicy`], is\n * tenant-only, and cannot join this model because AAGUID allow/block lists\n * have no \"more restrictive than\" ordering to validate an override against.\n * User verification does, so it can.\n */\nexport interface WebauthnPolicy {\n /**\n * How hard the authenticator must prove *who* is present.\n *\n * Applies to enrolment and to second-factor authentication. Usernameless\n * sign-in is held to `required` whatever this says — see\n * [`WebauthnUserVerification`].\n */\n webauthn_user_verification: string;\n}\n\n/** Webhook response — omits the shared secret. */\nexport interface WebhookResponse {\n /** `created_at`. */\n created_at: string;\n /** `enabled`. */\n enabled: boolean;\n /** `events`. */\n events: string[];\n /** `id`. */\n id: string;\n /** `retry_policy`. */\n retry_policy: RetryPolicy;\n /** `tenant_id`. */\n tenant_id: string;\n /** `updated_at`. */\n updated_at: string;\n /** `url`. */\n url: string;\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `users` management namespace (CONTRACT §27.1).\n *\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `users` namespace handle.\n *\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class UsersApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/users` */\n async list(page: PageRequest = {}): Promise<Page<models.UserResponse>> {\n const wire = await sendManagement<Page<models.UserResponse>>(this.#client, {\n operation: 'users.list',\n method: 'GET',\n pathTemplate: '/api/v1/users',\n path: '/api/v1/users',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `users.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.UserResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/users`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateUserRequest): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.create',\n method: 'POST',\n pathTemplate: '/api/v1/users',\n path: '/api/v1/users',\n body: models.createUserRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/users/{user_id}` */\n async get(userId: string): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.get',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(userId: string, body: models.UpdateUserRequest): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.update',\n method: 'PUT',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/users/{user_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}`,\n });\n }\n\n /** `GET /api/v1/users/{user_id}/mfa-methods` */\n async listMfaMethods(userId: string): Promise<models.MfaMethodResponse[]> {\n const wire = await sendManagement<models.MfaMethodResponse[]>(this.#client, {\n operation: 'users.list_mfa_methods',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}/mfa-methods',\n path: `/api/v1/users/${encodeURIComponent(userId)}/mfa-methods`,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/users/{user_id}/mfa-methods/{method_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteMfaMethod(userId: string, methodId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.delete_mfa_method',\n method: 'DELETE',\n pathTemplate: '/api/v1/users/{user_id}/mfa-methods/{method_id}',\n path: `/api/v1/users/${encodeURIComponent(userId)}/mfa-methods/${encodeURIComponent(methodId)}`,\n });\n }\n\n /**\n * `POST /api/v1/users/{user_id}/reset-mfa`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async resetMfa(userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'users.reset_mfa',\n method: 'POST',\n pathTemplate: '/api/v1/users/{user_id}/reset-mfa',\n path: `/api/v1/users/${encodeURIComponent(userId)}/reset-mfa`,\n });\n }\n\n /**\n * `POST /api/v1/users/{user_id}/unlock`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unlock(userId: string): Promise<models.UserResponse> {\n const wire = await sendManagement<models.UserResponse>(this.#client, {\n operation: 'users.unlock',\n method: 'POST',\n pathTemplate: '/api/v1/users/{user_id}/unlock',\n path: `/api/v1/users/${encodeURIComponent(userId)}/unlock`,\n });\n return wire;\n }\n\n /** `GET /api/v1/users/{user_id}/roles` */\n async listRoles(userId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'users.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}/roles',\n path: `/api/v1/users/${encodeURIComponent(userId)}/roles`,\n });\n return wire;\n }\n\n /** `GET /api/v1/users/{user_id}/sessions` */\n async listSessions(userId: string): Promise<models.SessionResponse[]> {\n const wire = await sendManagement<models.SessionResponse[]>(this.#client, {\n operation: 'users.list_sessions',\n method: 'GET',\n pathTemplate: '/api/v1/users/{user_id}/sessions',\n path: `/api/v1/users/${encodeURIComponent(userId)}/sessions`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `groups` management namespace (CONTRACT §27.1).\n *\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `groups` namespace handle.\n *\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class GroupsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/groups` */\n async list(page: PageRequest = {}): Promise<Page<models.Group>> {\n const wire = await sendManagement<Page<models.Group>>(this.#client, {\n operation: 'groups.list',\n method: 'GET',\n pathTemplate: '/api/v1/groups',\n path: '/api/v1/groups',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Group[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/groups`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateGroupRequest): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.create',\n method: 'POST',\n pathTemplate: '/api/v1/groups',\n path: '/api/v1/groups',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/groups/{group_id}` */\n async get(groupId: string): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.get',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(groupId: string, body: models.UpdateGroup): Promise<models.Group> {\n const wire = await sendManagement<models.Group>(this.#client, {\n operation: 'groups.update',\n method: 'PUT',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(groupId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}`,\n });\n }\n\n /** `GET /api/v1/groups/{group_id}/members` */\n async listMembers(groupId: string, page: PageRequest = {}): Promise<Page<models.UserResponse>> {\n const wire = await sendManagement<Page<models.UserResponse>>(this.#client, {\n operation: 'groups.list_members',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/members',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list_members` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listMembersAll(groupId: string, start: PageRequest = {}): Promise<models.UserResponse[]> {\n return collectPages(start, (p) => this.listMembers(groupId, p));\n }\n\n /**\n * `POST /api/v1/groups/{group_id}/members`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async addMember(groupId: string, body: models.AddMemberRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.add_member',\n method: 'POST',\n pathTemplate: '/api/v1/groups/{group_id}/members',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}/members/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async removeMember(groupId: string, userId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.remove_member',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}/members/{user_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(userId)}`,\n });\n }\n\n /** `GET /api/v1/groups/{group_id}/roles` */\n async listRoles(groupId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'groups.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/roles',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/roles`,\n });\n return wire;\n }\n\n /** `GET /api/v1/groups/{group_id}/service-accounts` */\n async listServiceAccounts(groupId: string, page: PageRequest = {}): Promise<Page<models.ServiceAccountResponse>> {\n const wire = await sendManagement<Page<models.ServiceAccountResponse>>(this.#client, {\n operation: 'groups.list_service_accounts',\n method: 'GET',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `groups.list_service_accounts` to exhaustion, concatenating every\n * page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listServiceAccountsAll(groupId: string, start: PageRequest = {}): Promise<models.ServiceAccountResponse[]> {\n return collectPages(start, (p) => this.listServiceAccounts(groupId, p));\n }\n\n /**\n * `POST /api/v1/groups/{group_id}/service-accounts`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async addServiceAccount(groupId: string, body: models.AddServiceAccountMemberRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.add_service_account',\n method: 'POST',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/groups/{group_id}/service-accounts/{service_account_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async removeServiceAccount(groupId: string, serviceAccountId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'groups.remove_service_account',\n method: 'DELETE',\n pathTemplate: '/api/v1/groups/{group_id}/service-accounts/{service_account_id}',\n path: `/api/v1/groups/${encodeURIComponent(groupId)}/service-accounts/${encodeURIComponent(serviceAccountId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `roles` management namespace (CONTRACT §27.1).\n *\n * Roles, their permission sets, and their assignment to users and groups.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `roles` namespace handle.\n *\n * Roles, their permission sets, and their assignment to users and groups.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class RolesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/roles` */\n async list(page: PageRequest = {}): Promise<Page<models.Role>> {\n const wire = await sendManagement<Page<models.Role>>(this.#client, {\n operation: 'roles.list',\n method: 'GET',\n pathTemplate: '/api/v1/roles',\n path: '/api/v1/roles',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `roles.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Role[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/roles`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateRoleRequest): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.create',\n method: 'POST',\n pathTemplate: '/api/v1/roles',\n path: '/api/v1/roles',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/roles/{role_id}` */\n async get(roleId: string): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.get',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/roles/{role_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(roleId: string, body: models.UpdateRole): Promise<models.Role> {\n const wire = await sendManagement<models.Role>(this.#client, {\n operation: 'roles.update',\n method: 'PUT',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(roleId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}`,\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/users` */\n async listUsers(roleId: string): Promise<models.RoleUserAssignment[]> {\n const wire = await sendManagement<models.RoleUserAssignment[]>(this.#client, {\n operation: 'roles.list_users',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/users',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/users`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToUser(roleId: string, body: models.AssignRoleToUserRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_user',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/users',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/users/{user_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromUser(roleId: string, userId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_user',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/users/{user_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/users/${encodeURIComponent(userId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/groups` */\n async listGroups(roleId: string): Promise<models.RoleGroupAssignment[]> {\n const wire = await sendManagement<models.RoleGroupAssignment[]>(this.#client, {\n operation: 'roles.list_groups',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/groups',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/groups`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToGroup(roleId: string, body: models.AssignRoleToGroupRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_group',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/groups',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/groups/{group_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromGroup(roleId: string, groupId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_group',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/groups/{group_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/groups/${encodeURIComponent(groupId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/permissions` */\n async listPermissions(roleId: string): Promise<models.ResolvedPermissionGrant[]> {\n const wire = await sendManagement<models.ResolvedPermissionGrant[]>(this.#client, {\n operation: 'roles.list_permissions',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/permissions',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/permissions`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async grantPermission(roleId: string, body: models.GrantPermissionRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.grant_permission',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/permissions',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions`,\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revokePermission(roleId: string, permissionId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.revoke_permission',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/permissions/{permission_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/permissions/${encodeURIComponent(permissionId)}`,\n });\n }\n\n /** `GET /api/v1/roles/{role_id}/service-accounts` */\n async listServiceAccounts(roleId: string): Promise<models.RoleServiceAccountAssignment[]> {\n const wire = await sendManagement<models.RoleServiceAccountAssignment[]>(this.#client, {\n operation: 'roles.list_service_accounts',\n method: 'GET',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/roles/{role_id}/service-accounts`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async assignToServiceAccount(roleId: string, body: models.AssignRoleToServiceAccountRequest): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.assign_to_service_account',\n method: 'POST',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts`,\n body: models.omitEmptyTenantScope(body),\n });\n }\n\n /**\n * `DELETE /api/v1/roles/{role_id}/service-accounts/{service_account_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async unassignFromServiceAccount(roleId: string, serviceAccountId: string, resourceId?: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'roles.unassign_from_service_account',\n method: 'DELETE',\n pathTemplate: '/api/v1/roles/{role_id}/service-accounts/{service_account_id}',\n path: `/api/v1/roles/${encodeURIComponent(roleId)}/service-accounts/${encodeURIComponent(serviceAccountId)}`,\n query: { 'resource_id': resourceId },\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `permissions` management namespace (CONTRACT §27.1).\n *\n * Permissions -- an action on a resource, optionally narrowed by a scope.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `permissions` namespace handle.\n *\n * Permissions -- an action on a resource, optionally narrowed by a scope.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PermissionsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/permissions` */\n async list(page: PageRequest = {}): Promise<Page<models.Permission>> {\n const wire = await sendManagement<Page<models.Permission>>(this.#client, {\n operation: 'permissions.list',\n method: 'GET',\n pathTemplate: '/api/v1/permissions',\n path: '/api/v1/permissions',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `permissions.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Permission[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/permissions`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreatePermissionRequest): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.create',\n method: 'POST',\n pathTemplate: '/api/v1/permissions',\n path: '/api/v1/permissions',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/permissions/{permission_id}` */\n async get(permissionId: string): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.get',\n method: 'GET',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(permissionId: string, body: models.UpdatePermissionRequest): Promise<models.Permission> {\n const wire = await sendManagement<models.Permission>(this.#client, {\n operation: 'permissions.update',\n method: 'PUT',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/permissions/{permission_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(permissionId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'permissions.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/permissions/{permission_id}',\n path: `/api/v1/permissions/${encodeURIComponent(permissionId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `resources` management namespace (CONTRACT §27.1).\n *\n * The resource hierarchy role assignments cascade down.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `resources` namespace handle.\n *\n * The resource hierarchy role assignments cascade down.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ResourcesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/resources` */\n async list(page: PageRequest = {}): Promise<Page<models.Resource>> {\n const wire = await sendManagement<Page<models.Resource>>(this.#client, {\n operation: 'resources.list',\n method: 'GET',\n pathTemplate: '/api/v1/resources',\n path: '/api/v1/resources',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `resources.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Resource[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/resources`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateResourceRequest): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.create',\n method: 'POST',\n pathTemplate: '/api/v1/resources',\n path: '/api/v1/resources',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}` */\n async get(resourceId: string): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.get',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/resources/{resource_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(resourceId: string, body: models.UpdateResourceRequest): Promise<models.Resource> {\n const wire = await sendManagement<models.Resource>(this.#client, {\n operation: 'resources.update',\n method: 'PUT',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/resources/{resource_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(resourceId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'resources.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/resources/{resource_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}`,\n });\n }\n\n /** `GET /api/v1/resources/{resource_id}/children` */\n async listChildren(resourceId: string): Promise<models.Resource[]> {\n const wire = await sendManagement<models.Resource[]>(this.#client, {\n operation: 'resources.list_children',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/children',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/children`,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}/ancestors` */\n async listAncestors(resourceId: string): Promise<models.Resource[]> {\n const wire = await sendManagement<models.Resource[]>(this.#client, {\n operation: 'resources.list_ancestors',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/ancestors',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/ancestors`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `scopes` management namespace (CONTRACT §27.1).\n *\n * Sub-resource granularity, always addressed under their resource.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `scopes` namespace handle.\n *\n * Sub-resource granularity, always addressed under their resource.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ScopesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/resources/{resource_id}/scopes` */\n async list(resourceId: string): Promise<models.Scope[]> {\n const wire = await sendManagement<models.Scope[]>(this.#client, {\n operation: 'scopes.list',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/resources/{resource_id}/scopes`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(resourceId: string, body: models.CreateScopeRequest): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.create',\n method: 'POST',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/resources/{resource_id}/scopes/{scope_id}` */\n async get(resourceId: string, scopeId: string): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.get',\n method: 'GET',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/resources/{resource_id}/scopes/{scope_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(resourceId: string, scopeId: string, body: models.UpdateScopeRequest): Promise<models.Scope> {\n const wire = await sendManagement<models.Scope>(this.#client, {\n operation: 'scopes.update',\n method: 'PUT',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/resources/{resource_id}/scopes/{scope_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(resourceId: string, scopeId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'scopes.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/resources/{resource_id}/scopes/{scope_id}',\n path: `/api/v1/resources/${encodeURIComponent(resourceId)}/scopes/${encodeURIComponent(scopeId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `service_accounts` management namespace (CONTRACT §27.1).\n *\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `service_accounts` namespace handle.\n *\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ServiceAccountsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/service-accounts` */\n async list(page: PageRequest = {}): Promise<Page<models.ServiceAccountResponse>> {\n const wire = await sendManagement<Page<models.ServiceAccountResponse>>(this.#client, {\n operation: 'service_accounts.list',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts',\n path: '/api/v1/service-accounts',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `service_accounts.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.ServiceAccountResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/service-accounts`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateServiceAccountRequest): Promise<models.ServiceAccountCreatedResponse> {\n const wire = await sendManagement<models.ServiceAccountCreatedResponseWire>(this.#client, {\n operation: 'service_accounts.create',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts',\n path: '/api/v1/service-accounts',\n body: body,\n });\n return models.serviceAccountCreatedResponseFromWire(wire);\n }\n\n /** `GET /api/v1/service-accounts/{sa_id}` */\n async get(saId: string): Promise<models.ServiceAccountResponse> {\n const wire = await sendManagement<models.ServiceAccountResponse>(this.#client, {\n operation: 'service_accounts.get',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/service-accounts/{sa_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(saId: string, body: models.UpdateServiceAccount): Promise<models.ServiceAccountResponse> {\n const wire = await sendManagement<models.ServiceAccountResponse>(this.#client, {\n operation: 'service_accounts.update',\n method: 'PUT',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/service-accounts/{sa_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(saId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'service_accounts.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/service-accounts/{sa_id}',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}`,\n });\n }\n\n /**\n * `POST /api/v1/service-accounts/{sa_id}/rotate-secret`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async rotateSecret(saId: string): Promise<models.RotateSecretResponse> {\n const wire = await sendManagement<models.RotateSecretResponseWire>(this.#client, {\n operation: 'service_accounts.rotate_secret',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts/{sa_id}/rotate-secret',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}/rotate-secret`,\n });\n return models.rotateSecretResponseFromWire(wire);\n }\n\n /**\n * `POST /api/v1/service-accounts/{sa_id}/bind-certificate`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async bindCertificate(saId: string, body: models.BindCertificate): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'service_accounts.bind_certificate',\n method: 'POST',\n pathTemplate: '/api/v1/service-accounts/{sa_id}/bind-certificate',\n path: `/api/v1/service-accounts/${encodeURIComponent(saId)}/bind-certificate`,\n body: body,\n });\n }\n\n /** `GET /api/v1/service-accounts/{service_account_id}/roles` */\n async listRoles(serviceAccountId: string): Promise<models.RoleAssignment[]> {\n const wire = await sendManagement<models.RoleAssignment[]>(this.#client, {\n operation: 'service_accounts.list_roles',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{service_account_id}/roles',\n path: `/api/v1/service-accounts/${encodeURIComponent(serviceAccountId)}/roles`,\n });\n return wire;\n }\n\n /** `GET /api/v1/service-accounts/{service_account_id}/groups` */\n async listGroups(serviceAccountId: string): Promise<models.Group[]> {\n const wire = await sendManagement<models.Group[]>(this.#client, {\n operation: 'service_accounts.list_groups',\n method: 'GET',\n pathTemplate: '/api/v1/service-accounts/{service_account_id}/groups',\n path: `/api/v1/service-accounts/${encodeURIComponent(serviceAccountId)}/groups`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `certificates` management namespace (CONTRACT §27.1).\n *\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `certificates` namespace handle.\n *\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class CertificatesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/certificates` */\n async list(page: PageRequest = {}): Promise<Page<models.Certificate>> {\n const wire = await sendManagement<Page<models.Certificate>>(this.#client, {\n operation: 'certificates.list',\n method: 'GET',\n pathTemplate: '/api/v1/certificates',\n path: '/api/v1/certificates',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `certificates.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.Certificate[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/certificates`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreateCertificateRequest): Promise<models.GeneratedCertificate> {\n const wire = await sendManagement<models.GeneratedCertificateWire>(this.#client, {\n operation: 'certificates.generate',\n method: 'POST',\n pathTemplate: '/api/v1/certificates',\n path: '/api/v1/certificates',\n body: body,\n });\n return models.generatedCertificateFromWire(wire);\n }\n\n /** `GET /api/v1/certificates/{id}` */\n async get(id: string): Promise<models.Certificate> {\n const wire = await sendManagement<models.Certificate>(this.#client, {\n operation: 'certificates.get',\n method: 'GET',\n pathTemplate: '/api/v1/certificates/{id}',\n path: `/api/v1/certificates/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/certificates/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'certificates.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/certificates/{id}/revoke',\n path: `/api/v1/certificates/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `ca_certificates` management namespace (CONTRACT §27.1).\n *\n * Organization CAs and the per-tenant signing CAs chained beneath them.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `ca_certificates` namespace handle.\n *\n * Organization CAs and the per-tenant signing CAs chained beneath them.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class CaCertificatesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): CaCertificatesApi {\n return new CaCertificatesApi(this.#client, { ...this.#scope, orgId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/ca-certificates` */\n async list(page: PageRequest = {}): Promise<Page<models.CaCertificate>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.list\");\n const wire = await sendManagement<Page<models.CaCertificate>>(this.#client, {\n operation: 'ca_certificates.list',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates',\n path: `/api/v1/organizations/${orgId}/ca-certificates`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `ca_certificates.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.CaCertificate[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreateCaCertificateRequest): Promise<models.GeneratedCaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.generate\");\n const wire = await sendManagement<models.GeneratedCaCertificateWire>(this.#client, {\n operation: 'ca_certificates.generate',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates',\n path: `/api/v1/organizations/${orgId}/ca-certificates`,\n body: body,\n });\n return models.generatedCaCertificateFromWire(wire);\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/import`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async importCa(body: models.ImportCaCertificateRequest): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.import_ca\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.import_ca',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/import',\n path: `/api/v1/organizations/${orgId}/ca-certificates/import`,\n body: models.importCaCertificateRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/ca-certificates/{id}` */\n async get(id: string): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.get\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.get',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.revoke\");\n await sendManagement<void>(this.#client, {\n operation: 'ca_certificates.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/revoke',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/ca-certificates/{id}/migrate-custody`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async migrateCustody(id: string): Promise<models.MigrateCustodyResponse> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.migrate_custody\");\n const wire = await sendManagement<models.MigrateCustodyResponse>(this.#client, {\n operation: 'ca_certificates.migrate_custody',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/migrate-custody',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/migrate-custody`,\n });\n return wire;\n }\n\n /**\n * `PUT\n * /api/v1/organizations/{org_id}/ca-certificates/{id}/mtls-trust-anchor`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setMtlsTrustAnchor(id: string, body: models.SetMtlsTrustAnchor): Promise<models.MtlsTrustAnchorResponse> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.set_mtls_trust_anchor\");\n const wire = await sendManagement<models.MtlsTrustAnchorResponse>(this.#client, {\n operation: 'ca_certificates.set_mtls_trust_anchor',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/ca-certificates/{id}/mtls-trust-anchor',\n path: `/api/v1/organizations/${orgId}/ca-certificates/${encodeURIComponent(id)}/mtls-trust-anchor`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas` */\n async listSigningCas(tenantId: string, page: PageRequest = {}): Promise<Page<models.CaCertificate>> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.list_signing_cas\");\n const wire = await sendManagement<Page<models.CaCertificate>>(this.#client, {\n operation: 'ca_certificates.list_signing_cas',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas`,\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `ca_certificates.list_signing_cas` to exhaustion, concatenating every\n * page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listSigningCasAll(tenantId: string, start: PageRequest = {}): Promise<models.CaCertificate[]> {\n return collectPages(start, (p) => this.listSigningCas(tenantId, p));\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas`\n *\n * **Returns secret material, once.** `private_key_pem` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generateSigningCa(tenantId: string, body: models.CreateIntermediateCaRequest): Promise<models.GeneratedCaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.generate_signing_ca\");\n const wire = await sendManagement<models.GeneratedCaCertificateWire>(this.#client, {\n operation: 'ca_certificates.generate_signing_ca',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas`,\n body: body,\n });\n return models.generatedCaCertificateFromWire(wire);\n }\n\n /**\n * `POST\n * /api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas/sign-csr`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async signSigningCaCsr(tenantId: string, body: models.SignIntermediateCsrRequest): Promise<models.CaCertificate> {\n const orgId = resolveOrg(this.#client, this.#scope, \"ca_certificates.sign_signing_ca_csr\");\n const wire = await sendManagement<models.CaCertificate>(this.#client, {\n operation: 'ca_certificates.sign_signing_ca_csr',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/tenants/{tenant_id}/signing-cas/sign-csr',\n path: `/api/v1/organizations/${orgId}/tenants/${encodeURIComponent(tenantId)}/signing-cas/sign-csr`,\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `pgp_keys` management namespace (CONTRACT §27.1).\n *\n * OpenPGP keys used for audit signing and encrypted data export.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `pgp_keys` namespace handle.\n *\n * OpenPGP keys used for audit signing and encrypted data export.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PgpKeysApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/pgp-keys` */\n async list(page: PageRequest = {}): Promise<Page<models.PgpKey>> {\n const wire = await sendManagement<Page<models.PgpKey>>(this.#client, {\n operation: 'pgp_keys.list',\n method: 'GET',\n pathTemplate: '/api/v1/pgp-keys',\n path: '/api/v1/pgp-keys',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `pgp_keys.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.PgpKey[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/pgp-keys`\n *\n * **Returns secret material, once.** `private_key_armored` is returned by\n * this call and by no other; no later `get` will return it again, and the\n * `get` projection has no field where it was. Discarding the result destroys\n * the credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async generate(body: models.CreatePgpKeyRequest): Promise<models.GeneratedPgpKey> {\n const wire = await sendManagement<models.GeneratedPgpKeyWire>(this.#client, {\n operation: 'pgp_keys.generate',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys',\n path: '/api/v1/pgp-keys',\n body: body,\n });\n return models.generatedPgpKeyFromWire(wire);\n }\n\n /** `GET /api/v1/pgp-keys/{id}` */\n async get(id: string): Promise<models.PgpKey> {\n const wire = await sendManagement<models.PgpKey>(this.#client, {\n operation: 'pgp_keys.get',\n method: 'GET',\n pathTemplate: '/api/v1/pgp-keys/{id}',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/pgp-keys/{id}/revoke`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'pgp_keys.revoke',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/{id}/revoke',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}/revoke`,\n });\n }\n\n /**\n * `POST /api/v1/pgp-keys/{id}/encrypt`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async encrypt(id: string, body: models.EncryptRequest): Promise<models.EncryptedExport> {\n const wire = await sendManagement<models.EncryptedExport>(this.#client, {\n operation: 'pgp_keys.encrypt',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/{id}/encrypt',\n path: `/api/v1/pgp-keys/${encodeURIComponent(id)}/encrypt`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/pgp-keys/sign-audit-batch`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async signAuditBatch(body: models.SignAuditBatchRequest): Promise<models.SignedAuditBatch> {\n const wire = await sendManagement<models.SignedAuditBatch>(this.#client, {\n operation: 'pgp_keys.sign_audit_batch',\n method: 'POST',\n pathTemplate: '/api/v1/pgp-keys/sign-audit-batch',\n path: '/api/v1/pgp-keys/sign-audit-batch',\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `webhooks` management namespace (CONTRACT §27.1).\n *\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `webhooks` namespace handle.\n *\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class WebhooksApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/webhooks` */\n async list(page: PageRequest = {}): Promise<Page<models.WebhookResponse>> {\n const wire = await sendManagement<Page<models.WebhookResponse>>(this.#client, {\n operation: 'webhooks.list',\n method: 'GET',\n pathTemplate: '/api/v1/webhooks',\n path: '/api/v1/webhooks',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `webhooks.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.WebhookResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/webhooks`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateWebhookRequest): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.create',\n method: 'POST',\n pathTemplate: '/api/v1/webhooks',\n path: '/api/v1/webhooks',\n body: models.createWebhookRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/webhooks/{id}` */\n async get(id: string): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.get',\n method: 'GET',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/webhooks/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateWebhookRequest): Promise<models.WebhookResponse> {\n const wire = await sendManagement<models.WebhookResponse>(this.#client, {\n operation: 'webhooks.update',\n method: 'PUT',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n body: models.updateWebhookRequestToWire(body),\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/webhooks/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'webhooks.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/webhooks/{id}',\n path: `/api/v1/webhooks/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `oauth2_clients` management namespace (CONTRACT §27.1).\n *\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `oauth2_clients` namespace handle.\n *\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class Oauth2ClientsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/oauth2-clients` */\n async list(page: PageRequest = {}): Promise<Page<models.OAuth2ClientResponse>> {\n const wire = await sendManagement<Page<models.OAuth2ClientResponse>>(this.#client, {\n operation: 'oauth2_clients.list',\n method: 'GET',\n pathTemplate: '/api/v1/oauth2-clients',\n path: '/api/v1/oauth2-clients',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `oauth2_clients.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.OAuth2ClientResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/oauth2-clients`\n *\n * **Returns secret material, once.** `client_secret` is returned by this\n * call and by no other; no later `get` will return it again, and the `get`\n * projection has no field where it was. Discarding the result destroys the\n * credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateOAuth2ClientRequest): Promise<models.OAuth2ClientCreatedResponse> {\n const wire = await sendManagement<models.OAuth2ClientCreatedResponseWire>(this.#client, {\n operation: 'oauth2_clients.create',\n method: 'POST',\n pathTemplate: '/api/v1/oauth2-clients',\n path: '/api/v1/oauth2-clients',\n body: body,\n });\n return models.oAuth2ClientCreatedResponseFromWire(wire);\n }\n\n /** `GET /api/v1/oauth2-clients/{id}` */\n async get(id: string): Promise<models.OAuth2ClientResponse> {\n const wire = await sendManagement<models.OAuth2ClientResponse>(this.#client, {\n operation: 'oauth2_clients.get',\n method: 'GET',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/oauth2-clients/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateOAuth2ClientRequest): Promise<models.OAuth2ClientResponse> {\n const wire = await sendManagement<models.OAuth2ClientResponse>(this.#client, {\n operation: 'oauth2_clients.update',\n method: 'PUT',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/oauth2-clients/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'oauth2_clients.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/oauth2-clients/{id}',\n path: `/api/v1/oauth2-clients/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `federation` management namespace (CONTRACT §27.1).\n *\n * Upstream IdP configuration and the per-user links it produces.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `federation` namespace handle.\n *\n * Upstream IdP configuration and the per-user links it produces.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class FederationApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/federation-configs` */\n async listConfigs(page: PageRequest = {}): Promise<Page<models.FederationConfigResponse>> {\n const wire = await sendManagement<Page<models.FederationConfigResponse>>(this.#client, {\n operation: 'federation.list_configs',\n method: 'GET',\n pathTemplate: '/api/v1/federation-configs',\n path: '/api/v1/federation-configs',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `federation.list_configs` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listConfigsAll(start: PageRequest = {}): Promise<models.FederationConfigResponse[]> {\n return collectPages(start, (p) => this.listConfigs(p));\n }\n\n /**\n * `POST /api/v1/federation-configs`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async createConfig(body: models.CreateFederationConfigRequest): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.create_config',\n method: 'POST',\n pathTemplate: '/api/v1/federation-configs',\n path: '/api/v1/federation-configs',\n body: models.createFederationConfigRequestToWire(body),\n });\n return wire;\n }\n\n /** `GET /api/v1/federation-configs/{id}` */\n async getConfig(id: string): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.get_config',\n method: 'GET',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/federation-configs/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async updateConfig(id: string, body: models.UpdateFederationConfigRequest): Promise<models.FederationConfigResponse> {\n const wire = await sendManagement<models.FederationConfigResponse>(this.#client, {\n operation: 'federation.update_config',\n method: 'PUT',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n body: models.updateFederationConfigRequestToWire(body),\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/federation-configs/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteConfig(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'federation.delete_config',\n method: 'DELETE',\n pathTemplate: '/api/v1/federation-configs/{id}',\n path: `/api/v1/federation-configs/${encodeURIComponent(id)}`,\n });\n }\n\n /** `GET /api/v1/federation-links/user/{user_id}` */\n async listUserLinks(userId: string): Promise<models.FederationLinkResponse[]> {\n const wire = await sendManagement<models.FederationLinkResponse[]>(this.#client, {\n operation: 'federation.list_user_links',\n method: 'GET',\n pathTemplate: '/api/v1/federation-links/user/{user_id}',\n path: `/api/v1/federation-links/user/${encodeURIComponent(userId)}`,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/federation-links/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteLink(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'federation.delete_link',\n method: 'DELETE',\n pathTemplate: '/api/v1/federation-links/{id}',\n path: `/api/v1/federation-links/${encodeURIComponent(id)}`,\n });\n }\n\n /**\n * `POST /api/v1/federation/oidc/authorize`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async oidcAuthorize(body: models.OidcAuthorizeRequest): Promise<models.OidcAuthorizeResponse> {\n const wire = await sendManagement<models.OidcAuthorizeResponse>(this.#client, {\n operation: 'federation.oidc_authorize',\n method: 'POST',\n pathTemplate: '/api/v1/federation/oidc/authorize',\n path: '/api/v1/federation/oidc/authorize',\n body: body,\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/federation/oidc/callback`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async oidcCallback(body: models.OidcCallbackRequest): Promise<models.OidcCallbackResponse> {\n const wire = await sendManagement<models.OidcCallbackResponse>(this.#client, {\n operation: 'federation.oidc_callback',\n method: 'POST',\n pathTemplate: '/api/v1/federation/oidc/callback',\n path: '/api/v1/federation/oidc/callback',\n body: body,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `notification_rules` management namespace (CONTRACT §27.1).\n *\n * Which events raise a notification, and to whom.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `notification_rules` namespace handle.\n *\n * Which events raise a notification, and to whom.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class NotificationRulesApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/notification-rules` */\n async list(page: PageRequest = {}): Promise<Page<models.NotificationRuleResponse>> {\n const wire = await sendManagement<Page<models.NotificationRuleResponse>>(this.#client, {\n operation: 'notification_rules.list',\n method: 'GET',\n pathTemplate: '/api/v1/notification-rules',\n path: '/api/v1/notification-rules',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `notification_rules.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.NotificationRuleResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/notification-rules`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateNotificationRuleRequest): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.create',\n method: 'POST',\n pathTemplate: '/api/v1/notification-rules',\n path: '/api/v1/notification-rules',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/notification-rules/{id}` */\n async get(id: string): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.get',\n method: 'GET',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/notification-rules/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateNotificationRuleRequest): Promise<models.NotificationRuleResponse> {\n const wire = await sendManagement<models.NotificationRuleResponse>(this.#client, {\n operation: 'notification_rules.update',\n method: 'PUT',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/notification-rules/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'notification_rules.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/notification-rules/{id}',\n path: `/api/v1/notification-rules/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `email_config` management namespace (CONTRACT §27.1).\n *\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `email_config` namespace handle.\n *\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class EmailConfigApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): EmailConfigApi {\n return new EmailConfigApi(this.#client, { ...this.#scope, orgId });\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): EmailConfigApi {\n return new EmailConfigApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/email-config` */\n async getOrg(): Promise<models.EmailConfig> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.get_org\");\n const wire = await sendManagement<models.EmailConfig>(this.#client, {\n operation: 'email_config.get_org',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/email-config`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setOrg(body: models.SetOrgEmailConfig): Promise<models.EmailConfig> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.set_org\");\n const wire = await sendManagement<models.EmailConfig>(this.#client, {\n operation: 'email_config.set_org',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/organizations/{org_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteOrg(): Promise<void> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.delete_org\");\n await sendManagement<void>(this.#client, {\n operation: 'email_config.delete_org',\n method: 'DELETE',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config',\n path: `/api/v1/organizations/${orgId}/email-config`,\n });\n }\n\n /**\n * `POST /api/v1/organizations/{org_id}/email-config/test`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async testOrg(): Promise<models.EmailTestResult> {\n const orgId = resolveOrg(this.#client, this.#scope, \"email_config.test_org\");\n const wire = await sendManagement<models.EmailTestResult>(this.#client, {\n operation: 'email_config.test_org',\n method: 'POST',\n pathTemplate: '/api/v1/organizations/{org_id}/email-config/test',\n path: `/api/v1/organizations/${orgId}/email-config/test`,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/email-config` */\n async getTenant(): Promise<models.EmailConfigOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.get_tenant\");\n const wire = await sendManagement<models.EmailConfigOverride>(this.#client, {\n operation: 'email_config.get_tenant',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setTenant(body: models.EmailConfigOverride): Promise<models.EmailConfigOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.set_tenant\");\n const wire = await sendManagement<models.EmailConfigOverride>(this.#client, {\n operation: 'email_config.set_tenant',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/tenants/{tenant_id}/email-config`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteTenant(): Promise<void> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.delete_tenant\");\n await sendManagement<void>(this.#client, {\n operation: 'email_config.delete_tenant',\n method: 'DELETE',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config',\n path: `/api/v1/tenants/${tenantId}/email-config`,\n });\n }\n\n /**\n * `POST /api/v1/tenants/{tenant_id}/email-config/test`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async testTenant(): Promise<models.EmailTestResult> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"email_config.test_tenant\");\n const wire = await sendManagement<models.EmailTestResult>(this.#client, {\n operation: 'email_config.test_tenant',\n method: 'POST',\n pathTemplate: '/api/v1/tenants/{tenant_id}/email-config/test',\n path: `/api/v1/tenants/${tenantId}/email-config/test`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `settings` management namespace (CONTRACT §27.1).\n *\n * Effective settings, and the organization/tenant layers they resolve from.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `settings` namespace handle.\n *\n * Effective settings, and the organization/tenant layers they resolve from.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class SettingsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different organization than the client's own.\n *\n * §27.4 rule 3: the client's `orgId` is the default, and a platform-admin\n * token legitimately overrides it. Returns a new handle; the original is\n * unchanged.\n */\n inOrg(orgId: string): SettingsApi {\n return new SettingsApi(this.#client, { ...this.#scope, orgId });\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): SettingsApi {\n return new SettingsApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/organizations/{org_id}/settings` */\n async getOrg(): Promise<models.SecuritySettings> {\n const orgId = resolveOrg(this.#client, this.#scope, \"settings.get_org\");\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.get_org',\n method: 'GET',\n pathTemplate: '/api/v1/organizations/{org_id}/settings',\n path: `/api/v1/organizations/${orgId}/settings`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/organizations/{org_id}/settings`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setOrg(body: models.SetOrgSettings): Promise<models.SecuritySettings> {\n const orgId = resolveOrg(this.#client, this.#scope, \"settings.set_org\");\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.set_org',\n method: 'PUT',\n pathTemplate: '/api/v1/organizations/{org_id}/settings',\n path: `/api/v1/organizations/${orgId}/settings`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/settings` */\n async getEffective(): Promise<models.SecuritySettings> {\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.get_effective',\n method: 'GET',\n pathTemplate: '/api/v1/settings',\n path: '/api/v1/settings',\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setEffective(body: models.TenantSettingsOverride): Promise<models.SecuritySettings> {\n const wire = await sendManagement<models.SecuritySettings>(this.#client, {\n operation: 'settings.set_effective',\n method: 'PUT',\n pathTemplate: '/api/v1/settings',\n path: '/api/v1/settings',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/settings` */\n async getTenantOverride(): Promise<models.TenantSettingsOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.get_tenant_override\");\n const wire = await sendManagement<models.TenantSettingsOverride>(this.#client, {\n operation: 'settings.get_tenant_override',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async setTenantOverride(body: models.TenantSettingsOverride): Promise<models.TenantSettingsOverride> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.set_tenant_override\");\n const wire = await sendManagement<models.TenantSettingsOverride>(this.#client, {\n operation: 'settings.set_tenant_override',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/tenants/{tenant_id}/settings`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async deleteTenantOverride(): Promise<void> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"settings.delete_tenant_override\");\n await sendManagement<void>(this.#client, {\n operation: 'settings.delete_tenant_override',\n method: 'DELETE',\n pathTemplate: '/api/v1/tenants/{tenant_id}/settings',\n path: `/api/v1/tenants/${tenantId}/settings`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `scim_tokens` management namespace (CONTRACT §27.1).\n *\n * Bearer tokens for the SCIM 2.0 provisioning endpoint.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `scim_tokens` namespace handle.\n *\n * Bearer tokens for the SCIM 2.0 provisioning endpoint.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ScimTokensApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/scim-tokens` */\n async list(): Promise<models.ScimTokenResponse[]> {\n const wire = await sendManagement<models.ScimTokenResponse[]>(this.#client, {\n operation: 'scim_tokens.list',\n method: 'GET',\n pathTemplate: '/api/v1/scim-tokens',\n path: '/api/v1/scim-tokens',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/scim-tokens`\n *\n * **Returns secret material, once.** `provisioning_token` is returned by\n * this call and by no other; no later `get` will return it again, and the\n * `get` projection has no field where it was. Discarding the result destroys\n * the credential (§27.5 rule 3).\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateScimTokenRequest): Promise<models.CreateScimTokenResponse> {\n const wire = await sendManagement<models.CreateScimTokenResponseWire>(this.#client, {\n operation: 'scim_tokens.create',\n method: 'POST',\n pathTemplate: '/api/v1/scim-tokens',\n path: '/api/v1/scim-tokens',\n body: body,\n });\n return models.createScimTokenResponseFromWire(wire);\n }\n\n /**\n * `DELETE /api/v1/scim-tokens/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async revoke(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'scim_tokens.revoke',\n method: 'DELETE',\n pathTemplate: '/api/v1/scim-tokens/{id}',\n path: `/api/v1/scim-tokens/${encodeURIComponent(id)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `reactors` management namespace (CONTRACT §27.1).\n *\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `reactors` namespace handle.\n *\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class ReactorsApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/reactors` */\n async list(page: PageRequest = {}): Promise<Page<models.ReactorResponse>> {\n const wire = await sendManagement<Page<models.ReactorResponse>>(this.#client, {\n operation: 'reactors.list',\n method: 'GET',\n pathTemplate: '/api/v1/reactors',\n path: '/api/v1/reactors',\n query: { ...pageQuery(page) },\n });\n return wire;\n }\n\n /**\n * Walk `reactors.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(start: PageRequest = {}): Promise<models.ReactorResponse[]> {\n return collectPages(start, (p) => this.list(p));\n }\n\n /**\n * `POST /api/v1/reactors`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async create(body: models.CreateReactorRequest): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.create',\n method: 'POST',\n pathTemplate: '/api/v1/reactors',\n path: '/api/v1/reactors',\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/reactors/{id}` */\n async get(id: string): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.get',\n method: 'GET',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/reactors/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async update(id: string, body: models.UpdateReactorRequest): Promise<models.ReactorResponse> {\n const wire = await sendManagement<models.ReactorResponse>(this.#client, {\n operation: 'reactors.update',\n method: 'PUT',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n body: body,\n });\n return wire;\n }\n\n /**\n * `DELETE /api/v1/reactors/{id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async delete(id: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'reactors.delete',\n method: 'DELETE',\n pathTemplate: '/api/v1/reactors/{id}',\n path: `/api/v1/reactors/${encodeURIComponent(id)}`,\n });\n }\n\n /** `GET /api/v1/reactors/events` */\n async listEvents(): Promise<models.ReactorEventDescriptor[]> {\n const wire = await sendManagement<models.ReactorEventDescriptor[]>(this.#client, {\n operation: 'reactors.list_events',\n method: 'GET',\n pathTemplate: '/api/v1/reactors/events',\n path: '/api/v1/reactors/events',\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `webauthn_policy` management namespace (CONTRACT §27.1).\n *\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\nimport { resolveOrg, resolveTenant } from '../scope.js';\n\n/**\n * The `webauthn_policy` namespace handle.\n *\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class WebauthnPolicyApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * Address a different tenant than the client's own (§27.4 rule 3).\n *\n * Returns a new handle; the original is unchanged.\n */\n forTenant(tenantId: string): WebauthnPolicyApi {\n return new WebauthnPolicyApi(this.#client, { ...this.#scope, tenantId });\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/webauthn/attestation-policy` */\n async get(): Promise<models.PolicyResponse> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.get\");\n const wire = await sendManagement<models.PolicyResponse>(this.#client, {\n operation: 'webauthn_policy.get',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/attestation-policy',\n path: `/api/v1/tenants/${tenantId}/webauthn/attestation-policy`,\n });\n return wire;\n }\n\n /**\n * `PUT /api/v1/tenants/{tenant_id}/webauthn/attestation-policy`\n *\n * **This is a replacement, not a patch** (§27.4 rule 5). Every field of the\n * body is required, and what you do not carry over from a prior read is not\n * preserved — it is overwritten. Read first, change the field you mean, send\n * the whole thing back.\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async set(body: models.WebauthnAttestationPolicy): Promise<models.WebauthnAttestationPolicy> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.set\");\n const wire = await sendManagement<models.WebauthnAttestationPolicy>(this.#client, {\n operation: 'webauthn_policy.set',\n method: 'PUT',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/attestation-policy',\n path: `/api/v1/tenants/${tenantId}/webauthn/attestation-policy`,\n body: body,\n });\n return wire;\n }\n\n /** `GET /api/v1/tenants/{tenant_id}/webauthn/compliance-report` */\n async complianceReport(): Promise<models.ComplianceReportEntry[]> {\n const tenantId = resolveTenant(this.#client, this.#scope, \"webauthn_policy.compliance_report\");\n const wire = await sendManagement<models.ComplianceReportEntry[]>(this.#client, {\n operation: 'webauthn_policy.compliance_report',\n method: 'GET',\n pathTemplate: '/api/v1/tenants/{tenant_id}/webauthn/compliance-report',\n path: `/api/v1/tenants/${tenantId}/webauthn/compliance-report`,\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `audit` management namespace (CONTRACT §27.1).\n *\n * Append-only audit log, read-only by construction.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport type { Page, PageRequest } from '../page.js';\nimport { collectPages, pageQuery } from '../page.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * Optional filters for `audit.list`.\n *\n * Six loose optional arguments is a call site a reader cannot check and a\n * refactor silently reorders, so they travel as one object.\n */\nexport interface AuditListFilter {\n /** Filter on `actor_id`. */\n actorId?: string;\n /** Filter on `action`. */\n action?: string;\n /** Filter on `outcome`. */\n outcome?: string;\n /** Filter on `resource_id`. */\n resourceId?: string;\n /** Filter on `from`. */\n from?: string;\n /** Filter on `to`. */\n to?: string;\n}\n\n/**\n * Optional filters for `audit.list_system`.\n *\n * Six loose optional arguments is a call site a reader cannot check and a\n * refactor silently reorders, so they travel as one object.\n */\nexport interface AuditListSystemFilter {\n /** Filter on `actor_id`. */\n actorId?: string;\n /** Filter on `action`. */\n action?: string;\n /** Filter on `outcome`. */\n outcome?: string;\n /** Filter on `resource_id`. */\n resourceId?: string;\n /** Filter on `from`. */\n from?: string;\n /** Filter on `to`. */\n to?: string;\n}\n\n/**\n * The `audit` namespace handle.\n *\n * Append-only audit log, read-only by construction.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class AuditApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /api/v1/audit-logs` */\n async list(filter: AuditListFilter = {}, page: PageRequest = {}): Promise<Page<models.AuditLogEntry>> {\n const wire = await sendManagement<Page<models.AuditLogEntry>>(this.#client, {\n operation: 'audit.list',\n method: 'GET',\n pathTemplate: '/api/v1/audit-logs',\n path: '/api/v1/audit-logs',\n query: { ...pageQuery(page), 'actor_id': filter.actorId, 'action': filter.action, 'outcome': filter.outcome, 'resource_id': filter.resourceId, 'from': filter.from, 'to': filter.to },\n });\n return wire;\n }\n\n /**\n * Walk `audit.list` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listAll(filter: AuditListFilter = {}, start: PageRequest = {}): Promise<models.AuditLogEntry[]> {\n return collectPages(start, (p) => this.list(filter, p));\n }\n\n /** `GET /api/v1/audit-logs/system` */\n async listSystem(filter: AuditListSystemFilter = {}, page: PageRequest = {}): Promise<Page<models.AuditLogEntry>> {\n const wire = await sendManagement<Page<models.AuditLogEntry>>(this.#client, {\n operation: 'audit.list_system',\n method: 'GET',\n pathTemplate: '/api/v1/audit-logs/system',\n path: '/api/v1/audit-logs/system',\n query: { ...pageQuery(page), 'actor_id': filter.actorId, 'action': filter.action, 'outcome': filter.outcome, 'resource_id': filter.resourceId, 'from': filter.from, 'to': filter.to },\n });\n return wire;\n }\n\n /**\n * Walk `audit.list_system` to exhaustion, concatenating every page.\n *\n * The auto-paging form §27.4 rule 4 requires. It stops on an empty page even\n * if `total` disagrees, so a misreporting server costs one wasted request\n * rather than an unbounded loop.\n */\n listSystemAll(filter: AuditListSystemFilter = {}, start: PageRequest = {}): Promise<models.AuditLogEntry[]> {\n return collectPages(start, (p) => this.listSystem(filter, p));\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `privacy` management namespace (CONTRACT §27.1).\n *\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `privacy` namespace handle.\n *\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PrivacyApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /**\n * `POST /api/v1/account/export`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async requestExport(body: unknown): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.request_export',\n method: 'POST',\n pathTemplate: '/api/v1/account/export',\n path: '/api/v1/account/export',\n body: body,\n });\n }\n\n /** `GET /api/v1/account/export/{token}` */\n async downloadExport(token: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.download_export',\n method: 'GET',\n pathTemplate: '/api/v1/account/export/{token}',\n path: `/api/v1/account/export/${encodeURIComponent(token)}`,\n });\n }\n\n /**\n * `POST /api/v1/account/delete`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async requestDelete(body: unknown): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.request_delete',\n method: 'POST',\n pathTemplate: '/api/v1/account/delete',\n path: '/api/v1/account/delete',\n body: body,\n });\n }\n\n /** `GET /api/v1/auth/account/delete/cancel` */\n async cancelDelete(token: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.cancel_delete',\n method: 'GET',\n pathTemplate: '/api/v1/auth/account/delete/cancel',\n path: '/api/v1/auth/account/delete/cancel',\n query: { \"token\": token },\n });\n }\n\n /** `GET /api/v1/account/consents` */\n async listConsents(): Promise<models.ConsentView[]> {\n const wire = await sendManagement<models.ConsentView[]>(this.#client, {\n operation: 'privacy.list_consents',\n method: 'GET',\n pathTemplate: '/api/v1/account/consents',\n path: '/api/v1/account/consents',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/account/consents/oidc-scopes`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async grantScopeConsent(body: models.GrantScopeConsent): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.grant_scope_consent',\n method: 'POST',\n pathTemplate: '/api/v1/account/consents/oidc-scopes',\n path: '/api/v1/account/consents/oidc-scopes',\n body: body,\n });\n }\n\n /**\n * `DELETE /api/v1/account/consents/oidc-scopes/{client_id}`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async withdrawScopeConsent(clientId: string): Promise<void> {\n await sendManagement<void>(this.#client, {\n operation: 'privacy.withdraw_scope_consent',\n method: 'DELETE',\n pathTemplate: '/api/v1/account/consents/oidc-scopes/{client_id}',\n path: `/api/v1/account/consents/oidc-scopes/${encodeURIComponent(clientId)}`,\n });\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * The `platform` management namespace (CONTRACT §27.1).\n *\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n */\n\nimport type { AxiamClient } from '../../rest/client.js';\nimport * as models from '../models.js';\nimport { sendManagement } from '../request.js';\nimport type { NamespaceScope } from '../scope.js';\n\n/**\n * The `platform` namespace handle.\n *\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n *\n * Acquiring one performs no I/O and allocates nothing meaningful (§27.2 rule\n * 1); it holds the client and cannot be constructed without one.\n */\nexport class PlatformApi {\n readonly #client: AxiamClient;\n readonly #scope: NamespaceScope;\n\n /** @internal — reached through `client.<namespace>`, never constructed directly. */\n constructor(client: AxiamClient, scope: NamespaceScope = {}) {\n this.#client = client;\n this.#scope = scope;\n }\n\n /** `GET /health` */\n async health(): Promise<models.HealthResponse> {\n const wire = await sendManagement<models.HealthResponse>(this.#client, {\n operation: 'platform.health',\n method: 'GET',\n pathTemplate: '/health',\n path: '/health',\n });\n return wire;\n }\n\n /** `GET /ready` */\n async ready(): Promise<models.ReadyResponse> {\n const wire = await sendManagement<models.ReadyResponse>(this.#client, {\n operation: 'platform.ready',\n method: 'GET',\n pathTemplate: '/ready',\n path: '/ready',\n });\n return wire;\n }\n\n /** `GET /api/v1/mds/status` */\n async mdsStatus(): Promise<models.MdsStatusResponse> {\n const wire = await sendManagement<models.MdsStatusResponse>(this.#client, {\n operation: 'platform.mds_status',\n method: 'GET',\n pathTemplate: '/api/v1/mds/status',\n path: '/api/v1/mds/status',\n });\n return wire;\n }\n\n /**\n * `POST /api/v1/mds/refresh`\n *\n * Not retried on failure (§27.4 rule 8): every write on this surface is\n * issued exactly once, including the ones that look idempotent.\n */\n async mdsRefresh(): Promise<models.MdsRefreshOutcome> {\n const wire = await sendManagement<models.MdsRefreshOutcome>(this.#client, {\n operation: 'platform.mds_refresh',\n method: 'POST',\n pathTemplate: '/api/v1/mds/refresh',\n path: '/api/v1/mds/refresh',\n });\n return wire;\n }\n\n}\n","// @generated by scripts/gen-management.mjs from management-registry.json and\n// openapi.json. DO NOT EDIT — your changes will be overwritten. Regenerate with\n// `node scripts/gen-management.mjs`; CI verifies the committed output is current.\n\n/**\n * One handle per §27 namespace, and the accessors that reach them.\n *\n * §27.2 makes this namespacing normative rather than stylistic: twenty\n * namespaces have a `list` and fourteen a `get`, so flattening 147 operations\n * onto the client would need a disambiguating prefix invented once per\n * operation — and would bury the eight §1 methods most callers actually want\n * under five times as many they do not.\n */\n\nexport * from './organizations.js';\nexport * from './tenants.js';\nexport * from './users.js';\nexport * from './groups.js';\nexport * from './roles.js';\nexport * from './permissions.js';\nexport * from './resources.js';\nexport * from './scopes.js';\nexport * from './service_accounts.js';\nexport * from './certificates.js';\nexport * from './ca_certificates.js';\nexport * from './pgp_keys.js';\nexport * from './webhooks.js';\nexport * from './oauth2_clients.js';\nexport * from './federation.js';\nexport * from './notification_rules.js';\nexport * from './email_config.js';\nexport * from './settings.js';\nexport * from './scim_tokens.js';\nexport * from './reactors.js';\nexport * from './webauthn_policy.js';\nexport * from './audit.js';\nexport * from './privacy.js';\nexport * from './platform.js';\n\nimport { OrganizationsApi } from './organizations.js';\nimport { TenantsApi } from './tenants.js';\nimport { UsersApi } from './users.js';\nimport { GroupsApi } from './groups.js';\nimport { RolesApi } from './roles.js';\nimport { PermissionsApi } from './permissions.js';\nimport { ResourcesApi } from './resources.js';\nimport { ScopesApi } from './scopes.js';\nimport { ServiceAccountsApi } from './service_accounts.js';\nimport { CertificatesApi } from './certificates.js';\nimport { CaCertificatesApi } from './ca_certificates.js';\nimport { PgpKeysApi } from './pgp_keys.js';\nimport { WebhooksApi } from './webhooks.js';\nimport { Oauth2ClientsApi } from './oauth2_clients.js';\nimport { FederationApi } from './federation.js';\nimport { NotificationRulesApi } from './notification_rules.js';\nimport { EmailConfigApi } from './email_config.js';\nimport { SettingsApi } from './settings.js';\nimport { ScimTokensApi } from './scim_tokens.js';\nimport { ReactorsApi } from './reactors.js';\nimport { WebauthnPolicyApi } from './webauthn_policy.js';\nimport { AuditApi } from './audit.js';\nimport { PrivacyApi } from './privacy.js';\nimport { PlatformApi } from './platform.js';\nimport type { AxiamClient } from '../../rest/client.js';\n\n/** Every §27 namespace handle, lazily constructed per access. */\nexport interface ManagementNamespaces {\n /**\n * Organizations an SDK client may read and configure. Creation and deletion\n * are outside the SDK boundary (§27.0).\n */\n readonly organizations: OrganizationsApi;\n /**\n * Tenants within an organization -- the isolation boundary every other\n * namespace is scoped to.\n */\n readonly tenants: TenantsApi;\n /**\n * Users within the client's tenant, and the administrative side of their\n * second factor and lockout state.\n */\n readonly users: UsersApi;\n /**\n * Named collections of users. Roles assigned to a group are inherited by\n * every member.\n */\n readonly groups: GroupsApi;\n /** Roles, their permission sets, and their assignment to users and groups. */\n readonly roles: RolesApi;\n /** Permissions -- an action on a resource, optionally narrowed by a scope. */\n readonly permissions: PermissionsApi;\n /** The resource hierarchy role assignments cascade down. */\n readonly resources: ResourcesApi;\n /** Sub-resource granularity, always addressed under their resource. */\n readonly scopes: ScopesApi;\n /**\n * Machine identities, their secrets, and the certificate a device-bound one\n * authenticates with.\n */\n readonly serviceAccounts: ServiceAccountsApi;\n /**\n * End-entity X.509 certificates -- the ones issued to users, services and\n * IoT devices.\n */\n readonly certificates: CertificatesApi;\n /** Organization CAs and the per-tenant signing CAs chained beneath them. */\n readonly caCertificates: CaCertificatesApi;\n /** OpenPGP keys used for audit signing and encrypted data export. */\n readonly pgpKeys: PgpKeysApi;\n /**\n * Outbound event notifications. Delivery signatures are verified with the\n * §13 helper, which this namespace configures.\n */\n readonly webhooks: WebhooksApi;\n /**\n * Registered OAuth2/OIDC clients -- the registration half of what §12, §21\n * and §26 then speak to.\n */\n readonly oauth2Clients: Oauth2ClientsApi;\n /** Upstream IdP configuration and the per-user links it produces. */\n readonly federation: FederationApi;\n /** Which events raise a notification, and to whom. */\n readonly notificationRules: NotificationRulesApi;\n /**\n * Transactional-mail transport, configurable at organization level and\n * overridable per tenant.\n */\n readonly emailConfig: EmailConfigApi;\n /** Effective settings, and the organization/tenant layers they resolve from. */\n readonly settings: SettingsApi;\n /** Bearer tokens for the SCIM 2.0 provisioning endpoint. */\n readonly scimTokens: ScimTokensApi;\n /**\n * Registration of §22 AMQP extension actors -- the admin surface §22.9\n * describes, which no SDK could previously reach.\n */\n readonly reactors: ReactorsApi;\n /**\n * Per-tenant attestation policy governing the §24 ceremonies, and the\n * compliance report over it.\n */\n readonly webauthnPolicy: WebauthnPolicyApi;\n /** Append-only audit log, read-only by construction. */\n readonly audit: AuditApi;\n /**\n * GDPR self-service: the authenticated account's own export and erasure.\n * Scoped to the caller, never to another user.\n */\n readonly privacy: PrivacyApi;\n /**\n * Deployment-level probes and FIDO metadata state. Unauthenticated where the\n * server leaves them so.\n */\n readonly platform: PlatformApi;\n}\n\n/**\n * Build the namespace handles for `client`.\n *\n * @internal — reached as `client.users`, `client.roles`, and so on.\n */\nexport function managementNamespaces(client: AxiamClient): ManagementNamespaces {\n return {\n get organizations() {\n return new OrganizationsApi(client);\n },\n get tenants() {\n return new TenantsApi(client);\n },\n get users() {\n return new UsersApi(client);\n },\n get groups() {\n return new GroupsApi(client);\n },\n get roles() {\n return new RolesApi(client);\n },\n get permissions() {\n return new PermissionsApi(client);\n },\n get resources() {\n return new ResourcesApi(client);\n },\n get scopes() {\n return new ScopesApi(client);\n },\n get serviceAccounts() {\n return new ServiceAccountsApi(client);\n },\n get certificates() {\n return new CertificatesApi(client);\n },\n get caCertificates() {\n return new CaCertificatesApi(client);\n },\n get pgpKeys() {\n return new PgpKeysApi(client);\n },\n get webhooks() {\n return new WebhooksApi(client);\n },\n get oauth2Clients() {\n return new Oauth2ClientsApi(client);\n },\n get federation() {\n return new FederationApi(client);\n },\n get notificationRules() {\n return new NotificationRulesApi(client);\n },\n get emailConfig() {\n return new EmailConfigApi(client);\n },\n get settings() {\n return new SettingsApi(client);\n },\n get scimTokens() {\n return new ScimTokensApi(client);\n },\n get reactors() {\n return new ReactorsApi(client);\n },\n get webauthnPolicy() {\n return new WebauthnPolicyApi(client);\n },\n get audit() {\n return new AuditApi(client);\n },\n get privacy() {\n return new PrivacyApi(client);\n },\n get platform() {\n return new PlatformApi(client);\n },\n };\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 */\nimport { ManifestApi } from '../management/manifest/engine.js';\nimport type { ManagementNamespaces } from '../management/ops/index.js';\nimport { managementNamespaces } from '../management/ops/index.js';\n\n/**\n * The §27 management namespaces, merged onto the client.\n *\n * Declaration merging rather than 24 hand-written getters: the namespace set\n * is generated from `management-registry.json`, and a hand-maintained copy of\n * it on this class is the thing §27.8 exists to prevent.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface AxiamClient extends ManagementNamespaces {}\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 // §27.2 rule 1: acquiring a handle performs no I/O and is not meant to be\n // observable. Copying the *descriptors* keeps the generated getters lazy,\n // so constructing a client does not construct 24 namespace objects; a\n // plain `Object.assign` would invoke every getter here.\n Object.defineProperties(this, Object.getOwnPropertyDescriptors(managementNamespaces(this)));\n }\n\n /**\n * Declarative management — CONTRACT.md §27.6.\n *\n * `client.manifest.plan(m)` says what would change and writes nothing;\n * `client.manifest.apply(m)` reconciles.\n */\n get manifest(): ManifestApi {\n return new ManifestApi(this);\n }\n\n /**\n * Every §27 namespace behind one accessor (§27.2 rule 4).\n *\n * `client.management.users` and `client.users` are the same handle; this\n * exists for callers who prefer the management surface not to be mixed in\n * with §1's eight methods when reading a call site.\n */\n get management(): ManagementNamespaces {\n return managementNamespaces(this);\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), sealed against the tenant this client is **acting on**.\n * The server cannot build one — it never sees the plaintext.\n *\n * Right for creating **another** account (§27 `users.create`); for the\n * caller's *own* password change use {@link opaqueEnrollmentForSelf}, which\n * seals against the tenant the account lives in (§5.2.2 rule 2).\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 * Build an OPAQUE registration record for the **caller's own** new password,\n * sealed against the tenant the caller's account lives in (§5.2.2 rule 2).\n *\n * Identical to {@link opaqueEnrollment} for every ordinary principal — the\n * two tenants are the same value there. They diverge for an\n * organization-level principal that has selected another tenant to act on,\n * and a record sealed against the acting one is refused with *\"the OPAQUE\n * session was issued for a different tenant\"*.\n *\n * Requires a completed login: the principal tenant is reported by the login\n * response, so there is nothing to seal against before then.\n */\n opaqueEnrollmentForSelf(password: string): Promise<opaqueMethods.OpaqueEnrollment> {\n return opaqueMethods.opaqueEnrollmentForSelf(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 /**\n * `POST /api/v1/auth/resend-verification` (§25.1) — the unauthenticated\n * resend. Resolves whatever the outcome; use {@link resendOwnVerification}\n * when there is a session (§25.7).\n */\n resendVerification(email: string, tenantId: string): Promise<void> {\n return accountMethods.resendVerification(this, email, tenantId);\n }\n\n /**\n * `POST /api/v1/users/me/resend-verification` (§25.1, §25.7) — the\n * authenticated resend, which takes no address and reports what happened.\n */\n resendOwnVerification(): Promise<void> {\n return accountMethods.resendOwnVerification(this);\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","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/http';\nimport type { AxiosInstance } from 'axios';\nimport type { NodeTlsOptions } from '../rest/session.js';\n\n/** The `axiam_access` cookie name (httpOnly, path `/`). */\nexport const ACCESS_COOKIE = 'axiam_access';\n/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */\nexport const REFRESH_COOKIE = 'axiam_refresh';\n/** The `axiam_csrf` cookie name (JS-readable, path `/`). */\nexport const CSRF_COOKIE = 'axiam_csrf';\n\n/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */\nexport function createJar(): CookieJar {\n return new CookieJar();\n}\n\n/**\n * Attach jar-aware agents to an axios instance so the jar persists\n * `Set-Cookie` responses across requests and replays them on subsequent\n * requests to the same origin/path (§4). Mutates and returns the same\n * instance.\n *\n * The agents are constructed HERE rather than via `axios-cookiejar-support`'s\n * `wrapper()`, which used to do it. That wrapper is a thin convenience layer:\n * all cookie handling lives in `http-cookie-agent`'s agents, which it builds\n * for you inside a request interceptor — and that interceptor is hostile to\n * any other agent. It THROWS\n *\n * axios-cookiejar-support does not support for use with other http(s).Agent.\n *\n * when it finds an `httpsAgent` it did not create, and otherwise replaces it.\n * Since `createSession` attaches an `https.Agent` whenever `customCa` or a\n * §6.1 client certificate is configured, the Node persona could never use\n * either: with TLS material configured every request threw, and there was no\n * seam to pass CA/cert/key through the wrapper's own agent construction.\n *\n * Building the agent ourselves closes that: ONE `HttpsCookieAgent` that is\n * both jar-aware and TLS-configured. Cookie behaviour is unchanged — it is\n * the same agent class the wrapper was constructing, just with the TLS\n * options merged in.\n *\n * @param tls §6/§6.1 TLS material, or undefined for the default trust store.\n * Never carries `rejectUnauthorized`: strict server verification\n * is not negotiable (§6).\n */\nexport function wrapAxios(\n instance: AxiosInstance,\n jar: CookieJar,\n tls?: NodeTlsOptions,\n): AxiosInstance {\n // `http-cookie-agent`'s .d.ts resolves tough-cookie through the CJS\n // condition while this file resolves it through the ESM one, so TypeScript\n // sees two structurally identical CookieJar declarations with separate\n // private fields and refuses the assignment. It is the same class at\n // runtime (one tough-cookie install, one instance). Narrow the cast to the\n // jar itself rather than loosening either signature.\n type AgentCookieOptions = NonNullable<ConstructorParameters<typeof HttpCookieAgent>[0]['cookies']>;\n const cookies = { jar } as unknown as AgentCookieOptions;\n instance.defaults.httpAgent = new HttpCookieAgent({ cookies });\n instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...(tls ?? {}) });\n return instance;\n}\n\n/**\n * Read a single cookie's value out of the jar by name, for the given URL.\n * This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body\n * fallback exists on the wire).\n */\nexport async function extractCookieValue(\n jar: CookieJar,\n url: string,\n name: string,\n): Promise<string | undefined> {\n const cookies = await jar.getCookies(url);\n return cookies.find((c) => c.key === name)?.value;\n}\n","// TokenManager — Node-persona token state (CONTRACT.md §7, D-09/D-11/D-26).\n//\n// Tokens are read from the tough-cookie jar by name (the ONLY token-source\n// path — login/refresh response bodies carry no token fields; see\n// RESEARCH.md Area 3) and wrapped in Sensitive<T> immediately. A\n// synchronous, non-blocking `cachedAccessToken()` fast-path is provided for\n// the grpc-js interceptor's `start()`, which cannot await (Pitfall 3) —\n// mirrors the Rust SDK's src/token/manager.rs::cached_access_token exactly.\n\nimport type { CookieJar } from 'tough-cookie';\nimport { Sensitive } from '../core/index.js';\nimport { ACCESS_COOKIE, REFRESH_COOKIE, extractCookieValue } from './cookieJar.js';\n\n/** Path the server scopes the `axiam_refresh` cookie to (mirrors csrf.rs). */\nconst REFRESH_COOKIE_PATH = '/api/v1/auth/refresh';\n\n/** Tracks the access/refresh token pair for a Node session, kept in sync with the cookie jar after each REST call/refresh. */\nexport class TokenManager {\n readonly #jar: CookieJar;\n readonly #baseUrl: string;\n #tenantId: string | undefined;\n /**\n * Non-blocking cached copy of the current access token, kept in sync via\n * `syncFromJar()` after each REST call/refresh. Read via\n * `cachedAccessToken()` without ever touching the jar's async API — this\n * is the fast-path the grpc-js interceptor's synchronous `start()` needs\n * (Pitfall 3).\n */\n #cachedAccess: Sensitive<string> | null = null;\n\n constructor(jar: CookieJar, baseUrl: string, tenantId?: string) {\n this.#jar = jar;\n this.#baseUrl = baseUrl;\n this.#tenantId = tenantId;\n }\n\n /**\n * Synchronous, best-effort read of the last-known access token. Returns\n * `null` if no token has been cached yet (no request/refresh has\n * completed since construction, or `syncFromJar()` was never called).\n */\n cachedAccessToken(): Sensitive<string> | null {\n return this.#cachedAccess;\n }\n\n /**\n * Async read of the current `axiam_refresh` cookie value from the jar,\n * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL\n * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible\n * at the bare base URL).\n */\n async refreshTokenValue(): Promise<Sensitive<string> | null> {\n const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);\n return value === undefined ? null : new Sensitive(value);\n }\n\n /**\n * Refresh the in-memory cached access token from the jar. Call this after\n * every REST request/refresh so the synchronous gRPC-interceptor fast-path\n * (`cachedAccessToken()`) stays current (Pitfall 3).\n */\n async syncFromJar(): Promise<void> {\n const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);\n this.#cachedAccess = value === undefined ? null : new Sensitive(value);\n }\n\n /** The resolved tenant identifier (slug or UUID form), if known. */\n tenantId(): string | undefined {\n return this.#tenantId;\n }\n\n /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */\n setTenantId(tenantId: string): void {\n this.#tenantId = tenantId;\n }\n\n /**\n * Best-effort decode of the `tenant_id`/`org_id` claims out of the cached\n * access token, WITHOUT signature verification. Used only to populate the\n * `refresh` request body (`RefreshRequest` requires both UUIDs) — never as a\n * trust decision: the actual credential is the httpOnly `axiam_access` cookie\n * the server verifies, and the server re-derives the authoritative `org_id`\n * from the tenant on refresh (see crates/axiam-api-rest handlers/auth.rs),\n * so echoing these values back carries no security weight. A malformed or\n * absent token yields an empty result (the caller then keeps whatever UUIDs\n * were resolved from construction options).\n */\n claimsFromCachedToken(): { tenantId?: string; orgId?: string } {\n const token = this.#cachedAccess?.expose();\n if (!token) {\n return {};\n }\n const claims = decodeJwtPayload(token);\n return {\n tenantId: typeof claims.tenant_id === 'string' ? claims.tenant_id : undefined,\n orgId: typeof claims.org_id === 'string' ? claims.org_id : undefined,\n };\n }\n\n /** Clear all cached token state (used by logout()). */\n clear(): void {\n this.#cachedAccess = null;\n }\n}\n\n/**\n * Decode a JWT's payload segment (the middle base64url part) into an object,\n * without verifying its signature. Returns `{}` for anything that is not a\n * well-formed three-segment JWT with a JSON object payload. This is a routing\n * helper, not a verifier — see {@link TokenManager.claimsFromCachedToken}.\n */\nfunction decodeJwtPayload(token: string): Record<string, unknown> {\n try {\n const segments = token.split('.');\n if (segments.length !== 3) {\n return {};\n }\n const json = Buffer.from(segments[1], 'base64url').toString('utf8');\n const parsed: unknown = JSON.parse(json);\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n","// ID-token claim validation — CONTRACT.md §12.4, OIDC Core §3.1.3.7.\n//\n// PURE logic only: no network, no jose, no crypto beyond a constant-time\n// compare. The signature half of §12.4 (rules 1–2: `alg` allowlist, `kid`\n// lookup, Ed25519 verification, single JWKS re-fetch) lives in node/jwks.ts,\n// on the SAME verifier the §10 middleware already uses — §12 forbids forking\n// it. This module holds rules 3–6 (issuer, audience, time, nonce) plus the\n// reason-code vocabulary, so both halves can be unit-tested independently and\n// ported as one pair.\n//\n// Every failure raises `AuthError` carrying one of the seven stable reason\n// codes from §12.3 rule 3. Rule 7 (all-or-nothing discard) is enforced by the\n// caller — `OidcClient.oidcExchange` never returns a token set whose ID token\n// failed here, so `access_token`/`refresh_token` from the same response are\n// dropped with it.\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { AuthError, type IdTokenFailureReason } from '../core/index.js';\n\n/**\n * The decoded, **already-validated** ID-token claim set carried by\n * {@link OidcTokenSet.idClaims} (CONTRACT.md §12.1).\n *\n * @remarks\n * Claim names are kept verbatim in their JWT/OIDC spelling (`iss`, `sub`,\n * `aud`, …) rather than camelCased: they are protocol identifiers a caller\n * cross-references against OIDC Core, exactly as {@link AxiamClaims} already\n * does for access-token claims. The open index signature is mandated by\n * §12.1 — the ID token's full claim set is not enumerated by `openapi.json`,\n * so unknown claims MUST be preserved and MUST NOT be rejected.\n */\nexport interface IdTokenClaims {\n /** Issuer — matched for exact string equality against the discovery document's `issuer` (§12.4 rule 3). */\n iss: string;\n /** Subject — the authenticated end user's stable identifier at AXIAM. */\n sub: string;\n /** Audience — contains the relying party's `client_id` (§12.4 rule 4). */\n aud: string | string[];\n /** Expiry time (epoch seconds). */\n exp: number;\n /** Issued-at time (epoch seconds). */\n iat: number;\n /** Not-before time (epoch seconds), when the server sends one. */\n nbf?: number;\n /** The `nonce` echoed back from the authorization request (§12.4 rule 6). */\n nonce?: string;\n /** Authorized party — required to equal `client_id` when `aud` holds multiple audiences (§12.4 rule 4). */\n azp?: string;\n /** Any further claim the server sends (e.g. `email`, `preferred_username`) — preserved, never rejected (§12.1). */\n [claim: string]: unknown;\n}\n\n/**\n * What an ID token is checked against by {@link IdTokenVerifier.verifyIdToken}\n * (CONTRACT.md §12.4 rules 3–6).\n */\nexport interface IdTokenExpectations {\n /**\n * The authoritative issuer — always the `issuer` value of the discovery\n * document the token endpoint was read from, never the client base URL\n * (§12.3 rule 6: behind a proxy the two legitimately differ).\n */\n issuer: string;\n /** The relying party's own `client_id`, matched against `aud`/`azp` (rule 4). */\n clientId: string;\n /**\n * The `nonce` returned by `oidcBegin` and passed back into `oidcExchange`.\n *\n * Mandatory for `oidcExchange`. Left `undefined` by `oidcRefresh` and\n * `loginClientCredentials`, which skip rule 6 entirely — OIDC Core §12.2\n * does not require a `nonce` in a refresh-issued ID token.\n */\n nonce?: string;\n /**\n * Permitted clock skew in seconds for `exp`/`iat`/`nbf` (rule 5). Defaults\n * to {@link MAX_CLOCK_SKEW_SEC} and is clamped to it — the contract forbids\n * configuring it *above* 60 s, so a larger value is silently reduced rather\n * than honoured.\n */\n clockSkewSec?: number;\n}\n\n/**\n * Maximum (and default) permitted clock skew in seconds for ID-token time\n * claims. CONTRACT.md §12.4 rule 5 caps this at 60 s and forbids any\n * configuration above the bound.\n */\nexport const MAX_CLOCK_SKEW_SEC = 60;\n\n/**\n * Build the `AuthError` for a §12.4 failure: a stable machine-readable\n * `reason` code plus a human-readable message that — per §12.3 rule 3 and §2's\n * construction rules — never embeds the token, a claim value that could carry\n * secret material, or the expected nonce.\n */\nexport function idTokenAuthError(reason: IdTokenFailureReason, message: string): AuthError {\n return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);\n}\n\n/**\n * Resolve the effective clock skew: the caller's value clamped into\n * `[0, MAX_CLOCK_SKEW_SEC]`, or the maximum when unset.\n */\nexport function resolveClockSkewSec(clockSkewSec?: number): number {\n if (clockSkewSec === undefined) {\n return MAX_CLOCK_SKEW_SEC;\n }\n return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);\n}\n\n/**\n * Constant-time string equality, used for the `nonce` comparison §12.4 rule 6\n * requires. A length mismatch short-circuits to `false` (`timingSafeEqual`\n * throws on unequal-length buffers) — the same idiom\n * `middleware/cookieHeader.ts` and `amqp/hmac.ts` already use.\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8');\n const right = Buffer.from(b, 'utf8');\n if (left.length !== right.length) {\n return false;\n }\n return timingSafeEqual(left, right);\n}\n\n/** Reject the JOSE header `alg` unless it is exactly `EdDSA` (§12.4 rule 1). */\nexport const ID_TOKEN_ALG = 'EdDSA';\n\n/**\n * §12.4 rule 1 — algorithm check, run against the JOSE **header** and BEFORE\n * any signature work, so the token can never select its own verification\n * algorithm. `none` is rejected by the same equality test as every other\n * non-`EdDSA` value; it gets no special case and no separate code path.\n */\nexport function assertIdTokenAlg(alg: unknown): void {\n if (alg !== ID_TOKEN_ALG) {\n throw idTokenAuthError(\n 'invalid_alg',\n `expected alg \"${ID_TOKEN_ALG}\", got ${typeof alg === 'string' ? `\"${alg}\"` : 'no alg header'}`,\n );\n }\n}\n\n/**\n * §12.4 rules 3–6 — issuer, audience, time and nonce checks over an\n * already-signature-verified claim set. Returns the claims unchanged on\n * success; throws the matching `AuthError` reason code on the first failure.\n *\n * @param claims the verified JWT payload.\n * @param expectations issuer/client_id/nonce to check against.\n * @param nowSec current time in epoch seconds — injectable so tests can pin it.\n */\nexport function checkIdTokenClaims(\n claims: IdTokenClaims,\n expectations: IdTokenExpectations,\n nowSec: number = Math.floor(Date.now() / 1000),\n): IdTokenClaims {\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n\n // Rule 3 — exact string comparison. No normalization, no trailing-slash\n // tolerance, no prefix matching.\n if (claims.iss !== expectations.issuer) {\n throw idTokenAuthError('invalid_issuer', 'iss does not equal the discovery document issuer');\n }\n\n // Rule 4 — aud must contain our client_id; with multiple audiences an azp\n // claim must be present and equal to it.\n const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!audiences.includes(expectations.clientId)) {\n throw idTokenAuthError('invalid_audience', 'aud does not contain this client_id');\n }\n if (audiences.length > 1 && claims.azp !== expectations.clientId) {\n throw idTokenAuthError(\n 'invalid_audience',\n 'aud holds multiple audiences and azp is absent or does not equal this client_id',\n );\n }\n\n // Rule 5 — exp must be in the future, iat must not be in the future, nbf is\n // honored when present; all within `skew` seconds. `exp` is treated as\n // REQUIRED: a token with no expiry could never satisfy \"exp must be in the\n // future\", so its absence is an expiry failure rather than a free pass.\n if (typeof claims.exp !== 'number') {\n throw idTokenAuthError('token_expired', 'exp claim is missing or not a number');\n }\n if (claims.exp + skew <= nowSec) {\n throw idTokenAuthError('token_expired', 'exp is in the past');\n }\n if (typeof claims.iat !== 'number') {\n throw idTokenAuthError('token_expired', 'iat claim is missing or not a number');\n }\n if (claims.iat - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'iat is in the future');\n }\n if (typeof claims.nbf === 'number' && claims.nbf - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'nbf is in the future');\n }\n\n // Rule 6 — mandatory for oidcExchange, skipped when the caller supplied no\n // expected nonce (oidcRefresh / loginClientCredentials).\n if (expectations.nonce !== undefined) {\n if (typeof claims.nonce !== 'string' || !constantTimeEquals(claims.nonce, expectations.nonce)) {\n throw idTokenAuthError('nonce_mismatch', 'nonce claim is absent or does not match the request nonce');\n }\n }\n\n return claims;\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist) — for BOTH inbound access tokens (§10\n// middleware) and relying-party ID tokens (§12.4). One verifier, one cached\n// remote key set, two entry points: `verifyAccessToken` and `verifyIdToken`.\n// §12 explicitly forbids forking this module for the OIDC flow.\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nimport { AuthError } from '../core/index.js';\nimport {\n assertIdTokenAlg,\n checkIdTokenClaims,\n ID_TOKEN_ALG,\n idTokenAuthError,\n resolveClockSkewSec,\n type IdTokenClaims,\n type IdTokenExpectations,\n} from './oidcIdToken.js';\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n /**\n * RFC 7800 / RFC 8705 §3.1 confirmation claim — present **only** on a\n * sender-constrained token (CONTRACT.md §10.1 rule 9, contract 1.15).\n *\n * Its presence changes what the token *is*. Without it, the token is a\n * bearer credential: whoever holds it may use it. With it, the token names\n * a key, and accepting it without proving the caller holds that key\n * converts it straight back into a bearer token.\n *\n * {@link Verifier.verifyAccessToken} does **not** check this — it cannot,\n * having no access to the connection's client certificate. Use\n * {@link verifyCertificateBinding}.\n */\n cnf?: CnfClaim;\n}\n\n/**\n * RFC 7800 confirmation claim.\n *\n * Deliberately an object with one optional field rather than a union: RFC 7800\n * permits confirmation methods this SDK does not implement, and such a token\n * must still *parse*. What it must not do is validate — see\n * {@link verifyCertificateBinding}.\n */\nexport interface CnfClaim {\n /**\n * RFC 8705 §3.1 — base64url (unpadded) SHA-256 of the DER client\n * certificate the token was issued to.\n */\n 'x5t#S256'?: string;\n /**\n * RFC 9449 §6.1 — base64url (unpadded) RFC 7638 thumbprint of the DPoP\n * public key the token was issued to (contract 1.16).\n */\n jkt?: string;\n}\n\n/**\n * The proofs a caller can present for a sender-constrained token\n * (contract 1.16, CONTRACT.md §10.1 rule 9).\n *\n * Both fields are optional because a caller may hold one, both or neither —\n * and \"neither\" is legitimate for an ordinary bearer token, which is why\n * {@link verifyTokenBinding} accepts `{}` and returns when the token names no\n * confirmation.\n *\n * @remarks\n * **Every thumbprint must come from the transport.** Take the certificate\n * thumbprint from the TLS peer certificate\n * (`TLSSocket.getPeerCertificate().raw` under Node), or from a *trusted*\n * terminating proxy over a channel your application controls. Never from a\n * caller-settable header: a forgeable input makes the mechanism decorative.\n */\nexport interface PresentedProofs {\n /** RFC 8705 §3.1 `x5t#S256` of the peer certificate on this connection. */\n certificateThumbprint?: string;\n /**\n * RFC 9449 §6.1 `jkt` of the key that signed a DPoP proof this SDK has\n * **already verified** for this request's `htm`/`htu`.\n *\n * Supplying a value here asserts the proof checked out. A thumbprint lifted\n * off an unverified proof would let a proof captured from any other\n * endpoint authorize this request.\n */\n dpopThumbprint?: string;\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * the certificate the caller presented on **this** connection\n * (RFC 8705 §3, contract 1.15).\n *\n * `presentedThumbprint` is the RFC 8705 §3.1 `x5t#S256` of the peer\n * certificate: base64url, **unpadded**, SHA-256 over the **DER** encoding.\n * {@link certificateThumbprintS256} computes it from DER bytes.\n *\n * | token's `cnf` | `presentedThumbprint` | result |\n * |---|---|---|\n * | absent | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | returns |\n * | `x5t#S256` | different, or `undefined` | **throws** |\n * | present, no `x5t#S256` | anything | **throws** |\n *\n * The first row is why adopting this rule breaks nothing: an unbound token is\n * still accepted whether or not a certificate is present. The last row is the\n * one that is easy to get wrong — a `cnf` naming a method this SDK cannot\n * check is an *unverifiable constraint*, never *no constraint*. Read the\n * other way, a sender-constrained token silently degrades to a bearer token\n * the day a newer AXIAM issues a confirmation this SDK predates.\n *\n * @remarks\n * **The thumbprint must come from the transport.** Take it from the TLS peer\n * certificate (`TLSSocket.getPeerCertificate().raw` under Node) or from a\n * value a *trusted* terminating proxy forwarded over a channel your\n * application controls. Never from a caller-settable request header: a\n * forgeable input makes the whole mechanism decorative.\n *\n * @throws {Error} on any of the three rejecting rows. The §10 middleware\n * wraps this into an `AuthError`.\n */\nexport function verifyCertificateBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n presentedThumbprint: string | undefined,\n): void {\n const cnf = claims.cnf;\n if (cnf === undefined || cnf === null) return;\n\n const expected = cnf['x5t#S256'];\n if (typeof expected !== 'string' || expected.length === 0) {\n // Includes the DPoP case: this entry point has no proof to check, so a\n // `jkt`-bound token is refused rather than silently downgraded.\n throw new Error(\n 'token carries a cnf confirmation naming a method this entry point cannot verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one; ' +\n 'use verifyTokenBinding for DPoP)',\n );\n }\n // A token naming BOTH methods is a conjunction (contract 1.16): this\n // function can establish one half and must not answer for the whole.\n // Refusing here is what stops \"check whichever we can\".\n if (typeof cnf.jkt === 'string' && cnf.jkt.length > 0) {\n throw new Error(\n 'token names both a certificate and a DPoP key; both must hold ' +\n '(CONTRACT.md §10.1 rule 9) — use verifyTokenBinding',\n );\n }\n if (presentedThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expected, presentedThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * **every** proof the caller presented (contract 1.16).\n *\n * This is the full rule, and the one to use unless your transport genuinely\n * cannot produce a DPoP thumbprint.\n *\n * | token's `cnf` | certificate | DPoP | result |\n * |---|---|---|---|\n * | absent | anything | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | ignored | returns |\n * | `x5t#S256` | different or absent | ignored | **throws** |\n * | `jkt` | ignored | equal | returns |\n * | `jkt` | ignored | different or absent | **throws** |\n * | both | equal | equal | returns — **conjunction** |\n * | both | either wrong or missing | — | **throws** |\n * | present, names neither | anything | anything | **throws** |\n *\n * Two rows carry the weight. **Both present is a conjunction**: an operator\n * who turned on two constraints asked for two, and satisfying the more\n * convenient one is not compliance. **Names neither is a refusal**: a\n * confirmation this SDK cannot interpret is an unverifiable constraint, and\n * reading it as \"unconstrained\" is the exact downgrade rule 9 exists to\n * prevent. That includes an *empty* `cnf` — which is also how proto3 delivers\n * an empty `CnfClaim` over gRPC (§10.3 rule 3).\n *\n * @remarks\n * This function compares thumbprints; it does **not** verify proofs. Supply\n * `dpopThumbprint` only after checking the proof's signature, `htm`, `htu`,\n * `iat` and `jti` for *this* request.\n *\n * @throws {Error} on any rejecting row. The §10 middleware wraps this into an\n * `AuthError`.\n */\nexport function verifyTokenBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n proofs: PresentedProofs = {},\n): void {\n const cnf = claims.cnf;\n // The fast path, and the common one. First on purpose: an unbound token is\n // accepted with no proofs at all, which is what keeps existing deployments\n // working when a guard adopts this rule.\n if (cnf === undefined || cnf === null) return;\n\n const expectedCert = typeof cnf['x5t#S256'] === 'string' && cnf['x5t#S256'].length > 0\n ? cnf['x5t#S256']\n : undefined;\n const expectedJkt = typeof cnf.jkt === 'string' && cnf.jkt.length > 0 ? cnf.jkt : undefined;\n\n if (expectedCert === undefined && expectedJkt === undefined) {\n throw new Error(\n 'token carries a cnf confirmation naming no method this SDK can verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one)',\n );\n }\n\n // Each arm that applies must pass. Written as two independent checks rather\n // than a switch on the pair precisely so \"both named\" needs no branch of its\n // own — it is simply the case where both run.\n if (expectedCert !== undefined) {\n if (proofs.certificateThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expectedCert, proofs.certificateThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n }\n\n if (expectedJkt !== undefined) {\n if (proofs.dpopThumbprint === undefined) {\n throw new Error('token is DPoP-bound but no verified DPoP proof was presented');\n }\n if (!constantTimeEqual(expectedJkt, proofs.dpopThumbprint)) {\n throw new Error('token is bound to a different DPoP key than the one presented');\n }\n }\n}\n\n/**\n * Constant-time string comparison for {@link verifyCertificateBinding}.\n *\n * The thumbprint is usually public — it derives from a certificate sent in the\n * clear during the handshake — so this is defence in depth. It matters most\n * for a self-signed client, where the registered thumbprint is the whole\n * credential. Hand-rolled rather than `crypto.timingSafeEqual` so that this\n * function stays usable in the browser build, where `node:crypto` is absent.\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n // Length inequality short-circuits, leaking only the length. Both operands\n // are fixed-length base64url SHA-256 digests whenever either is well-formed.\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i += 1) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/**\n * Compute the RFC 8705 §3.1 `x5t#S256` thumbprint of a DER client\n * certificate: base64url-encoded SHA-256, **without** padding.\n *\n * Unpadded is not a style choice — RFC 7515 §2 defines base64url in JOSE as\n * omitting `=`, and a padded value will not compare equal to what AXIAM put in\n * the token.\n *\n * Node only (it needs `node:crypto`). A browser-side guard has no peer\n * certificate to fingerprint in the first place.\n */\nexport async function certificateThumbprintS256(der: Uint8Array): Promise<string> {\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(der).digest('base64url');\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/**\n * Clock-skew leeway applied to the `exp` and `nbf` checks (CONTRACT.md §10.1\n * rule 7).\n *\n * A **named, bounded, non-configurable** constant, fixed at the contract's\n * RECOMMENDED 60 seconds. Rule 7 forbids both an inline literal and an\n * operator-settable value that could be widened without bound, so there is\n * deliberately no option to override it — widening the window is a source\n * change, reviewable as such.\n */\nexport const CLOCK_SKEW_LEEWAY_SEC = 60;\n\n/**\n * The verification policy {@link Verifier.verifyAccessToken} enforces, per\n * CONTRACT.md §10.1.\n *\n * `expectedTenantId` is **required** (rule 4): the `/oauth2/jwks` trust\n * anchor is organization-wide, so a valid signature proves only \"some tenant\n * in this organization\". `expectedIssuer` and `expectedAudience` are\n * **conditional** (rules 5 and 6) — omitted means the check is not performed,\n * and the SDK never assumes a default issuer.\n */\nexport interface AccessTokenExpectations {\n /**\n * §10.1 rule 4 — the tenant this resource server is configured for. The\n * token's `tenant_id` claim MUST equal it; an absent claim, an empty\n * expectation, or a mismatch all reject (fail closed).\n */\n expectedTenantId: string;\n /** §10.1 rule 5 — expected `iss`. Omit for no issuer check. */\n expectedIssuer?: string;\n /**\n * §10.1 rule 6 — expected `aud`. Omit for no audience check. A resource\n * server guarding user-facing routes SHOULD pass `\"axiam:user\"`.\n */\n expectedAudience?: string;\n}\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /**\n * Verify `token` against the **complete** CONTRACT.md §10.1 minimum\n * local-verification set and return its claims.\n *\n * | § | rule | how it is enforced |\n * |---|---|---|\n * | 1 | signature | `algorithms: ['EdDSA']` is checked by `jose` against the JWS header *before* the remote key set function is invoked, so `alg: none` and an HS-signed token bearing an EdDSA `kid` are rejected without a key lookup. |\n * | 2 | `exp` | `requiredClaims: ['exp']` — `jose` only checks `exp` *if present* by default, so an absent `exp` (a permanent credential) would otherwise sail through. A non-numeric `exp` is rejected by `jose`'s own type check. |\n * | 3 | `nbf` | honoured by `jose` when present, bounded by {@link CLOCK_SKEW_LEEWAY_SEC}. |\n * | 4 | `tenant_id` | asserted against {@link AccessTokenExpectations.expectedTenantId}; absent claim, absent expectation, or mismatch all reject. |\n * | 5 | `iss` | checked only when `expectedIssuer` is supplied. |\n * | 6 | `aud` | checked only when `expectedAudience` is supplied. |\n * | 7 | clock skew | {@link CLOCK_SKEW_LEEWAY_SEC}, passed as `clockTolerance`. |\n *\n * Rejects with the underlying error on any failed rule; the §10 middleware\n * wraps that into an `AuthError`.\n */\n verifyAccessToken(token: string, expectations: AccessTokenExpectations): Promise<AxiamClaims>;\n\n /**\n * Verify **only** the EdDSA signature of `token` — CONTRACT.md §10.1's\n * \"raw signature-only primitive\".\n *\n * @remarks\n * **This is not a guard.** It performs no `exp`, `nbf`, `tenant_id`, `iss`\n * or `aud` check whatsoever: an expired token, a not-yet-valid token, and a\n * token minted for a *different tenant* in the same organization all pass.\n * It exists only for integrators deliberately implementing their own\n * policy on top of the signature — the `Unchecked` suffix is there to make\n * that omission obvious at the call site. Anything guarding a route MUST\n * use {@link Verifier.verifyAccessToken} (or, better, the §10 middleware\n * built on it).\n */\n verifySignatureOnlyUnchecked(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * The relying-party half of the same verifier (CONTRACT.md §12.4): validates\n * an OIDC **ID token** rather than an AXIAM access token.\n *\n * @remarks\n * Kept as its own interface, and *added* to the object {@link createVerifier}\n * returns rather than to {@link Verifier} itself, so existing code that\n * implements `Verifier` (e.g. a hand-rolled test double supplied as\n * `VerifiableSession.jwksVerifier`) keeps compiling — contract 1.4 is\n * additive.\n */\nexport interface IdTokenVerifier {\n /**\n * Validate an OIDC ID token per CONTRACT.md §12.4 and return its claims.\n *\n * Enforces rule 1 (`alg` MUST be `EdDSA`, read from the header *before* any\n * signature work — `none` and every other algorithm rejected), rule 2\n * (Ed25519 signature against the key selected by `kid`, with the single\n * JWKS re-fetch policy §10 already implements), then rules 3–6 via\n * {@link checkIdTokenClaims}. Rejects with `AuthError` carrying the\n * matching §12.3 reason code on the first failure.\n */\n verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims>;\n}\n\n/**\n * The concrete verifier {@link createVerifier} / {@link createJwksVerifier}\n * return: one object, one cached remote key set, both the §10 access-token\n * path and the §12.4 ID-token path. §12 forbids a second verifier.\n */\nexport interface JwksVerifier extends Verifier, IdTokenVerifier {}\n\n/**\n * Build a verifier bound to `{baseUrl}/oauth2/jwks`.\n *\n * `jose` is loaded lazily via dynamic `import()` (Pitfall 1 — CJS-safe); the\n * remote JWKS itself is also fetched/cached lazily by `jose`, not eagerly\n * here.\n *\n * For the relying-party (§12) flow use {@link createJwksVerifier} with the\n * `jwks_uri` the discovery document advertises instead of hardcoding\n * {@link JWKS_PATH} — §12.3 rule 6 requires reading the URI from the document.\n */\nexport function createVerifier(baseUrl: string): JwksVerifier {\n return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);\n}\n\n/**\n * Build a verifier bound to an explicit, absolute JWKS URI — the `jwks_uri`\n * value taken from the OIDC discovery document (CONTRACT.md §12.3 rule 6).\n *\n * Identical machinery to {@link createVerifier}: one lazily-resolved\n * `createRemoteJWKSet` singleton per verifier instance, shared by\n * `verifyAccessToken` and `verifyIdToken`.\n */\nexport function createJwksVerifier(jwksUri: string): JwksVerifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // the same createRemoteJWKSet cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent invalid-`kid` burst\n // against a cold cache must collapse to exactly ONE network fetch. Proven\n // (not just assumed) by `test/node/jwks.test.ts`'s \"collapses N concurrent\n // verifyAccessToken calls ... to exactly one JWKS fetch\" test, which mocks\n // global `fetch` with a call counter and fires 8 concurrent calls: jose's\n // `createRemoteJWKSet` (see jose's `RemoteJWKSet.reload()`,\n // `this.#pendingFetch ||= fetchJwks(...).then(...)`) ALREADY holds its own\n // internal lazy-promise-singleton around the underlying fetch, so\n // concurrent callers reaching a cold/unknown-kid getter share the same\n // in-flight fetch promise natively — no additional `inFlightFetch` guard\n // is added here (it would be redundant). If a future `jose` upgrade\n // removes that internal guarantee, the burst test above will start\n // failing and an explicit guard (mirroring `jwksPromise`'s shape) must be\n // added at that point.\n let jwksPromise: Promise<ReturnType<typeof import('jose').createRemoteJWKSet>> | null = null;\n\n async function getJwks() {\n if (!jwksPromise) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n jwksPromise = import('jose').then(({ createRemoteJWKSet }) =>\n createRemoteJWKSet(new URL(jwksUri), {\n cooldownDuration: COOLDOWN_DURATION_MS,\n timeoutDuration: TIMEOUT_DURATION_MS,\n }),\n );\n }\n return jwksPromise;\n }\n\n return {\n async verifyAccessToken(\n token: string,\n expectations: AccessTokenExpectations,\n ): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // §10.1 rule 1: explicit algorithm allowlist — never trust the token's\n // own `alg` header; defense against algorithm-confusion attacks\n // (T-17-14). jose checks this against the JWS protected header BEFORE\n // it calls the remote-key-set resolver, so `alg: none` and an HS256\n // token carrying our EdDSA `kid` both die without a key lookup.\n //\n // §10.1 rule 2: `requiredClaims: ['exp']` is load-bearing and NOT a\n // jose default — jose validates `exp` only `if (payload.exp !==\n // undefined)`, so a token minted with no `exp` at all (a permanent\n // credential) would otherwise verify. This is precisely the SEC-080\n // defect. A present-but-non-numeric `exp` is rejected by jose's own\n // `\"exp\" claim must be a number` check.\n //\n // §10.1 rules 5/6: `issuer`/`audience` are passed ONLY when configured\n // — supplying them also makes jose require the corresponding claim to\n // be present, which is the intended fail-closed behaviour; omitting\n // them means no check, per the conditional wording of the rules.\n //\n // §10.1 rules 3/7: jose honours `nbf` when present; `clockTolerance`\n // bounds both the `exp` and the `nbf` comparison.\n const { payload } = await jwtVerify(token, jwks, {\n algorithms: ['EdDSA'],\n requiredClaims: ['exp'],\n clockTolerance: CLOCK_SKEW_LEEWAY_SEC,\n ...(expectations.expectedIssuer !== undefined\n ? { issuer: expectations.expectedIssuer }\n : {}),\n ...(expectations.expectedAudience !== undefined\n ? { audience: expectations.expectedAudience }\n : {}),\n });\n\n // §10.1 rule 4 — the tenant assertion, which no JWT library can do for\n // us: `tenant_id` is an AXIAM claim, and the JWKS trust anchor is\n // organization-wide. Fails closed on all three failure shapes: no\n // configured tenant, an absent/ill-typed claim, and a mismatch.\n // \"Nothing to compare against, so nothing to check\" is the SEC-080\n // defect, not a pass.\n assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);\n\n return payload as unknown as AxiamClaims;\n },\n\n async verifySignatureOnlyUnchecked(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Signature + algorithm pinning ONLY — see the interface docs. No\n // `requiredClaims`, no `clockTolerance`, and deliberately no tenant\n // assertion. `jose` still refuses an *expired* token here because its\n // `exp` check is unconditional when the claim is present; a token with\n // no `exp` at all is accepted, which is exactly why this entry point\n // must never guard a route.\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n\n async verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims> {\n const { decodeProtectedHeader, jwtVerify } = await import('jose');\n\n // §12.4 rule 1 — read `alg` from the header and reject anything but\n // EdDSA BEFORE touching the JWKS or the signature. A malformed token\n // (not three base64url segments) cannot even yield a header, which is\n // itself an `invalid_alg` failure: no algorithm was assertable.\n let header: { alg?: string; kid?: string };\n try {\n header = decodeProtectedHeader(token);\n } catch {\n throw idTokenAuthError('invalid_alg', 'token is not a well-formed JWS');\n }\n assertIdTokenAlg(header.alg);\n\n // §12.4 rule 2 — a token with no `kid` is rejected outright: there is\n // no key to select, and guessing \"the only key\" would defeat rotation.\n if (!header.kid) {\n throw idTokenAuthError('unknown_kid', 'token carries no kid header');\n }\n\n const jwks = await getJwks();\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n let claims: IdTokenClaims;\n try {\n // `algorithms` is passed again (belt and braces with rule 1) so jose\n // can never be talked into another algorithm either. `clockTolerance`\n // keeps jose's own exp/nbf checks aligned with rule 5's bound; the\n // explicit re-checks in checkIdTokenClaims cover iat and give each\n // failure its own reason code.\n const { payload } = await jwtVerify(token, jwks, {\n algorithms: [ID_TOKEN_ALG],\n clockTolerance: skew,\n });\n claims = payload as unknown as IdTokenClaims;\n } catch (err) {\n throw mapJoseVerifyError(err);\n }\n\n return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });\n },\n };\n}\n\n/**\n * CONTRACT.md §10.1 rule 4 — assert the token's `tenant_id` claim against the\n * tenant the relying party is configured for.\n *\n * Exported so the §10 middleware can re-assert it on the guard side, where it\n * cannot be bypassed by a caller-supplied {@link Verifier} implementation\n * that ignores its expectations.\n *\n * @param claim - the raw `tenant_id` claim value off the verified payload.\n * @param expected - the configured tenant.\n * @throws AuthError when no tenant is configured, when the claim is absent or\n * not a non-empty string, or when the two differ.\n */\nexport function assertTenantClaim(claim: unknown, expected: string | undefined): void {\n if (typeof expected !== 'string' || expected === '') {\n throw new AuthError(\n 'no configured tenant to verify the token against; refusing the request ' +\n '(CONTRACT.md §10.1 rule 4 fails closed)',\n );\n }\n if (typeof claim !== 'string' || claim === '') {\n throw new AuthError('invalid tenant_id claim');\n }\n if (claim !== expected) {\n warnOnceIfComparandLooksLikeASlug(claim, expected);\n throw new AuthError('token tenant_id does not match configured tenant');\n }\n}\n\n/** Canonical 8-4-4-4-12 hex UUID shape. Shape only — no version/variant check. */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Latches {@link warnOnceIfComparandLooksLikeASlug} to one emission per process. */\nlet slugComparandWarned = false;\n\n/**\n * Test seam: reset the once-per-process latch so each test observes its own\n * behaviour rather than a previous test's.\n *\n * @internal\n */\nexport function resetTenantComparandWarningForTests(): void {\n slugComparandWarned = false;\n}\n\n/**\n * Name the slug-vs-UUID misconfiguration explicitly (§13.4 observation 6).\n *\n * AXIAM access tokens carry the tenant **UUID** in `tenant_id`, but this SDK's\n * client is commonly configured with a tenant **slug**. A guard handed that slug\n * rejects 100% of traffic — fail-closed and safe, but it presents as \"every\n * token is invalid\" with nothing pointing at the cause, which is a miserable\n * thing to debug.\n *\n * Deliberately: emitted **once per process**, so it is a configuration\n * diagnostic and not a log-flood sink an attacker can drive with bad tokens;\n * keyed on the **shape of the operator-configured value**, never on anything a\n * caller supplies, so it cannot be triggered on demand; and emitted **after**\n * the rejection is decided, so it only ever explains a failure and the\n * verification outcome is byte-for-byte unchanged.\n *\n * A UUID-vs-UUID mismatch is a genuine cross-tenant rejection and stays silent.\n */\nfunction warnOnceIfComparandLooksLikeASlug(claim: string, expected: string): void {\n if (slugComparandWarned) return;\n if (!UUID_RE.test(claim) || UUID_RE.test(expected)) return;\n\n slugComparandWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n `AXIAM: the tenant this guard was configured with (\"${expected}\") is not a UUID, ` +\n 'but access tokens carry the tenant UUID in their `tenant_id` claim, so this guard ' +\n 'will reject every request. Configure it with the tenant UUID, not the slug. ' +\n '(CONTRACT.md §10.1 rule 4; logged once per process, and it does not affect the ' +\n 'rejection itself.)',\n );\n}\n\n/**\n * Translate a `jose` verification failure into the §12.3 reason-code\n * vocabulary. jose's error `code` strings are stable public API\n * (`ERR_JWKS_NO_MATCHING_KEY`, `ERR_JWT_EXPIRED`, …); anything unrecognized\n * degrades to `invalid_signature`, the safest catch-all — an unclassifiable\n * verification failure is never treated as success.\n */\nfunction mapJoseVerifyError(err: unknown): AuthError {\n const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : '';\n switch (code) {\n case 'ERR_JWKS_NO_MATCHING_KEY':\n // jose has already performed its single re-fetch-then-fail dance here\n // (createRemoteJWKSet reloads once per cooldown window on an unmatched\n // kid) — exactly the §12.4 rule 2 / §10 policy.\n return idTokenAuthError('unknown_kid', 'no JWKS key matches the token kid');\n case 'ERR_JWT_EXPIRED':\n return idTokenAuthError('token_expired', 'exp is in the past');\n case 'ERR_JWT_CLAIM_VALIDATION_FAILED':\n return idTokenAuthError('token_expired', 'a time-based claim (nbf/iat) is not yet valid');\n default:\n return idTokenAuthError('invalid_signature', 'signature verification failed');\n }\n}\n","// createNodeSession — extends the 17-02 SharedSession with the Node\n// persona's auth internals (D-13).\n//\n// Builds the same REST SharedSession the browser persona uses, then swaps\n// in a tough-cookie jar (via wrapAxios) so httpOnly Set-Cookie tokens\n// persist, and attaches a TokenManager + JWKS verifier. This is the ONE\n// shared session object gRPC (interceptor.ts/callWithRefresh.ts) and REST\n// both operate on — the single-flight refresh guard (`session.refreshGuard`,\n// a per-session instance created in the SharedSession constructor, CR-02)\n// is therefore transparently shared across both transports FOR THIS\n// SESSION ONLY, since both call it with an equivalent `POST\n// /api/v1/auth/refresh` closure. A different NodeSession/SharedSession\n// instance gets its own independent guard — refreshes never cross-wire\n// between sessions.\n\nimport type { CookieJar } from 'tough-cookie';\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, resolveNodeTlsOptions, SharedSession } from '../rest/session.js';\nimport { AxiamClient } from '../rest/client.js';\nimport { CSRF_COOKIE, createJar, extractCookieValue, wrapAxios } from './cookieJar.js';\nimport { TokenManager } from './tokenManager.js';\nimport { createVerifier, type Verifier } from './jwks.js';\n\n/** Node-only {@link SharedSession} adding a {@link TokenManager} and a JWKS {@link Verifier} for local (offline) access-token verification. */\nexport class NodeSession extends SharedSession {\n /** Manages the access/refresh token pair backing this session. */\n readonly tokenManager: TokenManager;\n /** Local JWKS verifier for validating access tokens without a server round-trip. */\n readonly jwksVerifier: Verifier;\n readonly #jar: CookieJar;\n\n constructor(\n options: AxiamClientOptions,\n base: SharedSession,\n tokenManager: TokenManager,\n jwksVerifier: Verifier,\n jar: CookieJar,\n ) {\n super(options, base.axios, base.tenantHeaderValue);\n this.tokenManager = tokenManager;\n this.jwksVerifier = jwksVerifier;\n this.#jar = jar;\n }\n\n /**\n * Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this\n * session's per-instance `refreshGuard` (inherited from SharedSession) by\n * both REST's reactive interceptor (rest/interceptors.ts) and gRPC's\n * callWithRefresh — since `refreshGuard` is scoped to THIS session\n * instance (CR-02, D-13), both transports share exactly one in-flight\n * refresh for this session regardless of which one triggers it, while\n * remaining fully independent from any other session's guard.\n */\n doRefresh = async (): Promise<void> => {\n await this.axios.post('/api/v1/auth/refresh', this.buildRefreshBody());\n await this.tokenManager.syncFromJar();\n // A rotated access token may carry a new tenant_id/org_id — keep the\n // resolved refresh identifiers current for the next refresh.\n this.#resolveIdentifiersFromToken();\n // The refresh response may rotate the axiam_csrf cookie — resync\n // session.csrfToken from the jar so the next state-changing request\n // still forwards a valid X-CSRF-Token (CR-01).\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a\n * successful login()/verifyMfa(). Refreshes the cached access token (so\n * the gRPC interceptor's synchronous fast-path is current immediately\n * after login) and reads the `axiam_csrf` cookie out of the jar into\n * `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.\n */\n onAuthenticated = async (): Promise<void> => {\n await this.tokenManager.syncFromJar();\n // D-14: resolve the authoritative tenant_id/org_id UUIDs from the freshly\n // issued access token so refresh() can supply them (RefreshRequest needs\n // the UUID form, and the client may have been constructed with slugs).\n this.#resolveIdentifiersFromToken();\n await this.#syncCsrfFromJar();\n };\n\n /**\n * Populate `resolvedTenantId`/`resolvedOrgId` from the cached access token's\n * claims when present, leaving any UUID resolved from construction options in\n * place otherwise. Best-effort and unverified (see\n * TokenManager.claimsFromCachedToken) — used purely to build the refresh body.\n */\n #resolveIdentifiersFromToken(): void {\n const { tenantId, orgId } = this.tokenManager.claimsFromCachedToken();\n if (tenantId) {\n this.resolvedTenantId = tenantId;\n this.tokenManager.setTenantId(tenantId);\n }\n if (orgId) {\n this.resolvedOrgId = orgId;\n }\n }\n\n async #syncCsrfFromJar(): Promise<void> {\n this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);\n }\n}\n\n/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */\nexport function createNodeSession(options: AxiamClientOptions): NodeSession {\n const base = createSession(options);\n const jar = createJar();\n // Hand the §6/§6.1 TLS material to the jar-aware agent. createSession's own\n // `https.Agent` is unusable here — a cookie agent must own the socket — so\n // this is the ONLY place a customCa or client certificate reaches the wire\n // under the Node persona. See wrapAxios' doc comment.\n wrapAxios(base.axios, jar, resolveNodeTlsOptions(options));\n\n const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);\n const jwksVerifier = createVerifier(options.baseUrl);\n\n return new NodeSession(options, base, tokenManager, jwksVerifier, jar);\n}\n\n/**\n * Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node\n * counterpart to `new AxiamClient(options)` (which builds the browser\n * `SharedSession` with no cookie jar): it constructs a `NodeSession`\n * (tough-cookie jar + CSRF/refresh token sync) and adopts it via the\n * `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens\n * from login/refresh persist and every post-login REST call authenticates\n * correctly under Node.\n *\n * Lives in this Node-only module (reachable via the `axiam-sdk/node` and\n * `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`\n * entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).\n * The returned client shares the single session with any `AuthzGrpcClient`\n * built from the same `NodeSession`.\n */\nexport function createNodeClient(options: AxiamClientOptions): AxiamClient {\n return new AxiamClient(options, createNodeSession(options));\n}\n"]}