axiam-sdk 1.0.0-alpha21 → 1.0.0-alpha24

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 (46) hide show
  1. package/README.md +93 -2
  2. package/dist/{authzCore-DuRI1aJf.d.cts → authzCore-CA9zFm1n.d.cts} +38 -4
  3. package/dist/{authzCore-DtSN59if.d.ts → authzCore-a-wZL2P3.d.ts} +38 -4
  4. package/dist/{client-B_FqmZ0i.d.cts → client-CtT9nHQP.d.cts} +1 -1
  5. package/dist/{client-Dn1fs5MH.d.ts → client-utwuwc9m.d.ts} +1 -1
  6. package/dist/{cookieJar-Cl8Lq9dL.d.ts → cookieJar-C9fqLqbh.d.ts} +29 -6
  7. package/dist/{cookieJar-BTDnjjbL.d.cts → cookieJar-DeJKczxD.d.cts} +29 -6
  8. package/dist/grpc/index.d.cts +5 -5
  9. package/dist/grpc/index.d.ts +5 -5
  10. package/dist/grpc/index.js +81 -14
  11. package/dist/grpc/index.js.map +1 -1
  12. package/dist/grpc/index.mjs +81 -14
  13. package/dist/grpc/index.mjs.map +1 -1
  14. package/dist/index.d.cts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +32 -7
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +32 -7
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{jwks-BgojMGC5.d.cts → jwks-DEiwxlku.d.cts} +84 -3
  21. package/dist/{jwks-BgojMGC5.d.ts → jwks-DEiwxlku.d.ts} +84 -3
  22. package/dist/middleware/index.d.cts +6 -6
  23. package/dist/middleware/index.d.ts +6 -6
  24. package/dist/middleware/index.js +177 -138
  25. package/dist/middleware/index.js.map +1 -1
  26. package/dist/middleware/index.mjs +176 -139
  27. package/dist/middleware/index.mjs.map +1 -1
  28. package/dist/nestjs/index.d.cts +2 -2
  29. package/dist/nestjs/index.d.ts +2 -2
  30. package/dist/node/index.d.cts +94 -6
  31. package/dist/node/index.d.ts +94 -6
  32. package/dist/node/index.js +183 -16
  33. package/dist/node/index.js.map +1 -1
  34. package/dist/node/index.mjs +179 -18
  35. package/dist/node/index.mjs.map +1 -1
  36. package/dist/{oidcState-CkFuCjpM.d.ts → oidcState-CfebuJ0n.d.ts} +2 -2
  37. package/dist/{oidcState-BGxqWUun.d.cts → oidcState-tHRAg5bu.d.cts} +2 -2
  38. package/dist/rest/index.d.cts +2 -2
  39. package/dist/rest/index.d.ts +2 -2
  40. package/dist/rest/index.js +32 -7
  41. package/dist/rest/index.js.map +1 -1
  42. package/dist/rest/index.mjs +32 -7
  43. package/dist/rest/index.mjs.map +1 -1
  44. package/dist/{session-BWUWhhyB.d.cts → session-ti3C9ZJU.d.cts} +28 -1
  45. package/dist/{session-BWUWhhyB.d.ts → session-ti3C9ZJU.d.ts} +28 -1
  46. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/rest/session.ts","../../src/rest/interceptors.ts","../../src/rest/auth.ts","../../src/rest/authz.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../../src/node/tokenManager.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/node/session.ts","../../src/node/oidcPkce.ts","../../src/node/oidc.ts","../../src/node/oidcState.ts"],"names":["document"],"mappings":";;;;;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAA,CAAK,GAAA,EAAI,EAAG;AAChC,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA;AAAA,EAGA,MAAA,GAAe;AACb,IAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AACrB,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAK,QAAA,EAAU;AACzC,MAAA,IAAI,IAAA,CAAK,aAAa,GAAA,EAAK;AACzB,QAAA,IAAA,CAAK,QAAA,CAAS,OAAO,KAAK,CAAA;AAAA,MAC5B;AAAA,IACF;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Central status -> error mapper (CONTRACT.md §2, D-17).\n//\n// The single source of truth for both rest/ and grpc/ transports so the two\n// cannot drift on the error taxonomy. Transcribes CONTRACT.md §2's HTTP and\n// gRPC tables exactly.\n//\n// GrpcStatus is exported here (not imported from @grpc/grpc-js) so that\n// core stays dependency-free — grpc/ imports the numeric codes from core\n// rather than the other way around.\n\nimport {\n AuthError,\n AuthzError,\n NetworkError,\n OAuthProtocolError,\n type AxiamError,\n} from './errors.js';\n\n/** gRPC status codes referenced by CONTRACT.md §2 (subset of the full grpc.status enum). */\nexport const GrpcStatus = {\n DEADLINE_EXCEEDED: 4,\n PERMISSION_DENIED: 7,\n RESOURCE_EXHAUSTED: 8,\n INTERNAL: 13,\n UNAVAILABLE: 14,\n UNAUTHENTICATED: 16,\n} as const;\n\nexport interface HttpErrorContext {\n action?: string;\n resourceId?: string;\n cause?: unknown;\n /**\n * The request URL (absolute or path-only) the error came from, when\n * available. Load-bearing for the two **endpoint-qualified** rows of §2's\n * HTTP table (added by contract 1.4): a `400`/`401` carrying an\n * `OAuth2ErrorResponse` body maps to `OAuthProtocolError` only when it came\n * from an `/oauth2/*` endpoint. Omitting it simply keeps the generic rows.\n */\n url?: string;\n /**\n * The parsed JSON response body (when available). For a 403/409\n * authorization-denied response the server shapes this as\n * `{ error: \"authorization_denied\", message, action?, resource_id? }`\n * (`action` present when known, `resource_id` present only for a\n * resource-scoped denial). `mapHttpStatusToError` prefers these body\n * fields over `action`/`resourceId` above when populating `AuthzError`.\n */\n body?: unknown;\n}\n\n/**\n * Extract `action`/`resource_id` (snake_case -> camelCase) from a parsed\n * authorization-denied response body, if present and string-typed. Any other\n * shape (missing fields, non-object body, older servers with no body at all)\n * yields `{}`, so callers fall back to caller-supplied context.\n */\nfunction extractAuthzFieldsFromBody(body: unknown): { action?: string; resourceId?: string } {\n if (body === null || typeof body !== 'object') {\n return {};\n }\n const record = body as Record<string, unknown>;\n const action = typeof record.action === 'string' ? record.action : undefined;\n const resourceId = typeof record.resource_id === 'string' ? record.resource_id : undefined;\n return { action, resourceId };\n}\n\n/**\n * The RFC 6749 error body shape (`OAuth2ErrorResponse` in `openapi.json`)\n * returned by AXIAM's `/oauth2/*` endpoints. Both fields are required by the\n * schema.\n */\nexport interface OAuth2ErrorResponseWire {\n /** RFC 6749 error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable description of the failure. */\n error_description: string;\n}\n\n/**\n * Path prefix identifying AXIAM's OAuth2 endpoint family (`/oauth2/token`,\n * `/oauth2/introspect`, `/oauth2/revoke`, …). The two endpoint-qualified §2\n * rows apply only to URLs whose path starts with it.\n */\nconst OAUTH2_PATH_PREFIX = '/oauth2/';\n\n/**\n * Whether `url` targets an `/oauth2/*` endpoint. Accepts both an absolute URL\n * (as taken from the discovery document) and a bare path (as axios request\n * configs carry), and never throws on a malformed value — an unparseable URL\n * simply falls back to a substring test, so a mis-shaped URL can only ever\n * *fail* to qualify for the OAuth2 rows, never wrongly qualify for them.\n */\nexport function isOAuth2EndpointUrl(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n // A relative path has no base here, so `URL` throws and we fall through.\n return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);\n } catch {\n return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);\n }\n}\n\n/**\n * Narrow a parsed response body to {@link OAuth2ErrorResponseWire}. Both\n * `error` and `error_description` must be present and string-typed — a body\n * that carries only one of them is NOT an `OAuth2ErrorResponse` and keeps the\n * generic §2 mapping (better a generic error than a fabricated\n * `error_description`).\n */\nexport function isOAuth2ErrorBody(body: unknown): body is OAuth2ErrorResponseWire {\n if (body === null || typeof body !== 'object') {\n return false;\n }\n const record = body as Record<string, unknown>;\n return typeof record.error === 'string' && typeof record.error_description === 'string';\n}\n\n/**\n * ALLOWLIST (X-3) of response headers that are safe to preserve in a\n * NetworkError.cause. Every header NOT listed here has its value redacted to a\n * placeholder, so a custom sensitive header (e.g. `X-Auth-Token`) can never\n * survive into a thrown error — unlike a small denylist, which only catches the\n * headers it happens to enumerate. Names are compared case-insensitively (all\n * entries are lower-case). Keep this list small and strictly non-secret:\n * standard diagnostic response headers plus this SDK's own non-secret request\n * headers (e.g. `x-tenant-id`).\n */\nconst SAFE_RESPONSE_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'date',\n 'server',\n 'retry-after',\n 'x-request-id',\n 'x-tenant-id',\n]);\n\n/** Placeholder substituted for the value of any non-allowlisted header. */\nconst REDACTED_HEADER = '[REDACTED]';\n\n/**\n * Redact every non-allowlisted response header from an axios-error-shaped\n * `err` before it is attached as `NetworkError.cause` (CR-04, D-16, X-3). On\n * login/refresh error paths the server may have already issued Set-Cookie\n * headers containing raw `axiam_access`/`axiam_refresh` values (and callers may\n * set custom sensitive headers such as `X-Auth-Token`); none of these must be\n * reachable via `console.log`/`JSON.stringify`/`util.inspect` of the thrown\n * error. Only headers on `SAFE_RESPONSE_HEADERS` keep their value; all others\n * are replaced with `[REDACTED]`.\n *\n * Returns a new, shallow-cloned object for any input shaped like\n * `{ response: { headers: {...} } }` — the caller's original axios error\n * object is left untouched. Non-object inputs (plain Error, string,\n * undefined) and objects with no `response.headers` are returned unchanged.\n */\nexport function sanitizeAxiosError(err: unknown): unknown {\n if (err === null || typeof err !== 'object') {\n return err;\n }\n const candidate = err as { response?: unknown };\n if (candidate.response === null || typeof candidate.response !== 'object') {\n return err;\n }\n const response = candidate.response as { headers?: unknown };\n if (response.headers === null || typeof response.headers !== 'object') {\n return err;\n }\n\n const sanitizedHeaders: Record<string, unknown> = { ...(response.headers as Record<string, unknown>) };\n for (const key of Object.keys(sanitizedHeaders)) {\n if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {\n sanitizedHeaders[key] = REDACTED_HEADER;\n }\n }\n\n return {\n ...err,\n response: {\n ...response,\n headers: sanitizedHeaders,\n },\n };\n}\n\n/**\n * Map an HTTP status code to an AxiamError variant per CONTRACT.md §2's HTTP\n * status table.\n *\n * | Status | Type |\n * |-----------|--------------|\n * | 400 | NetworkError |\n * | 400 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 401 | AuthError |\n * | 401 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * Where two rows match the same response the more specific\n * (endpoint- and body-qualified) row wins, per §2 — so the two\n * `OAuthProtocolError` rows are evaluated first. They require BOTH an\n * `/oauth2/*` `ctx.url` AND an `OAuth2ErrorResponse`-shaped `ctx.body`;\n * anything else keeps the generic mapping.\n *\n * NetworkError's `cause` (when provided via `ctx.cause`) is always passed\n * through `sanitizeAxiosError` first (CR-04) — this is the single choke\n * point for both rest/ auth call sites and any future caller.\n *\n * For 403/409, `action`/`resourceId` are sourced from the response body\n * (`ctx.body`) when the body carries them, falling back to the\n * caller-supplied `ctx.action`/`ctx.resourceId` (the request call-args)\n * otherwise — this keeps compatibility with older servers that don't yet\n * echo `action`/`resource_id` in the denial body.\n */\nexport function mapHttpStatusToError(\n status: number,\n message: string,\n ctx?: HttpErrorContext,\n): AxiamError {\n // Endpoint-qualified rows first (§2 \"the more specific row wins\",\n // §12.3 rule 3). `message` is deliberately ignored here: the contract fixes\n // OAuthProtocolError's message to \"<error>: <error_description>\".\n if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {\n return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);\n }\n if (status === 401) {\n return new AuthError(message);\n }\n if (status === 403 || status === 409) {\n const fromBody = extractAuthzFieldsFromBody(ctx?.body);\n return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);\n }\n // 400, 408, 429, 5xx, and any other status fall through to NetworkError.\n return new NetworkError(message, sanitizeAxiosError(ctx?.cause));\n}\n\n/**\n * Map a gRPC status code to an AxiamError variant per CONTRACT.md §2's gRPC\n * status table.\n *\n * | Code | Type |\n * |------------------------|--------------|\n * | 16 UNAUTHENTICATED | AuthError |\n * | 7 PERMISSION_DENIED | AuthzError |\n * | 14 UNAVAILABLE | NetworkError |\n * | 4 DEADLINE_EXCEEDED | NetworkError |\n * | 13 INTERNAL | NetworkError |\n * | 8 RESOURCE_EXHAUSTED | NetworkError |\n * | other | NetworkError |\n */\nexport function mapGrpcStatusToError(code: number, message: string): AxiamError {\n if (code === GrpcStatus.UNAUTHENTICATED) {\n return new AuthError(message);\n }\n if (code === GrpcStatus.PERMISSION_DENIED) {\n return new AuthzError(message);\n }\n return new NetworkError(message);\n}\n","// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// CSRF double-submit helpers (CONTRACT.md §3, D-05/D-28).\n//\n// The AXIAM server's CSRF middleware validates X-CSRF-Token against the\n// axiam_csrf cookie value directly (cookie double-submit). The regex is\n// deliberately hardcoded (not built dynamically from a configurable cookie\n// name) to avoid ReDoS/CWE-1333 — mirrors frontend/src/lib/api.ts exactly.\n\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\nexport const CSRF_HEADER = 'X-CSRF-Token';\nexport const CSRF_METHODS: ReadonlySet<string> = new Set(['post', 'put', 'patch', 'delete']);\n\nconst CSRF_COOKIE_REGEX = /(?:^|;\\s*)axiam_csrf=([^;]*)/;\n\n/** Extract the axiam_csrf cookie value from a `document.cookie`-shaped string, or null if absent. */\nexport function readCsrfCookie(cookieString: string): string | null {\n const match = CSRF_COOKIE_REGEX.exec(cookieString);\n if (!match) {\n return null;\n }\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Returns the CSRF header value for a state-changing HTTP method\n * (post/put/patch/delete, case-insensitive), or undefined for safe methods\n * (get/head/options) or when no CSRF cookie is present yet.\n */\nexport function csrfHeaderForMethod(method: string, cookieString: string): string | undefined {\n if (!CSRF_METHODS.has(method.toLowerCase())) {\n return undefined;\n }\n const token = readCsrfCookie(cookieString);\n return token ?? undefined;\n}\n","// Single-flight refresh guard (CONTRACT.md §9, D-07/D-13).\n//\n// Per-session-scoped shared-Promise guard (CR-02 gap closure, 17-VERIFICATION.md):\n// createRefreshGuard() returns a fresh, independent refreshOnce closure per\n// call, each closing over its OWN private refreshPromise. Concurrent callers\n// against the SAME guard instance share the same in-flight Promise; the\n// guard clears on settle (success or failure) so a later expiry can trigger\n// a fresh refresh — this is the exactly-one-in-flight-at-a-time semantics §9\n// requires, not a permanent single-refresh-ever lock. Distinct guard\n// instances (one per SharedSession/NodeSession, D-13) never share state, so\n// a refresh on session A can never silently satisfy a concurrent refresh on\n// session B.\n\n/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */\nexport type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;\n\n/** Test-only reset hook type, attached to each guard closure via `Object.assign`. @internal */\ninterface ResettableRefreshGuard {\n (doRefresh: () => Promise<void>): Promise<void>;\n __reset(): void;\n}\n\n/**\n * Build a fresh, independent single-flight refresh guard. Each call returns\n * its own closure with a private `refreshPromise` — instantiate one per\n * `SharedSession`/`NodeSession` (D-13) so refresh guards never cross-wire\n * between independent client instances (CR-02).\n */\nexport function createRefreshGuard(): RefreshGuard {\n let refreshPromise: Promise<void> | null = null;\n\n const guard = ((doRefresh: () => Promise<void>): Promise<void> => {\n if (!refreshPromise) {\n refreshPromise = doRefresh().finally(() => {\n refreshPromise = null;\n });\n }\n return refreshPromise;\n }) as ResettableRefreshGuard;\n\n guard.__reset = () => {\n refreshPromise = null;\n };\n\n return guard;\n}\n\n// Backward-compatible module-level default guard instance, retained for\n// test/core/singleFlightRefresh.test.ts and any caller still importing the\n// bare `refreshOnce`/`resetRefreshGuard` module-level functions. New\n// wiring (rest/interceptors.ts, grpc/callWithRefresh.ts) MUST use a\n// per-session guard from `createRefreshGuard()` instead (see\n// SharedSession.refreshGuard).\nconst defaultGuard = createRefreshGuard() as ResettableRefreshGuard;\n\n/**\n * Ensures at most one `doRefresh()` call is in flight at a time, backed by\n * the single module-level default guard instance. Concurrent callers share\n * the same in-flight Promise; after it settles, a subsequent call invokes\n * `doRefresh` again.\n *\n * @deprecated for new wiring — use a per-instance guard from\n * `createRefreshGuard()` instead (D-13/CR-02). Retained for backward\n * compatibility.\n */\nexport function refreshOnce(doRefresh: () => Promise<void>): Promise<void> {\n return defaultGuard(doRefresh);\n}\n\n/** Test-only helper to reset the module-level default guard between test cases. @internal */\nexport function resetRefreshGuard(): void {\n defaultGuard.__reset();\n}\n","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\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 * 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 /** 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","// 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 /**\n * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`\n * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config\n * when the UUID was supplied, then updated from the access-token `tenant_id`\n * claim after each successful login/refresh (Node persona only — the browser\n * cannot read the httpOnly access-token cookie).\n */\n resolvedTenantId: string | undefined;\n /**\n * Resolved organization UUID used to build the `refresh` body. Seeded from\n * `orgId` config, then updated from the access-token `org_id` claim after a\n * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.\n */\n resolvedOrgId: string | undefined;\n /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */\n csrfToken: string | undefined;\n /** Set true once a successful login/verifyMfa has completed. */\n authenticated = false;\n /**\n * Per-instance single-flight refresh guard (CR-02, D-13). Shared across\n * this session's REST and gRPC transports (rest/interceptors.ts,\n * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but\n * NEVER shared with a different SharedSession/NodeSession instance.\n *\n * @internal SDK-internal transport wiring, not intended to be invoked\n * directly by SDK consumers — refreshes are driven automatically by the\n * response interceptor (rest) or `callWithRefresh` (grpc).\n */\n readonly refreshGuard: RefreshGuard;\n\n constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string) {\n this.axios = axiosInstance;\n this.baseUrl = options.baseUrl;\n this.tenantHeaderValue = tenantHeaderValue;\n this.tenantId = options.tenantId;\n this.tenantSlug = options.tenantSlug;\n this.orgId = options.orgId;\n this.orgSlug = options.orgSlug;\n // 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 maybeBuildHttpsAgent(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): unknown {\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 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 — require lazily so this branch never executes\n // (and never needs to resolve) in a browser bundle.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const https = require('node:https') as typeof import('node:https');\n return new https.Agent({\n ...(customCa ? { ca: customCa } : {}),\n // rejectUnauthorized is intentionally left at its secure default (true).\n ...(identity ? { cert: identity.cert, key: identity.key.expose() } : {}),\n });\n}\n\n/** Build the axios instance + SharedSession for an AxiamClient (D-13/D-25). */\nexport function createSession(options: AxiamClientOptions): SharedSession {\n const tenantHeaderValue = resolveTenantHeaderValue(options);\n\n // customCa is validated (PEM-shape) even when running in an environment\n // that will end up ignoring it (browser), so construction fails fast and\n // consistently across personas (§6).\n if (options.customCa !== undefined && !options.customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n\n // The mTLS client identity (§6.1) is likewise validated on every persona so\n // a one-of/bad-PEM misconfiguration throws identically in browser and Node,\n // even though only Node presents the certificate.\n const clientIdentity = resolveClientIdentity(options);\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);\n\n const axiosInstance = axios.create({\n baseURL: options.baseUrl,\n withCredentials: true,\n timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n ...(httpsAgent ? { httpsAgent } : {}),\n });\n\n const session = new SharedSession(options, axiosInstance, tenantHeaderValue);\n\n // Attach X-Tenant-ID to every outgoing request (§5.2) — except when the\n // request targets a host other than our own origin (host-isolation, 3A).\n axiosInstance.interceptors.request.use((config) => {\n if (session.isForeignHost(config.url)) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['X-Tenant-ID'] = session.tenantHeaderValue;\n return config;\n });\n\n return session;\n}\n","// Axios interceptors: CSRF forwarding (D-05, §3) + reactive single-flight\n// 401->refresh (D-07, §9). Mirrors frontend/src/lib/api.ts's proven pattern,\n// generalized off the app store: this is a library, not an app — refresh\n// failure clears session auth state and rejects; it never redirects\n// (no window.location access anywhere in this module).\n\nimport type { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport { csrfHeaderForMethod, mapHttpStatusToError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Endpoints that must never trigger a silent refresh (§9.3, §12.3 rule 3).\n *\n * Two groups:\n * - the refresh endpoint itself plus login/logout — not\n * authenticated-session-continuation calls, so refreshing would only build\n * an infinite loop;\n * - the `/oauth2/*` endpoints — they authenticate the *client* with\n * `client_id`/`client_secret`, not the user session. A `401` there is a\n * client-credential failure, not a session expiry, so retrying after a\n * session refresh cannot help and MUST NOT enter the §9 guard\n * (CONTRACT.md §12.3 rule 3). `oidcRefresh` reaches the §9 guard through\n * its own explicit call path instead (`OidcClient.oidcRefresh`).\n */\nexport const SKIP_REFRESH = [\n '/api/v1/auth/refresh',\n '/api/v1/auth/login',\n '/api/v1/auth/logout',\n '/oauth2/token',\n '/oauth2/introspect',\n '/oauth2/revoke',\n];\n\ntype RetryableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean };\n\n/**\n * Request interceptor: forwards the axiam_csrf cookie as X-CSRF-Token on\n * state-changing methods (POST/PUT/PATCH/DELETE) per §3/D-05.\n *\n * Browser: reads `document.cookie` directly (guarded by `typeof document !==\n * 'undefined'`). Node: reads the session's csrfToken store, populated by the\n * Node persona's cookie-jar read (17-03) — left undefined here since no jar\n * exists in the browser-only REST core built by this plan.\n */\nexport function installCsrfInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {\n // Host-isolation (3A): never echo the CSRF token to an off-origin host.\n if (session.isForeignHost(config.url)) {\n return config;\n }\n const method = (config.method ?? 'get').toLowerCase();\n const cookieString = typeof document !== 'undefined' ? document.cookie : '';\n const csrfToken =\n typeof document !== 'undefined' ? csrfHeaderForMethod(method, cookieString) : csrfHeaderForMethod(method, session.csrfToken ? `axiam_csrf=${session.csrfToken}` : '');\n\n if (csrfToken) {\n config.headers = config.headers ?? {};\n config.headers['X-CSRF-Token'] = csrfToken;\n }\n return config;\n });\n}\n\n/**\n * Response interceptor: on 401 (when authenticated, not a SKIP_REFRESH url,\n * not already retried) performs a reactive single-flight refresh and replays\n * the original request (D-07/§9). Non-2xx responses are mapped through\n * core's mapHttpStatusToError.\n */\nexport function installRefreshInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.response.use(\n (response) => response,\n async (error: AxiosError) => {\n const originalRequest = error.config as RetryableRequestConfig | undefined;\n\n if (!originalRequest || !error.response) {\n // No response at all (network/timeout) — surface as NetworkError below via caller mapping.\n return Promise.reject(error);\n }\n\n const status = error.response.status;\n const url = originalRequest.url ?? '';\n const isSkipRefresh = SKIP_REFRESH.some((skipUrl) => url.includes(skipUrl));\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated) {\n // CQ-F32: set _retry BEFORE the refresh call so a 401 on the replayed\n // request cannot trigger a second refresh cycle.\n originalRequest._retry = true;\n\n try {\n await session.refreshGuard(async () => {\n await session.axios.post('/api/v1/auth/refresh', session.buildRefreshBody());\n // H8 fix: resync the Node persona's cached access token + CSRF\n // token after a reactive refresh too — see the matching fix\n // and comment on rest/auth.ts's explicit refresh(). Without\n // this the replayed request below (and every request after it)\n // echoes a stale X-CSRF-Token and 403s.\n await session.onAuthenticated?.();\n });\n return axiosInstance(originalRequest);\n } catch (refreshError) {\n session.authenticated = false;\n session.csrfToken = undefined;\n return Promise.reject(\n mapHttpStatusToError(401, 'session refresh failed; re-authentication required', {\n cause: refreshError,\n }),\n );\n }\n }\n\n if (status === 401 && isSkipRefresh) {\n // url + body are forwarded so the mapper can apply the\n // endpoint-qualified §2 row: a 401 from /oauth2/introspect or\n // /oauth2/revoke carrying an OAuth2ErrorResponse body becomes an\n // OAuthProtocolError rather than a bare AuthError (§12.3 rule 3).\n return Promise.reject(\n mapHttpStatusToError(401, 'authentication failed', {\n url,\n body: error.response.data,\n cause: error,\n }),\n );\n }\n\n return Promise.reject(error);\n },\n );\n}\n\n/** Install both the CSRF and reactive single-flight refresh interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n}\n","// login/verifyMfa/refresh/logout over REST (D-18, §1).\n//\n// Mirrors the Rust SDK's src/rest/auth.rs's request/response shapes exactly\n// (mirror only, no server crate dependency). Tokens are delivered\n// exclusively via Set-Cookie — LoginResult deliberately carries no session\n// token field anywhere in the public API (T-17-07).\n\nimport { mapHttpStatusToError, NetworkError, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n RefreshSuccessResponseWire,\n} from './types.js';\n\nconst LOGIN_PATH = '/api/v1/auth/login';\nconst MFA_VERIFY_PATH = '/api/v1/auth/mfa/verify';\nconst REFRESH_PATH = '/api/v1/auth/refresh';\nconst LOGOUT_PATH = '/api/v1/auth/logout';\n\ninterface MfaVerifyRequestBody {\n challenge_token: string;\n totp_code: string;\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire): LoginResult {\n return {\n status: 'authenticated',\n user: { id: wire.user.id, username: wire.user.username, email: wire.user.email },\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\nfunction mfaRequiredToResult(wire: MfaRequiredResponseWire): LoginResult {\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n}\n\nfunction extractErrorMessage(err: unknown): string {\n if (err && typeof err === 'object' && 'message' in err && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message;\n }\n return 'request failed';\n}\n\n/**\n * `POST /api/v1/auth/login` (§1).\n *\n * On a 200 response returns the authenticated branch of the LoginResult\n * discriminated union; on the MFA-required response (202) returns the\n * mfa_required branch (mfaToken sourced from the wire challenge_token).\n */\nexport async function login(client: AxiamClient, email: string, password: string): Promise<LoginResult> {\n // The server resolves the workspace from the login body (org + tenant), not\n // the X-Tenant-ID header, so tenant/org context must travel here (§5).\n const body = client.session.buildLoginBody(email, password);\n\n try {\n // axios treats any 2xx (including 202 MFA-required) as a resolved\n // response, not a thrown error — branch on the actual status here.\n const response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n LOGIN_PATH,\n body,\n );\n if (response.status === 202) {\n return mfaRequiredToResult(response.data as MfaRequiredResponseWire);\n }\n client.session.authenticated = true;\n // CR-01/D-05: sync the Node persona's csrfToken (and cached access token)\n // from the jar now that the session cookie(s) have landed. No-op for the\n // browser SharedSession, which has no onAuthenticated implementation.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data as LoginSuccessResponseWire);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'login failed', {\n cause: err,\n });\n }\n throw new NetworkError('login request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/mfa/verify` (§1).\n *\n * Completes the two-phase flow started by login() when status was\n * 'mfa_required', using the caller-supplied mfaToken (the challenge token\n * returned from that prior login() call).\n */\nexport async function verifyMfa(client: AxiamClient, mfaToken: string, code: string): Promise<LoginResult> {\n const body: MfaVerifyRequestBody = { challenge_token: mfaToken, totp_code: code };\n\n try {\n const response = await client.session.axios.post<LoginSuccessResponseWire>(MFA_VERIFY_PATH, body);\n client.session.authenticated = true;\n // CR-01/D-05: same post-authentication sync as login()'s 200 branch.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'verifyMfa failed', {\n cause: err,\n });\n }\n throw new NetworkError('verifyMfa request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/refresh` (§1).\n *\n * Callers typically do not invoke this directly — the response interceptor\n * (interceptors.ts) drives it reactively via the single-flight guard on a\n * 401 (D-07). Exposed as a public method for explicit proactive refresh.\n */\nexport async function refresh(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, client.session.buildRefreshBody());\n // H8 fix (SDK bench harness validation): a successful refresh rotates\n // the `axiam_csrf` cookie (new random token, CONTRACT.md §3) the same\n // way login does, but — unlike login/verifyMfa just below, which both\n // call `onAuthenticated?.()` — this path never resynced the Node\n // persona's in-memory `session.csrfToken` (only NodeSession.doRefresh\n // did that, and doRefresh is wired to gRPC's callWithRefresh only, never\n // to this REST path). Every REST call after the FIRST refresh() then\n // echoed a now-stale X-CSRF-Token and failed with 403 \"CSRF validation\n // failed\" — refresh() effectively broke the session after one use.\n // `onAuthenticated` is exactly the right hook to reuse: same\n // access/csrf resync as login, it's a no-op on the browser persona\n // (undefined there), and Node's implementation is idempotent.\n await client.session.onAuthenticated?.();\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n // §9.3: 401 on the refresh call itself is AuthError, no retry loop.\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'refresh failed', {\n cause: err,\n });\n }\n throw new NetworkError('refresh request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/logout` (§1).\n *\n * Clears session csrf/auth state regardless of the response outcome once\n * the request has been sent successfully.\n */\nexport async function logout(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post(LOGOUT_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'logout failed', {\n cause: err,\n });\n }\n throw new NetworkError('logout request failed', sanitizeAxiosError(err));\n } finally {\n client.session.authenticated = false;\n client.session.csrfToken = undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// axios error helpers (kept local — core stays dependency-free of axios)\n// ---------------------------------------------------------------------------\n\nfunction extractAxiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number } }).response;\n return response?.status;\n }\n return undefined;\n}\n\nfunction extractAxiosData<T>(err: unknown): T | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { data?: T } }).response;\n return response?.data;\n }\n return undefined;\n}\n","// checkAccess/can/batchCheck over REST (D-08, FND-04, §1).\n//\n// Mirrors the Rust SDK's src/rest/authz.rs and\n// crates/axiam-api-rest/src/handlers/authz_check.rs exactly. tenant_id is\n// never sent in the body — the server derives it from the JWT (§5); the SDK\n// only sends X-Tenant-ID (already attached by session.ts's request\n// interceptor on every call). No client-side cache (D-08) — plain stateless\n// async functions.\n\nimport { mapHttpStatusToError, NetworkError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n AccessCheck,\n AccessDecision,\n BatchCheckAccessBodyWire,\n BatchCheckAccessResponseWire,\n CheckAccessBodyWire,\n CheckAccessResponseWire,\n} from './types.js';\n\nconst CHECK_PATH = '/api/v1/authz/check';\nconst BATCH_CHECK_PATH = '/api/v1/authz/check/batch';\n\nfunction toWireBody(check: AccessCheck): CheckAccessBodyWire {\n return {\n action: check.action,\n resource_id: check.resourceId,\n scope: check.scope,\n subject_id: check.subjectId,\n };\n}\n\nfunction fromWireDecision(wire: CheckAccessResponseWire): AccessDecision {\n return { allowed: wire.allowed, reason: wire.reason };\n}\n\n/**\n * `POST /api/v1/authz/check` (§1, FND-04).\n *\n * A 403 authz denial (server-side error, distinct from the `allowed: false`\n * decision the endpoint itself returns) is mapped to AuthzError, not treated\n * as a transport failure.\n */\nexport async function checkAccess(client: AxiamClient, check: AccessCheck): Promise<AccessDecision> {\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n return fromWireDecision(response.data);\n } catch (err) {\n throw mapAuthzError(err, check.action, check.resourceId);\n }\n}\n\n/**\n * `can` — alias for checkAccess targeting browser/UI scenarios (§1 note),\n * returning just the boolean `allowed` outcome.\n */\nexport async function can(client: AxiamClient, action: string, resourceId: string, scope?: string): Promise<boolean> {\n const decision = await checkAccess(client, { action, resourceId, scope });\n return decision.allowed;\n}\n\n/**\n * `POST /api/v1/authz/check/batch` (§1). Results are returned in the same\n * order as the input `checks` array (server-guaranteed ordering).\n */\nexport async function batchCheck(client: AxiamClient, checks: AccessCheck[]): Promise<AccessDecision[]> {\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n throw mapAuthzError(err);\n }\n}\n\nfunction mapAuthzError(err: unknown, action?: string, resourceId?: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: { message?: string } } }).response;\n if (response?.status !== undefined) {\n if (response.status === 403) {\n // Body (response.data) carries the server's own action/resource_id\n // for the denial (structured 403 body) — preferred by the mapper\n // over the call-args action/resourceId below when present.\n return mapHttpStatusToError(403, response.data?.message ?? 'authorization denied', {\n action,\n resourceId,\n body: response.data,\n });\n }\n return mapHttpStatusToError(response.status, response.data?.message ?? 'authz request failed', {\n action,\n resourceId,\n body: response.data,\n cause: err,\n });\n }\n }\n return new NetworkError('authz request failed', err);\n}\n","// AxiamClient — the isomorphic REST + auth core (D-01/D-25).\n//\n// Constructor validates the required tenant (§5), builds the SharedSession\n// (D-13), and installs the CSRF + reactive single-flight refresh\n// interceptors (D-05/D-07). REST method implementations (login/verifyMfa/\n// refresh/logout/checkAccess/can/batchCheck) are added by Task 2's\n// auth.ts/authz.ts, which extend this class's prototype.\n\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as authzMethods from './authz.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\n\n/**\n * The main entry point for the AXIAM TypeScript/JavaScript SDK — an\n * isomorphic (browser + Node) REST client for authentication and\n * authorization against an AXIAM server.\n *\n * @remarks\n * `AxiamClient` implements the SDK's cross-language behavioral contract\n * (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/\n * `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the\n * three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic\n * CSRF forwarding (§3), the required tenant context (§5), and a per-instance\n * single-flight refresh guard that de-duplicates concurrent token refreshes\n * (§9).\n *\n * A `tenantSlug` or `tenantId` is mandatory at construction — there is no\n * default tenant, and AXIAM is a multi-tenant system where every\n * authenticated call is scoped by the `X-Tenant-ID` header this client\n * injects on every request (§5). Session tokens never appear as a return\n * value or public property anywhere on this class: they arrive exclusively\n * via `httpOnly` cookies set by the server.\n *\n * @example\n * ```ts\n * const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });\n *\n * const result = await client.login('user@example.com', 'hunter2');\n * if (result.status === 'mfa_required') {\n * await client.verifyMfa(result.mfaToken, '123456');\n * }\n *\n * const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });\n * if (!decision.allowed) {\n * throw new Error(decision.reason ?? 'access denied');\n * }\n * ```\n */\nexport class AxiamClient {\n /** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */\n readonly session: SharedSession;\n\n /**\n * @param options client configuration (§5/§6).\n * @param session optional pre-built session to adopt instead of the default\n * browser `SharedSession`. This is the injection point for the Node\n * persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie\n * jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`\n * from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it\n * is adopted here, so httpOnly login/refresh cookies persist. When omitted\n * the browser `SharedSession` is built by default — the Node modules are\n * NEVER statically imported from this browser-safe module, so a `/rest`\n * browser bundle keeps pulling zero Node dependencies (SC#1).\n */\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n }\n\n /** `POST /api/v1/auth/login` (§1, D-18). */\n login(email: string, password: string): Promise<LoginResult> {\n return authMethods.login(this, email, password);\n }\n\n /** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */\n verifyMfa(mfaToken: string, code: string): Promise<LoginResult> {\n return authMethods.verifyMfa(this, mfaToken, code);\n }\n\n /** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */\n refresh(): Promise<void> {\n return authMethods.refresh(this);\n }\n\n /** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */\n logout(): Promise<void> {\n return authMethods.logout(this);\n }\n\n /** `POST /api/v1/authz/check` (§1, FND-04). */\n checkAccess(check: AccessCheck): Promise<AccessDecision> {\n return authzMethods.checkAccess(this, check);\n }\n\n /** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */\n can(action: string, resourceId: string, scope?: string): Promise<boolean> {\n return authzMethods.can(this, action, resourceId, scope);\n }\n\n /** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */\n batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]> {\n return authzMethods.batchCheck(this, checks);\n }\n}\n","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { wrapper } from 'axios-cookiejar-support';\nimport type { AxiosInstance } from 'axios';\n\n/** The `axiam_access` cookie name (httpOnly, path `/`). */\nexport const ACCESS_COOKIE = 'axiam_access';\n/** The `axiam_refresh` cookie name (httpOnly, path-scoped to `/api/v1/auth/refresh`). */\nexport const REFRESH_COOKIE = 'axiam_refresh';\n/** The `axiam_csrf` cookie name (JS-readable, path `/`). */\nexport const CSRF_COOKIE = 'axiam_csrf';\n\n/** Construct a fresh, per-client-instance cookie jar (§4 — never process-global). */\nexport function createJar(): CookieJar {\n return new CookieJar();\n}\n\n/**\n * Wrap an axios instance with `axios-cookiejar-support` so the jar persists\n * `Set-Cookie` responses across requests and replays them on subsequent\n * requests to the same origin/path (§4). Mutates and returns the same\n * instance (matches `axios-cookiejar-support`'s documented in-place wrap).\n */\nexport function wrapAxios(instance: AxiosInstance, jar: CookieJar): AxiosInstance {\n const wrapped = wrapper(instance);\n wrapped.defaults.jar = jar;\n return wrapped;\n}\n\n/**\n * Read a single cookie's value out of the jar by name, for the given URL.\n * This is the ONLY token-source path (RESEARCH.md Area 3 — no JSON-body\n * fallback exists on the wire).\n */\nexport async function extractCookieValue(\n jar: CookieJar,\n url: string,\n name: string,\n): Promise<string | undefined> {\n const cookies = await jar.getCookies(url);\n return cookies.find((c) => c.key === name)?.value;\n}\n","// TokenManager — Node-persona token state (CONTRACT.md §7, D-09/D-11/D-26).\n//\n// Tokens are read from the tough-cookie jar by name (the ONLY token-source\n// path — login/refresh response bodies carry no token fields; see\n// RESEARCH.md Area 3) and wrapped in Sensitive<T> immediately. A\n// synchronous, non-blocking `cachedAccessToken()` fast-path is provided for\n// the grpc-js interceptor's `start()`, which cannot await (Pitfall 3) —\n// mirrors the Rust SDK's src/token/manager.rs::cached_access_token exactly.\n\nimport type { CookieJar } from 'tough-cookie';\nimport { Sensitive } from '../core/index.js';\nimport { ACCESS_COOKIE, REFRESH_COOKIE, extractCookieValue } from './cookieJar.js';\n\n/** Path the server scopes the `axiam_refresh` cookie to (mirrors csrf.rs). */\nconst REFRESH_COOKIE_PATH = '/api/v1/auth/refresh';\n\n/** Tracks the access/refresh token pair for a Node session, kept in sync with the cookie jar after each REST call/refresh. */\nexport class TokenManager {\n readonly #jar: CookieJar;\n readonly #baseUrl: string;\n #tenantId: string | undefined;\n /**\n * Non-blocking cached copy of the current access token, kept in sync via\n * `syncFromJar()` after each REST call/refresh. Read via\n * `cachedAccessToken()` without ever touching the jar's async API — this\n * is the fast-path the grpc-js interceptor's synchronous `start()` needs\n * (Pitfall 3).\n */\n #cachedAccess: Sensitive<string> | null = null;\n\n constructor(jar: CookieJar, baseUrl: string, tenantId?: string) {\n this.#jar = jar;\n this.#baseUrl = baseUrl;\n this.#tenantId = tenantId;\n }\n\n /**\n * Synchronous, best-effort read of the last-known access token. Returns\n * `null` if no token has been cached yet (no request/refresh has\n * completed since construction, or `syncFromJar()` was never called).\n */\n cachedAccessToken(): Sensitive<string> | null {\n return this.#cachedAccess;\n }\n\n /**\n * Async read of the current `axiam_refresh` cookie value from the jar,\n * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL\n * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible\n * at the bare base URL).\n */\n async refreshTokenValue(): Promise<Sensitive<string> | null> {\n const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);\n return value === undefined ? null : new Sensitive(value);\n }\n\n /**\n * Refresh the in-memory cached access token from the jar. Call this after\n * every REST request/refresh so the synchronous gRPC-interceptor fast-path\n * (`cachedAccessToken()`) stays current (Pitfall 3).\n */\n async syncFromJar(): Promise<void> {\n const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);\n this.#cachedAccess = value === undefined ? null : new Sensitive(value);\n }\n\n /** The resolved tenant identifier (slug or UUID form), if known. */\n tenantId(): string | undefined {\n return this.#tenantId;\n }\n\n /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */\n setTenantId(tenantId: string): void {\n this.#tenantId = tenantId;\n }\n\n /**\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 type { 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\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /** Verify `token` against the cached JWKS (EdDSA only) and return its claims; rejects any invalid/expired/wrong-algorithm token. */\n verifyAccessToken(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * 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(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Explicit algorithm allowlist — never trust the token's own `alg`\n // header; defense against algorithm-confusion attacks (T-17-14).\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n\n 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 * 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, 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 wrapAxios(base.axios, jar);\n\n const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);\n const jwksVerifier = createVerifier(options.baseUrl);\n\n return new NodeSession(options, base, tokenManager, jwksVerifier, jar);\n}\n\n/**\n * Build an `AxiamClient` wired to the Node persona (SDK-Q05). This is the Node\n * counterpart to `new AxiamClient(options)` (which builds the browser\n * `SharedSession` with no cookie jar): it constructs a `NodeSession`\n * (tough-cookie jar + CSRF/refresh token sync) and adopts it via the\n * `AxiamClient` session-injection constructor, so httpOnly `Set-Cookie` tokens\n * from login/refresh persist and every post-login REST call authenticates\n * correctly under Node.\n *\n * Lives in this Node-only module (reachable via the `axiam-sdk/node` and\n * `axiam-sdk/grpc` subpaths) rather than in the browser-safe `axiam-sdk/rest`\n * entry, so browser bundles never pull in tough-cookie/jose/node:https (SC#1).\n * The returned client shares the single session with any `AuthzGrpcClient`\n * built from the same `NodeSession`.\n */\nexport function createNodeClient(options: AxiamClientOptions): AxiamClient {\n return new AxiamClient(options, createNodeSession(options));\n}\n","// PKCE + CSPRNG primitives for the OIDC relying-party flow\n// (CONTRACT.md §12.1 \"oidc_begin inputs and construction\", RFC 7636).\n//\n// Node's `node:crypto` covers everything needed — CSPRNG, SHA-256 and\n// base64url — so §12 adds NO new runtime dependency (plan §6 criterion 4).\n// This module is deliberately tiny, pure and synchronous: `oidc_begin`\n// performs no network I/O (§12.1), and every value here is derived locally.\n//\n// S256 ONLY. `plain` is not implemented, not reachable, and not configurable:\n// there is no code path in this SDK that can emit\n// `code_challenge_method=plain`.\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The only PKCE code-challenge method this SDK emits (RFC 7636 §4.2,\n * CONTRACT.md §12.1 rule 3). `plain` is intentionally absent.\n */\nexport const CODE_CHALLENGE_METHOD_S256 = 'S256';\n\n/**\n * Entropy, in bytes, of a generated `state` / `nonce` / `code_verifier`.\n *\n * §12.1 rule 1 requires at least 16 bytes (128 bits) and RECOMMENDS 32;\n * rule 2 RECOMMENDS 32 bytes for the verifier, which base64url-encodes to\n * exactly 43 characters — the minimum RFC 7636 §4.1 length, drawn only from\n * the unreserved set `[A-Za-z0-9-._~]`.\n */\nexport const CSPRNG_BYTES = 32;\n\n/**\n * Generate a URL-safe random token: `bytes` CSPRNG bytes, base64url-encoded\n * **without** padding (RFC 4648 §5 — Node's `'base64url'` encoding never\n * emits `=`).\n *\n * Used for both `state` and `nonce`, which §12.3 rule 2 classes as\n * **non-secret**: they are returned as plain strings, are echoed through the\n * browser's address bar by construction, and are safe to log.\n */\nexport function randomUrlSafeToken(bytes: number = CSPRNG_BYTES): string {\n return randomBytes(bytes).toString('base64url');\n}\n\n/**\n * Generate a fresh PKCE `code_verifier` (RFC 7636 §4.1): 32 CSPRNG bytes\n * base64url-encoded without padding, i.e. 43 characters from the unreserved\n * set.\n *\n * Returned already wrapped in {@link Sensitive} — §12.5 makes the verifier\n * secret **for its whole lifetime**, including while it sits in the\n * `AuthorizationRequest` handed back to the caller and in any\n * `OidcStateStore` entry.\n */\nexport function generateCodeVerifier(): Sensitive<string> {\n return new Sensitive(randomUrlSafeToken(CSPRNG_BYTES));\n}\n\n/**\n * Derive the PKCE `code_challenge` from a verifier:\n * `BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))`, unpadded\n * (RFC 7636 §4.2, CONTRACT.md §12.1 rule 3).\n *\n * The verifier is hashed as ASCII exactly as the RFC specifies. Verified\n * against the RFC 7636 Appendix B test vector in\n * `test/node/oidcPkce.test.ts`, which every SDK must carry (§12.1 rule 3).\n *\n * The challenge is a one-way digest and is **not** secret — it travels in the\n * authorization URL — so it is returned as a plain string.\n */\nexport function computeCodeChallenge(codeVerifier: string): string {\n return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');\n}\n","// OIDC / SSO relying-party helpers — CONTRACT.md §12 (contract 1.4).\n//\n// The nine canonical §12 operations, under the exact §12.2 TypeScript names:\n// oidcDiscover, oidcBegin, oidcExchange, oidcRefresh, loginClientCredentials,\n// introspect, revoke, ssoStart, ssoComplete.\n//\n// ── Why a separate class instead of methods on AxiamClient ─────────────────\n// `AxiamClient` lives in the browser-safe `src/rest/` core, and CI's SC#1\n// bundle-and-grep gate proves a `/rest` browser bundle pulls in zero Node-only\n// code. These helpers need `node:crypto` (CSPRNG + SHA-256 for PKCE) and\n// `jose` (ID-token verification), so hanging them off `AxiamClient` would drag\n// both into every browser bundle. They therefore live on a Node-only\n// `OidcClient` reached through the `axiam-sdk/node` subpath — the same shape\n// the repo already uses for the gRPC-only operations (`AuthzGrpcClient`,\n// `UserInfoGrpcClient`). §12 fixes the *method names*, not which object hosts\n// them, so this is conformant; an SDK without a browser-bundle constraint\n// (Rust, Python, Go, Java, Kotlin, C#, PHP) SHOULD put the nine methods\n// directly on its existing client, as the plan's T2–T8 items say.\n//\n// Everything else is reuse, not reimplementation (§12 forbids forking):\n// * transport + §2 error mapping + §3 CSRF + §4 cookie jar + §5 tenant\n// header + §6 TLS → the SharedSession/NodeSession axios instance;\n// * §9 single-flight refresh → session.refreshGuard;\n// * §12.4 signature verification → node/jwks.ts's verifier;\n// * §7/§12.5 redaction → core/sensitive.ts.\n\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport {\n AuthError,\n AxiamError,\n mapHttpStatusToError,\n NetworkError,\n sanitizeAxiosError,\n Sensitive,\n} from '../core/index.js';\nimport type { SharedSession } from '../rest/session.js';\nimport { createJwksVerifier, type JwksVerifier } from './jwks.js';\nimport type { IdTokenClaims } from './oidcIdToken.js';\nimport {\n CODE_CHALLENGE_METHOD_S256,\n computeCodeChallenge,\n generateCodeVerifier,\n randomUrlSafeToken,\n} from './oidcPkce.js';\nimport type {\n AuthorizationRequest,\n IntrospectParams,\n IntrospectionResponseWire,\n IntrospectionResult,\n LoginClientCredentialsParams,\n OidcBeginParams,\n OidcConfiguration,\n OidcExchangeParams,\n OidcRefreshParams,\n OidcStartResponseWire,\n OidcTokenSet,\n RevokeParams,\n SsoCompleteParams,\n SsoCompleteResult,\n SsoLoginSuccessResponseWire,\n SsoStartParams,\n SsoStartResult,\n TokenResponseWire,\n} from './oidcTypes.js';\n\n/** Path of the OIDC discovery document, relative to the client base URL. */\nexport const DISCOVERY_PATH = '/.well-known/openid-configuration';\n\n/** Path of the federation SSO step-1 endpoint. */\nexport const SSO_START_PATH = '/api/v1/auth/federation/oidc/start';\n\n/** Path of the federation SSO step-2 (callback) endpoint. */\nexport const SSO_CALLBACK_PATH = '/api/v1/auth/federation/oidc/callback';\n\n/**\n * Minimum — and default — discovery-cache TTL. CONTRACT.md §12.3 rule 6 sets\n * a floor of 5 minutes; a smaller configured value is raised to it.\n */\nexport const MIN_DISCOVERY_TTL_MS = 300_000;\n\n/** The `openid` scope, which every authorization request must carry (§12.1 rule 4). */\nconst OPENID_SCOPE = 'openid';\n\n/**\n * The eight query parameters `oidcBegin` owns (§12.1 rule 5). Caller-supplied\n * `extraParams` may add to the authorization request but never override these.\n */\nconst RESERVED_AUTHORIZE_PARAMS = new Set([\n 'response_type',\n 'client_id',\n 'redirect_uri',\n 'scope',\n 'state',\n 'nonce',\n 'code_challenge',\n 'code_challenge_method',\n]);\n\n/** Shape of a UUID, used to reject a slug where §12.3 rule 4 requires a UUID. */\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/** Configuration for {@link OidcClient}. */\nexport interface OidcClientOptions {\n /**\n * The relying party's OAuth2 `client_id`. Used on every grant and matched\n * against the ID token's `aud`/`azp` (§12.4 rule 4).\n */\n clientId: string;\n /**\n * The `client_secret` for a confidential client, held behind\n * {@link Sensitive} (§12.5). Omit for a public client — then it is never\n * added to a form body (§12.1 \"MUST omit rather than send empty/null\").\n *\n * `introspect` and `revoke` REQUIRE it: the server marks `client_secret`\n * non-nullable on both, so a public client cannot call them (§12.1 note 4).\n */\n clientSecret?: Sensitive<string> | string;\n /**\n * Default tenant UUID for the `tenant_id` query parameter the token,\n * introspection and revocation endpoints require. Falls back to the\n * session's configured `tenantId` when it was built in UUID form; a\n * slug-only client must pass `tenantId` per call (§12.3 rule 4).\n */\n tenantId?: string;\n /**\n * Discovery-cache TTL in milliseconds. Defaults to (and is floored at)\n * {@link MIN_DISCOVERY_TTL_MS} — §12.3 rule 6 forbids a TTL under 5 minutes.\n */\n discoveryTtlMs?: number;\n /**\n * Permitted ID-token clock skew in seconds. Defaults to 60 and is clamped to\n * 60 — §12.4 rule 5 forbids configuring it higher.\n */\n clockSkewSec?: number;\n}\n\n/** A cached discovery document together with its expiry. */\ninterface CachedDiscovery {\n document: OidcConfiguration;\n expiresAt: number;\n}\n\n/**\n * Origin-keyed discovery cache with single-flight fetching\n * (CONTRACT.md §12.3 rule 6).\n *\n * @remarks\n * The key is the **normalized scheme + host + port** of the base URL the\n * document was fetched from, so a document fetched from one origin can never\n * be served for another (cross-issuer cache poisoning). The cache is *not*\n * keyed on the tenant, and — because each {@link OidcClient} owns its own\n * instance — it is not shared across tenants either, nor process-global.\n *\n * Single-flight uses the same mechanism §9 prescribes for TypeScript: a shared\n * `Promise` held in a map for the duration of the fetch, cleared on settle, so\n * N concurrent callers produce exactly one HTTP request and all receive the\n * same document (or the same failure).\n *\n * @internal\n */\nclass DiscoveryCache {\n readonly #documents = new Map<string, CachedDiscovery>();\n readonly #inFlight = new Map<string, Promise<OidcConfiguration>>();\n readonly #ttlMs: number;\n\n constructor(ttlMs: number) {\n this.#ttlMs = Math.max(ttlMs, MIN_DISCOVERY_TTL_MS);\n }\n\n async get(originKey: string, fetcher: () => Promise<OidcConfiguration>): Promise<OidcConfiguration> {\n const cached = this.#documents.get(originKey);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.document;\n }\n\n const pending = this.#inFlight.get(originKey);\n if (pending) {\n return pending;\n }\n\n const fetch = fetcher()\n .then((document) => {\n this.#documents.set(originKey, { document, expiresAt: Date.now() + this.#ttlMs });\n return document;\n })\n .finally(() => {\n this.#inFlight.delete(originKey);\n });\n this.#inFlight.set(originKey, fetch);\n return fetch;\n }\n}\n\n/**\n * Normalize a URL to its cache key: lowercased scheme and host with the port\n * always explicit (§12.3 rule 6). `https://IAM.example.com/` and\n * `https://iam.example.com:443/x` therefore share one key, while\n * `http://iam.example.com` gets its own.\n */\nexport function normalizeOrigin(url: string): string {\n const parsed = new URL(url);\n const scheme = parsed.protocol.replace(/:$/, '').toLowerCase();\n const host = parsed.hostname.toLowerCase();\n const defaultPort = scheme === 'https' ? '443' : scheme === 'http' ? '80' : '';\n const port = parsed.port || defaultPort;\n return `${scheme}://${host}:${port}`;\n}\n\n/** Read a secret that the caller may have supplied wrapped or bare. */\nfunction exposeSecret(value: Sensitive<string> | string): string {\n return typeof value === 'string' ? value : value.expose();\n}\n\n/** Pull the HTTP status off an axios-shaped error, if any. */\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/** Pull the parsed response body off an axios-shaped error, if any. */\nfunction axiosBody(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/** Best-effort human-readable message from a parsed error body. */\nfunction bodyMessage(body: unknown, fallback: string): string {\n if (body && typeof body === 'object') {\n const record = body as Record<string, unknown>;\n if (typeof record.error_description === 'string') {\n return record.error_description;\n }\n if (typeof record.message === 'string') {\n return record.message;\n }\n }\n return fallback;\n}\n\n/**\n * Map any failure from a §12 wire call onto the §2 taxonomy, routing\n * everything through the single `mapHttpStatusToError` source of truth so the\n * endpoint-qualified `OAuthProtocolError` rows apply (§12.3 rule 3).\n *\n * An error that is *already* an `AxiamError` is passed through untouched: the\n * rest/interceptors.ts response interceptor may have mapped it first (it does\n * exactly that for a 401 on an `/oauth2/*` path), and re-mapping would discard\n * the richer error it built.\n */\nfunction mapOidcError(err: unknown, url: string, fallbackMessage: string): AxiamError {\n if (err instanceof AxiamError) {\n return err;\n }\n const status = axiosStatus(err);\n if (status !== undefined) {\n const body = axiosBody(err);\n return mapHttpStatusToError(status, bodyMessage(body, fallbackMessage), { url, body, cause: err });\n }\n return new NetworkError(fallbackMessage, sanitizeAxiosError(err));\n}\n\n/**\n * The OIDC / SSO relying-party client (CONTRACT.md §12).\n *\n * @remarks\n * Build one with {@link createOidcClient}, passing the same session your\n * `AxiamClient` uses so the cookie jar (§4), TLS configuration (§6), tenant\n * header (§5) and single-flight refresh guard (§9) are shared rather than\n * duplicated.\n *\n * **The caller owns the login state.** `oidcBegin` returns `state`, `nonce`\n * and `codeVerifier`; this class stores none of them (§12.3 rule 1). Keep them\n * in your own HTTP session — or use {@link MemoryOidcStateStore} together with\n * the `oidcLoginHandlers` glue from `axiam-sdk/middleware`, which does that\n * bookkeeping for you.\n *\n * @example\n * ```ts\n * const session = createNodeSession({ baseUrl, tenantId });\n * const oidc = createOidcClient(session, { clientId: 'my-app', clientSecret: secret });\n *\n * // 1. redirect the browser\n * const configuration = await oidc.oidcDiscover();\n * const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });\n * // …store request.state / request.nonce / request.codeVerifier in your session…\n * res.redirect(request.url);\n *\n * // 2. on the callback, having checked the returned `state` matches\n * const tokens = await oidc.oidcExchange({\n * code, codeVerifier: request.codeVerifier, nonce: request.nonce, redirectUri,\n * });\n * console.log(tokens.idClaims?.sub); // validated ID-token subject\n * ```\n */\nexport class OidcClient {\n readonly #session: SharedSession;\n readonly #options: OidcClientOptions;\n readonly #discoveryCache: DiscoveryCache;\n /** One verifier per `jwks_uri` — the same node/jwks.ts implementation the §10 middleware uses. */\n readonly #verifiers = new Map<string, JwksVerifier>();\n /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */\n #adoptedCredential: Sensitive<string> | null = null;\n #adoptionInterceptorInstalled = false;\n /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */\n #pendingRefresh: Promise<OidcTokenSet> | null = null;\n\n constructor(session: SharedSession, options: OidcClientOptions) {\n this.#session = session;\n this.#options = options;\n this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);\n }\n\n // -------------------------------------------------------------------------\n // 1. oidcDiscover\n // -------------------------------------------------------------------------\n\n /**\n * `GET /.well-known/openid-configuration` (§12.1) — fetch the OIDC discovery\n * document, cached per origin with a ≥5-minute TTL and single-flight\n * de-duplication of concurrent calls (§12.3 rule 6).\n *\n * The document's own `issuer` is authoritative for ID-token validation and\n * may legitimately differ from `baseUrl` behind a proxy, so a mismatch is\n * never treated as an error.\n */\n async oidcDiscover(): Promise<OidcConfiguration> {\n const originKey = normalizeOrigin(this.#session.baseUrl);\n return this.#discoveryCache.get(originKey, async () => {\n const response = await this.#get<OidcConfiguration>(DISCOVERY_PATH, 'oidc discovery request failed');\n return response.data;\n });\n }\n\n // -------------------------------------------------------------------------\n // 2. oidcBegin\n // -------------------------------------------------------------------------\n\n /**\n * Build an authorization request (§12.1) — **pure local computation, no\n * network I/O**.\n *\n * Generates a 32-byte CSPRNG `state` and `nonce` (base64url, unpadded) and a\n * fresh PKCE verifier/challenge pair using **S256 only** — `plain` is not\n * implemented anywhere in this SDK. The URL is built from the discovery\n * document's `authorization_endpoint` with exactly the eight parameters\n * §12.1 rule 5 mandates, plus any `extraParams` the caller adds.\n *\n * Nothing is stored: persist the returned `state`, `nonce` and\n * `codeVerifier` yourself (§12.3 rule 1).\n *\n * @throws Error when `extraParams` tries to override one of the eight\n * SDK-owned parameters — a programming error, caught at call time.\n */\n oidcBegin(params: OidcBeginParams): AuthorizationRequest {\n const state = randomUrlSafeToken();\n const nonce = randomUrlSafeToken();\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = computeCodeChallenge(codeVerifier.expose());\n\n const scope = normalizeScope(params.scope);\n const target = new URL(params.configuration.authorization_endpoint);\n const query = new URLSearchParams(target.search);\n\n for (const [key, value] of Object.entries(params.extraParams ?? {})) {\n if (RESERVED_AUTHORIZE_PARAMS.has(key)) {\n throw new Error(\n `oidcBegin: extraParams may not override the SDK-owned authorization parameter \"${key}\" (CONTRACT.md §12.1 rule 5).`,\n );\n }\n query.set(key, value);\n }\n\n query.set('response_type', 'code');\n query.set('client_id', this.#options.clientId);\n query.set('redirect_uri', params.redirectUri);\n query.set('scope', scope);\n query.set('state', state);\n query.set('nonce', nonce);\n query.set('code_challenge', codeChallenge);\n query.set('code_challenge_method', CODE_CHALLENGE_METHOD_S256);\n\n // URLSearchParams serializes a space as '+', which is legal in a query\n // string but not RFC 3986 percent-encoding; §12.1 rule 5 asks for the\n // latter, so spaces become %20. Every other character is already\n // percent-encoded correctly by URLSearchParams.\n target.search = query.toString().replace(/\\+/g, '%20');\n\n return { url: target.toString(), state, nonce, codeVerifier };\n }\n\n // -------------------------------------------------------------------------\n // 3. oidcExchange\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=authorization_code` (§12.1) —\n * exchange an authorization code for a token set, validating the returned\n * ID token in full before returning.\n *\n * The `nonce` argument is mandatory: this grant always requests the `openid`\n * scope, so §12.4 rule 6 always applies. If **any** §12.4 rule fails, the\n * whole token set is discarded and `AuthError` is raised with the matching\n * reason code — the access and refresh tokens from the same response are\n * never returned (§12.4 rule 7).\n */\n async oidcExchange(params: OidcExchangeParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'authorization_code');\n form.set('code', params.code);\n form.set('code_verifier', exposeSecret(params.codeVerifier));\n form.set('redirect_uri', params.redirectUri);\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n return this.#toTokenSet(wire, configuration, params.nonce);\n }\n\n // -------------------------------------------------------------------------\n // 4. oidcRefresh\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an\n * {@link OidcTokenSet}, under the §9 single-flight refresh guard.\n *\n * @remarks\n * This is a **distinct operation** from `AxiamClient.refresh()`, which drives\n * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The\n * two are never merged or aliased and neither falls back to the other\n * (§12.1). They do share the session's §9 guard, so at most one refresh of\n * either kind is ever in flight for a session.\n *\n * Concurrent `oidcRefresh` calls collapse into one HTTP request and all\n * receive the same token set — §9 rule 2's result sharing.\n *\n * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;\n * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce\n * in a refresh-issued ID token.\n */\n oidcRefresh(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const existing = this.#pendingRefresh;\n if (existing) {\n return existing;\n }\n const pending = this.#refreshUnderGuard(params);\n this.#pendingRefresh = pending;\n const clear = (): void => {\n if (this.#pendingRefresh === pending) {\n this.#pendingRefresh = null;\n }\n };\n pending.then(clear, clear);\n return pending;\n }\n\n // -------------------------------------------------------------------------\n // 5. loginClientCredentials\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=client_credentials` (§12.1) —\n * service-account machine-to-machine login.\n *\n * Requests no `openid` scope, so the response carries no `id_token`. Pass\n * `adoptAsCredential: true` to additionally use the returned access token as\n * this session's bearer credential for subsequent REST calls (§12.1, a MAY).\n *\n * @throws AuthError when no `clientSecret` is configured — this grant cannot\n * be performed by a public client.\n */\n async loginClientCredentials(params: LoginClientCredentialsParams = {}): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'client_credentials');\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('loginClientCredentials'));\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to this grant (§12.4 rule 6).\n const tokenSet = await this.#toTokenSet(wire, configuration, undefined);\n\n if (params.adoptAsCredential) {\n this.#adoptCredential(tokenSet.accessToken);\n }\n return tokenSet;\n }\n\n // -------------------------------------------------------------------------\n // 6. introspect\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/introspect` (RFC 7662, §12.1) — ask the server whether a\n * token is active and, if so, for its metadata.\n *\n * Requires confidential-client credentials (§12.1 note 4). A `401` here is a\n * *client-credential* failure surfaced as `OAuthProtocolError`; it never\n * enters the §9 refresh guard, because refreshing the user session cannot\n * fix a bad `client_secret` (§12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async introspect(params: IntrospectParams): Promise<IntrospectionResult> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('introspect'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.introspection_endpoint, params.tenantId);\n const response = await this.#postForm<IntrospectionResponseWire>(url, form, 'introspect request failed');\n const wire = response.data;\n return {\n active: wire.active,\n ...(wire.sub != null ? { sub: wire.sub } : {}),\n ...(wire.client_id != null ? { clientId: wire.client_id } : {}),\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.token_type != null ? { tokenType: wire.token_type } : {}),\n ...(wire.exp != null ? { exp: wire.exp } : {}),\n ...(wire.iat != null ? { iat: wire.iat } : {}),\n };\n }\n\n // -------------------------------------------------------------------------\n // 7. revoke\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/revoke` (RFC 7009, §12.1) — revoke an access or refresh\n * token. Returns nothing.\n *\n * Per RFC 7009 the server answers `200` for unknown, expired and\n * already-revoked tokens alike, so revocation is **idempotent**: any `200`\n * is success and no error is raised for a token the server has never seen.\n * Only a `401` (client authentication failed) is an error, surfaced as\n * `OAuthProtocolError` (§12.1 note 5, §12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async revoke(params: RevokeParams): Promise<void> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('revoke'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.revocation_endpoint, params.tenantId);\n await this.#postForm<void>(url, form, 'revoke request failed');\n }\n\n // -------------------------------------------------------------------------\n // 8. ssoStart\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/start` (§12.1) — step 1 of first-time\n * SSO against an **upstream** IdP. No JWT required.\n *\n * One tenant form (`tenantId` or `tenantSlug`) and one org form (`orgId` or\n * `orgSlug`) must be resolvable, from the arguments or from the session's\n * construction options (§5.1). Redirect the browser to the returned\n * `authorizeUrl` and round-trip `state` back into {@link ssoComplete}\n * unmodified — the server keeps the nonce to itself (§12.1 note 7).\n *\n * @throws AuthError client-side, without a wire call, when tenant or org\n * context cannot be resolved.\n */\n async ssoStart(params: SsoStartParams): Promise<SsoStartResult> {\n const tenantId = params.tenantId ?? this.#session.tenantId;\n const tenantSlug = params.tenantSlug ?? this.#session.tenantSlug;\n const orgId = params.orgId ?? this.#session.orgId;\n const orgSlug = params.orgSlug ?? this.#session.orgSlug;\n\n if (!tenantId && !tenantSlug) {\n throw new AuthError(\n 'ssoStart requires tenant context: pass tenantId or tenantSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n if (!orgId && !orgSlug) {\n throw new AuthError(\n 'ssoStart requires organization context: pass orgId or orgSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n\n const body: Record<string, string> = {\n federation_config_id: params.federationConfigId,\n redirect_uri: params.redirectUri,\n };\n // One tenant form AND one org form (§5.1). The UUID form wins when both\n // are present, mirroring how tenantSlug/tenantId already resolve.\n if (tenantId) {\n body.tenant_id = tenantId;\n } else if (tenantSlug) {\n body.tenant_slug = tenantSlug;\n }\n if (orgId) {\n body.org_id = orgId;\n } else if (orgSlug) {\n body.org_slug = orgSlug;\n }\n\n const response = await this.#postJson<OidcStartResponseWire>(\n SSO_START_PATH,\n body,\n 'ssoStart request failed',\n );\n return {\n authorizeUrl: response.data.authorize_url,\n state: response.data.state,\n expiresInSecs: response.data.expires_in_secs,\n };\n }\n\n // -------------------------------------------------------------------------\n // 9. ssoComplete\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/callback` (§12.1) — step 2 of upstream\n * SSO: consumes the single-use `state`, provisions or links the user, and\n * establishes the session.\n *\n * @remarks\n * The session arrives as **`Set-Cookie`**, not in the response body\n * (§12.1 note 6), so this call must go through the §4 cookie jar: use a\n * `NodeSession` (`createNodeSession`/`createNodeClient`) or the session is\n * silently lost. On success the session is marked authenticated and its\n * post-authentication hook runs, syncing the CSRF token and cached access\n * token out of the jar exactly as `login()` does.\n *\n * §12.4 does not apply here — no ID token ever reaches the SDK on the\n * federation path.\n */\n async ssoComplete(params: SsoCompleteParams): Promise<SsoCompleteResult> {\n const response = await this.#postJson<SsoLoginSuccessResponseWire>(\n SSO_CALLBACK_PATH,\n { state: params.state, code: params.code },\n 'ssoComplete request failed',\n );\n\n this.#session.authenticated = true;\n // Same post-login sync login()/verifyMfa() perform (CR-01/D-05): reads the\n // freshly-set axiam_csrf/axiam_access cookies out of the jar. A no-op on\n // the browser SharedSession, which has no jar.\n await this.#session.onAuthenticated?.();\n\n return {\n userId: response.data.user_id,\n sessionId: response.data.session_id,\n expiresIn: response.data.expires_in,\n redirectUri: response.data.redirect_uri,\n };\n }\n\n // -------------------------------------------------------------------------\n // internals\n // -------------------------------------------------------------------------\n\n /**\n * Run one `refresh_token` grant under the session's §9 single-flight guard.\n *\n * The guard's callback signature returns `void`, so the token set is\n * published through a local variable. When the callback does NOT run, the\n * guard was already busy with a *different* refresh (the §1 cookie-session\n * path, which cannot produce an `OidcTokenSet`); rather than return a stale\n * or wrong result we simply try again now that the other refresh has\n * settled. Bounded, so a pathologically busy guard fails loudly instead of\n * spinning.\n */\n async #refreshUnderGuard(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'refresh_token');\n form.set('refresh_token', exposeSecret(params.refreshToken));\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n for (let attempt = 0; attempt < 3; attempt += 1) {\n let refreshed: OidcTokenSet | undefined;\n await this.#session.refreshGuard(async () => {\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to a refresh-issued ID token.\n refreshed = await this.#toTokenSet(wire, configuration, undefined);\n });\n if (refreshed) {\n return refreshed;\n }\n }\n throw new AuthError(\n 'oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md §9); another refresh kept it busy.',\n );\n }\n\n /** POST a form body to the token endpoint from the discovery document. */\n async #postToken(\n configuration: OidcConfiguration,\n form: URLSearchParams,\n tenantId: string | undefined,\n ): Promise<TokenResponseWire> {\n const url = this.#endpointUrl(configuration.token_endpoint, tenantId);\n const response = await this.#postForm<TokenResponseWire>(url, form, 'token request failed');\n return response.data;\n }\n\n /**\n * Convert a `TokenResponse` into an {@link OidcTokenSet}, validating any\n * `id_token` first (§12.4). Validation precedes construction, so a failure\n * discards the whole set — the caller never sees the access or refresh token\n * from a response whose ID token was rejected (§12.4 rule 7).\n */\n async #toTokenSet(\n wire: TokenResponseWire,\n configuration: OidcConfiguration,\n nonce: string | undefined,\n ): Promise<OidcTokenSet> {\n let idClaims: IdTokenClaims | undefined;\n if (wire.id_token) {\n idClaims = await this.#verifierFor(configuration.jwks_uri).verifyIdToken(wire.id_token, {\n issuer: configuration.issuer,\n clientId: this.#options.clientId,\n ...(nonce !== undefined ? { nonce } : {}),\n ...(this.#options.clockSkewSec !== undefined ? { clockSkewSec: this.#options.clockSkewSec } : {}),\n });\n }\n\n return {\n accessToken: new Sensitive(wire.access_token),\n tokenType: wire.token_type,\n expiresIn: wire.expires_in,\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.refresh_token != null ? { refreshToken: new Sensitive(wire.refresh_token) } : {}),\n ...(wire.id_token != null ? { idToken: new Sensitive(wire.id_token) } : {}),\n ...(idClaims !== undefined ? { idClaims } : {}),\n };\n }\n\n /** Lazily build (and reuse) the JWKS verifier for a `jwks_uri` (§12.3 rule 6). */\n #verifierFor(jwksUri: string): JwksVerifier {\n const existing = this.#verifiers.get(jwksUri);\n if (existing) {\n return existing;\n }\n const verifier = createJwksVerifier(jwksUri);\n this.#verifiers.set(jwksUri, verifier);\n return verifier;\n }\n\n /**\n * Build the final endpoint URL: the discovery document's endpoint plus the\n * mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2). Existing\n * query parameters on the endpoint are preserved.\n */\n #endpointUrl(endpoint: string, tenantId: string | undefined): string {\n const url = new URL(endpoint);\n url.searchParams.set('tenant_id', this.#resolveTenantId(tenantId));\n return url.toString();\n }\n\n /**\n * Resolve the tenant UUID for the `tenant_id` query parameter (§12.3\n * rule 4): the explicit argument, else the client-level `tenantId`, else the\n * session's `tenantId` — and only ever a UUID. A slug-only client raises the\n * taxonomy error client-side, with no wire call, rather than sending a slug\n * where the server requires a UUID.\n */\n #resolveTenantId(explicit: string | undefined): string {\n const candidate = explicit ?? this.#options.tenantId ?? this.#session.tenantId;\n if (!candidate) {\n throw new AuthError(\n 'this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenantId explicitly, ' +\n 'or construct the client with the tenantId (UUID) form (CONTRACT.md §12.3 rule 4).',\n );\n }\n if (!UUID_RE.test(candidate)) {\n throw new AuthError(\n 'tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted ' +\n '(CONTRACT.md §12.3 rule 4).',\n );\n }\n return candidate;\n }\n\n /**\n * Add `client_secret` to a form body for a confidential client, and omit it\n * entirely for a public client — §12.1 forbids sending an empty/null value\n * for an absent optional field.\n */\n #appendClientSecret(form: URLSearchParams): void {\n const secret = this.#options.clientSecret;\n if (secret !== undefined) {\n form.set('client_secret', exposeSecret(secret));\n }\n }\n\n /** The `client_secret` for an operation that cannot be performed without one (§12.1 note 4). */\n #requireClientSecret(operation: string): string {\n const secret = this.#options.clientSecret;\n if (secret === undefined) {\n throw new AuthError(\n `${operation} requires confidential-client credentials: construct the OidcClient with a clientSecret ` +\n '(CONTRACT.md §12.1 note 4).',\n );\n }\n return exposeSecret(secret);\n }\n\n /**\n * Adopt an access token as this session's bearer credential (§12.1, opt-in).\n *\n * The token lives only inside the interceptor closure, behind\n * {@link Sensitive} — never on `axios.defaults`, a public property or the\n * cookie jar — so it stays unreachable through any public getter (§12.3\n * rule 2). It is deliberately NOT sent to `/oauth2/*`: those endpoints\n * authenticate the client through the form body (§12.1 note 3).\n */\n #adoptCredential(accessToken: Sensitive<string>): void {\n this.#adoptedCredential = accessToken;\n if (this.#adoptionInterceptorInstalled) {\n return;\n }\n this.#adoptionInterceptorInstalled = true;\n this.#session.axios.interceptors.request.use((config) => {\n const adopted = this.#adoptedCredential;\n const url = config.url ?? '';\n if (!adopted || this.#session.isForeignHost(url) || url.includes('/oauth2/')) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['Authorization'] = `Bearer ${adopted.expose()}`;\n return config;\n });\n }\n\n /** GET through the session transport, mapping failures onto the §2 taxonomy. */\n async #get<T>(url: string, fallbackMessage: string): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.get<T>(url);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a form-encoded body (§12.1 note 1) through the session transport. */\n async #postForm<T>(\n url: string,\n form: URLSearchParams,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n const config: AxiosRequestConfig = {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n };\n try {\n return await this.#session.axios.post<T>(url, form.toString(), config);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a JSON body (the federation endpoints) through the session transport. */\n async #postJson<T>(\n url: string,\n body: Record<string, string>,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.post<T>(url, body);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n}\n\n/**\n * Normalize the requested scope to a space-separated string that always\n * contains `openid` (§12.1 rule 4 — the helper adds it when the caller omits\n * it). Duplicate entries are collapsed so `\"openid openid profile\"` cannot be\n * produced.\n */\nfunction normalizeScope(scope: string | string[] | undefined): string {\n const requested = Array.isArray(scope) ? scope : (scope ?? '').split(' ');\n const values = requested.map((value) => value.trim()).filter(Boolean);\n if (!values.includes(OPENID_SCOPE)) {\n values.unshift(OPENID_SCOPE);\n }\n return [...new Set(values)].join(' ');\n}\n\n/**\n * Build an {@link OidcClient} on an existing session (CONTRACT.md §12).\n *\n * @param session the session the rest of the SDK already uses — normally a\n * `NodeSession` from `createNodeSession`, so the §4 cookie jar is in place\n * for `ssoComplete` (its session arrives as `Set-Cookie`).\n * @param options the relying party's `clientId`, optional `clientSecret`, and\n * optional tenant/TTL/skew overrides.\n *\n * @example\n * ```ts\n * import { createNodeSession, createOidcClient } from 'axiam-sdk/node';\n *\n * const session = createNodeSession({ baseUrl, tenantId, orgId });\n * const oidc = createOidcClient(session, {\n * clientId: process.env.AXIAM_CLIENT_ID!,\n * clientSecret: process.env.AXIAM_CLIENT_SECRET,\n * });\n * ```\n */\nexport function createOidcClient(session: SharedSession, options: OidcClientOptions): OidcClient {\n return new OidcClient(session, options);\n}\n","// OidcStateStore + MemoryOidcStateStore (CONTRACT.md §12.3 rule 1).\n//\n// STRICTLY OPTIONAL. The nine §12 operations never touch a store: `oidcBegin`\n// and `oidcExchange` are stateless by contract, and the caller normally keeps\n// `state`/`nonce`/`code_verifier` in its own HTTP session. This store exists\n// for the framework glue (`middleware/oidcLogin*`), where a login and its\n// callback are two separate HTTP requests with nothing but a `state` value\n// linking them.\n//\n// Semantics mirror the server's `federation_login_state` table exactly:\n// 10-minute TTL, single-use consume. That symmetry is deliberate — a reader\n// who knows the server side already knows this class.\n\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The tuple an {@link OidcStateStore} holds for one in-flight login.\n *\n * @remarks\n * `codeVerifier` stays {@link Sensitive} while stored (§12.5: the verifier is\n * secret for its whole lifetime, \"including … in any `OidcStateStore` entry\"),\n * so `JSON.stringify()`ing an entry — e.g. into a Redis-backed store — emits\n * `\"[SENSITIVE]\"` rather than the verifier. A store implementation that needs\n * to persist the value must call `expose()` explicitly and is then responsible\n * for protecting it at rest.\n */\nexport interface OidcStateEntry {\n /** The `state` value this entry is keyed by. Not a secret (§12.3 rule 2). */\n state: string;\n /** The `nonce` to check the ID token's `nonce` claim against. Not a secret (§12.3 rule 2). */\n nonce: string;\n /** The PKCE verifier for the matching authorization request (§12.5 secret). */\n codeVerifier: Sensitive<string>;\n /** The `redirect_uri` that was sent on the authorization request and must be replayed on exchange. */\n redirectUri: string;\n /** Optional application-owned data, e.g. the page the user was heading to before login. */\n returnTo?: string;\n}\n\n/**\n * Optional server-side store for in-flight `oidcBegin` state\n * (CONTRACT.md §12.3 rule 1).\n *\n * @remarks\n * Implement this to back the login/callback handlers with your own storage\n * (Redis, a database, an encrypted cookie). Two invariants are normative:\n *\n * 1. **Single-use.** {@link consume} MUST return the entry *and delete it\n * atomically*, so a replayed callback cannot reuse a `state`.\n * 2. **Expiry.** An entry older than 10 minutes MUST NOT be returned.\n */\nexport interface OidcStateStore {\n /** Persist an entry, keyed by its `state`, starting its TTL now. */\n save(entry: OidcStateEntry): Promise<void>;\n /**\n * Atomically fetch **and remove** the entry for `state`. Returns\n * `undefined` when the state is unknown, already consumed, or expired —\n * three cases a caller MUST treat identically (as a failed login), because\n * distinguishing them leaks whether a `state` ever existed.\n */\n consume(state: string): Promise<OidcStateEntry | undefined>;\n}\n\n/**\n * The contract-mandated TTL for stored login state: 10 minutes, matching the\n * server's `federation_login_state` row lifetime (D-22, §12.3 rule 1).\n */\nexport const OIDC_STATE_TTL_MS = 600_000;\n\n/**\n * In-memory reference implementation of {@link OidcStateStore} (§12.3 rule 1).\n *\n * @remarks\n * Per-instance (never process-global), single-use, 10-minute TTL. Expired\n * entries are dropped lazily on {@link consume} and swept opportunistically on\n * {@link save}, so no timer is held and the store needs no shutdown hook — a\n * long-lived `setInterval` would keep a Node process alive and would be a\n * surprising side effect for a library.\n *\n * Suitable for a single-process app and for tests. A multi-instance deployment\n * needs a shared store (Redis, database) — implement {@link OidcStateStore}\n * yourself for that; nothing in the SDK assumes this class.\n *\n * @example\n * ```ts\n * const store = new MemoryOidcStateStore();\n * await store.save({ state, nonce, codeVerifier, redirectUri });\n * const entry = await store.consume(state); // returns the entry\n * const again = await store.consume(state); // undefined — single-use\n * ```\n */\nexport class MemoryOidcStateStore implements OidcStateStore {\n readonly #entries = new Map<string, { entry: OidcStateEntry; expiresAt: number }>();\n readonly #ttlMs: number;\n\n /**\n * @param ttlMs entry lifetime in milliseconds. Defaults to\n * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a\n * shorter TTL is honoured (useful in tests), a longer one is reduced,\n * because §12.3 rule 1 fixes 10 minutes as the maximum.\n */\n constructor(ttlMs: number = OIDC_STATE_TTL_MS) {\n this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);\n }\n\n /** Number of unexpired entries currently held. Intended for tests and metrics. */\n get size(): number {\n this.#sweep();\n return this.#entries.size;\n }\n\n /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */\n async save(entry: OidcStateEntry): Promise<void> {\n this.#sweep();\n this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });\n }\n\n /**\n * Atomically return and delete the entry for `state`. Deletion happens\n * before the expiry check, so even an expired hit is removed rather than\n * left to accumulate — and a second call can never return the same entry\n * twice regardless of timing (JavaScript's single-threaded event loop makes\n * this get-then-delete pair genuinely atomic; a store backed by real\n * concurrency must use an atomic primitive such as Redis `GETDEL`).\n */\n async consume(state: string): Promise<OidcStateEntry | undefined> {\n const held = this.#entries.get(state);\n if (!held) {\n return undefined;\n }\n this.#entries.delete(state);\n if (held.expiresAt <= Date.now()) {\n return undefined;\n }\n return held.entry;\n }\n\n /** Drop every expired entry. Lazy housekeeping — no background timer. */\n #sweep(): void {\n const now = Date.now();\n for (const [state, held] of this.#entries) {\n if (held.expiresAt <= now) {\n this.#entries.delete(state);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/csrf.ts","../../src/core/singleFlightRefresh.ts","../../src/core/config.ts","../../src/rest/session.ts","../../src/rest/interceptors.ts","../../src/rest/auth.ts","../../src/rest/authz.ts","../../src/rest/client.ts","../../src/node/cookieJar.ts","../../src/node/tokenManager.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/node/session.ts","../../src/node/oidcPkce.ts","../../src/node/oidc.ts","../../src/node/oidcState.ts","../../src/node/webhook.ts"],"names":["UUID_RE","document","timingSafeEqual"],"mappings":";;;;;;;;;;;;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU/B,MAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAA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K,GAAA,KAAQ,GAAI,CAAA;AAC1D,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,IAAa,6BAAA;AACvC,EAAA,MAAM,MAAM,MAAA,GAAS,SAAA;AACrB,EAAA,IAAI,MAAM,SAAA,EAAW;AACnB,IAAA,IAAA,CAAK,iBAAA,EAAmB,CAAA,aAAA,EAAgB,GAAG,CAAA,mBAAA,EAAsB,SAAS,CAAA,WAAA,CAAa,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,CAAC,MAAM,SAAA,EAAW;AACpB,IAAA,IAAA,CAAK,oBAAoB,CAAA,aAAA,EAAgB,CAAC,GAAG,CAAA,6BAAA,EAAgC,SAAS,CAAA,WAAA,CAAa,CAAA;AAAA,EACrG;AAEA,EAAA,IAAI,UAAA;AACJ,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,IAAA,UAAA,GAAa,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,QAAA,CAAS,MAAM,CAAC,CAAA;AAChD,IAAA,IAAI,UAAA,KAAe,IAAA,IAAQ,OAAO,UAAA,KAAe,QAAA,EAAU;AACzD,MAAA,MAAM,GAAA,GAAM,UAAA;AACZ,MAAA,IAAI,OAAO,GAAA,CAAI,KAAA,KAAU,QAAA,UAAkB,GAAA,CAAI,KAAA;AAC/C,MAAA,IAAI,OAAO,GAAA,CAAI,EAAA,KAAO,QAAA,OAAe,GAAA,CAAI,EAAA;AAAA,IAC3C;AAAA,EACF,CAAA,CAAA,MAAQ;AAIN,IAAA,UAAA,GAAa,MAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,EAAA,EAAI,SAAA,EAAW,IAAA,EAAM,YAAY,OAAA,EAAQ;AAC3D","file":"index.mjs","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Central status -> error mapper (CONTRACT.md §2, D-17).\n//\n// The single source of truth for both rest/ and grpc/ transports so the two\n// cannot drift on the error taxonomy. Transcribes CONTRACT.md §2's HTTP and\n// gRPC tables exactly.\n//\n// GrpcStatus is exported here (not imported from @grpc/grpc-js) so that\n// core stays dependency-free — grpc/ imports the numeric codes from core\n// rather than the other way around.\n\nimport {\n AuthError,\n AuthzError,\n NetworkError,\n OAuthProtocolError,\n type AxiamError,\n} from './errors.js';\n\n/** gRPC status codes referenced by CONTRACT.md §2 (subset of the full grpc.status enum). */\nexport const GrpcStatus = {\n DEADLINE_EXCEEDED: 4,\n PERMISSION_DENIED: 7,\n RESOURCE_EXHAUSTED: 8,\n INTERNAL: 13,\n UNAVAILABLE: 14,\n UNAUTHENTICATED: 16,\n} as const;\n\nexport interface HttpErrorContext {\n action?: string;\n resourceId?: string;\n cause?: unknown;\n /**\n * The request URL (absolute or path-only) the error came from, when\n * available. Load-bearing for the two **endpoint-qualified** rows of §2's\n * HTTP table (added by contract 1.4): a `400`/`401` carrying an\n * `OAuth2ErrorResponse` body maps to `OAuthProtocolError` only when it came\n * from an `/oauth2/*` endpoint. Omitting it simply keeps the generic rows.\n */\n url?: string;\n /**\n * The parsed JSON response body (when available). For a 403/409\n * authorization-denied response the server shapes this as\n * `{ error: \"authorization_denied\", message, action?, resource_id? }`\n * (`action` present when known, `resource_id` present only for a\n * resource-scoped denial). `mapHttpStatusToError` prefers these body\n * fields over `action`/`resourceId` above when populating `AuthzError`.\n */\n body?: unknown;\n}\n\n/**\n * Extract `action`/`resource_id` (snake_case -> camelCase) from a parsed\n * authorization-denied response body, if present and string-typed. Any other\n * shape (missing fields, non-object body, older servers with no body at all)\n * yields `{}`, so callers fall back to caller-supplied context.\n */\nfunction extractAuthzFieldsFromBody(body: unknown): { action?: string; resourceId?: string } {\n if (body === null || typeof body !== 'object') {\n return {};\n }\n const record = body as Record<string, unknown>;\n const action = typeof record.action === 'string' ? record.action : undefined;\n const resourceId = typeof record.resource_id === 'string' ? record.resource_id : undefined;\n return { action, resourceId };\n}\n\n/**\n * The RFC 6749 error body shape (`OAuth2ErrorResponse` in `openapi.json`)\n * returned by AXIAM's `/oauth2/*` endpoints. Both fields are required by the\n * schema.\n */\nexport interface OAuth2ErrorResponseWire {\n /** RFC 6749 error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable description of the failure. */\n error_description: string;\n}\n\n/**\n * Path prefix identifying AXIAM's OAuth2 endpoint family (`/oauth2/token`,\n * `/oauth2/introspect`, `/oauth2/revoke`, …). The two endpoint-qualified §2\n * rows apply only to URLs whose path starts with it.\n */\nconst OAUTH2_PATH_PREFIX = '/oauth2/';\n\n/**\n * Whether `url` targets an `/oauth2/*` endpoint. Accepts both an absolute URL\n * (as taken from the discovery document) and a bare path (as axios request\n * configs carry), and never throws on a malformed value — an unparseable URL\n * simply falls back to a substring test, so a mis-shaped URL can only ever\n * *fail* to qualify for the OAuth2 rows, never wrongly qualify for them.\n */\nexport function isOAuth2EndpointUrl(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n // A relative path has no base here, so `URL` throws and we fall through.\n return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);\n } catch {\n return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);\n }\n}\n\n/**\n * Narrow a parsed response body to {@link OAuth2ErrorResponseWire}. Both\n * `error` and `error_description` must be present and string-typed — a body\n * that carries only one of them is NOT an `OAuth2ErrorResponse` and keeps the\n * generic §2 mapping (better a generic error than a fabricated\n * `error_description`).\n */\nexport function isOAuth2ErrorBody(body: unknown): body is OAuth2ErrorResponseWire {\n if (body === null || typeof body !== 'object') {\n return false;\n }\n const record = body as Record<string, unknown>;\n return typeof record.error === 'string' && typeof record.error_description === 'string';\n}\n\n/**\n * ALLOWLIST (X-3) of response headers that are safe to preserve in a\n * NetworkError.cause. Every header NOT listed here has its value redacted to a\n * placeholder, so a custom sensitive header (e.g. `X-Auth-Token`) can never\n * survive into a thrown error — unlike a small denylist, which only catches the\n * headers it happens to enumerate. Names are compared case-insensitively (all\n * entries are lower-case). Keep this list small and strictly non-secret:\n * standard diagnostic response headers plus this SDK's own non-secret request\n * headers (e.g. `x-tenant-id`).\n */\nconst SAFE_RESPONSE_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'date',\n 'server',\n 'retry-after',\n 'x-request-id',\n 'x-tenant-id',\n]);\n\n/** Placeholder substituted for the value of any non-allowlisted header. */\nconst REDACTED_HEADER = '[REDACTED]';\n\n/**\n * Redact every non-allowlisted response header from an axios-error-shaped\n * `err` before it is attached as `NetworkError.cause` (CR-04, D-16, X-3). On\n * login/refresh error paths the server may have already issued Set-Cookie\n * headers containing raw `axiam_access`/`axiam_refresh` values (and callers may\n * set custom sensitive headers such as `X-Auth-Token`); none of these must be\n * reachable via `console.log`/`JSON.stringify`/`util.inspect` of the thrown\n * error. Only headers on `SAFE_RESPONSE_HEADERS` keep their value; all others\n * are replaced with `[REDACTED]`.\n *\n * Returns a new, shallow-cloned object for any input shaped like\n * `{ response: { headers: {...} } }` — the caller's original axios error\n * object is left untouched. Non-object inputs (plain Error, string,\n * undefined) and objects with no `response.headers` are returned unchanged.\n */\nexport function sanitizeAxiosError(err: unknown): unknown {\n if (err === null || typeof err !== 'object') {\n return err;\n }\n const candidate = err as { response?: unknown };\n if (candidate.response === null || typeof candidate.response !== 'object') {\n return err;\n }\n const response = candidate.response as { headers?: unknown };\n if (response.headers === null || typeof response.headers !== 'object') {\n return err;\n }\n\n const sanitizedHeaders: Record<string, unknown> = { ...(response.headers as Record<string, unknown>) };\n for (const key of Object.keys(sanitizedHeaders)) {\n if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {\n sanitizedHeaders[key] = REDACTED_HEADER;\n }\n }\n\n return {\n ...err,\n response: {\n ...response,\n headers: sanitizedHeaders,\n },\n };\n}\n\n/**\n * Map an HTTP status code to an AxiamError variant per CONTRACT.md §2's HTTP\n * status table.\n *\n * | Status | Type |\n * |-----------|--------------|\n * | 400 | NetworkError |\n * | 400 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 401 | AuthError |\n * | 401 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * Where two rows match the same response the more specific\n * (endpoint- and body-qualified) row wins, per §2 — so the two\n * `OAuthProtocolError` rows are evaluated first. They require BOTH an\n * `/oauth2/*` `ctx.url` AND an `OAuth2ErrorResponse`-shaped `ctx.body`;\n * anything else keeps the generic mapping.\n *\n * NetworkError's `cause` (when provided via `ctx.cause`) is always passed\n * through `sanitizeAxiosError` first (CR-04) — this is the single choke\n * point for both rest/ auth call sites and any future caller.\n *\n * For 403/409, `action`/`resourceId` are sourced from the response body\n * (`ctx.body`) when the body carries them, falling back to the\n * caller-supplied `ctx.action`/`ctx.resourceId` (the request call-args)\n * otherwise — this keeps compatibility with older servers that don't yet\n * echo `action`/`resource_id` in the denial body.\n */\nexport function mapHttpStatusToError(\n status: number,\n message: string,\n ctx?: HttpErrorContext,\n): AxiamError {\n // Endpoint-qualified rows first (§2 \"the more specific row wins\",\n // §12.3 rule 3). `message` is deliberately ignored here: the contract fixes\n // OAuthProtocolError's message to \"<error>: <error_description>\".\n if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {\n return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);\n }\n if (status === 401) {\n return new AuthError(message);\n }\n if (status === 403 || status === 409) {\n const fromBody = extractAuthzFieldsFromBody(ctx?.body);\n return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);\n }\n // 400, 408, 429, 5xx, and any other status fall through to NetworkError.\n return new NetworkError(message, sanitizeAxiosError(ctx?.cause));\n}\n\n/**\n * Map a gRPC status code to an AxiamError variant per CONTRACT.md §2's gRPC\n * status table.\n *\n * | Code | Type |\n * |------------------------|--------------|\n * | 16 UNAUTHENTICATED | AuthError |\n * | 7 PERMISSION_DENIED | AuthzError |\n * | 14 UNAVAILABLE | NetworkError |\n * | 4 DEADLINE_EXCEEDED | NetworkError |\n * | 13 INTERNAL | NetworkError |\n * | 8 RESOURCE_EXHAUSTED | NetworkError |\n * | other | NetworkError |\n */\nexport function mapGrpcStatusToError(code: number, message: string): AxiamError {\n if (code === GrpcStatus.UNAUTHENTICATED) {\n return new AuthError(message);\n }\n if (code === GrpcStatus.PERMISSION_DENIED) {\n return new AuthzError(message);\n }\n return new NetworkError(message);\n}\n","// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// CSRF double-submit helpers (CONTRACT.md §3, D-05/D-28).\n//\n// The AXIAM server's CSRF middleware validates X-CSRF-Token against the\n// axiam_csrf cookie value directly (cookie double-submit). The regex is\n// deliberately hardcoded (not built dynamically from a configurable cookie\n// name) to avoid ReDoS/CWE-1333 — mirrors frontend/src/lib/api.ts exactly.\n\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\nexport const CSRF_HEADER = 'X-CSRF-Token';\nexport const CSRF_METHODS: ReadonlySet<string> = new Set(['post', 'put', 'patch', 'delete']);\n\nconst CSRF_COOKIE_REGEX = /(?:^|;\\s*)axiam_csrf=([^;]*)/;\n\n/** Extract the axiam_csrf cookie value from a `document.cookie`-shaped string, or null if absent. */\nexport function readCsrfCookie(cookieString: string): string | null {\n const match = CSRF_COOKIE_REGEX.exec(cookieString);\n if (!match) {\n return null;\n }\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Returns the CSRF header value for a state-changing HTTP method\n * (post/put/patch/delete, case-insensitive), or undefined for safe methods\n * (get/head/options) or when no CSRF cookie is present yet.\n */\nexport function csrfHeaderForMethod(method: string, cookieString: string): string | undefined {\n if (!CSRF_METHODS.has(method.toLowerCase())) {\n return undefined;\n }\n const token = readCsrfCookie(cookieString);\n return token ?? undefined;\n}\n","// Single-flight refresh guard (CONTRACT.md §9, D-07/D-13).\n//\n// Per-session-scoped shared-Promise guard (CR-02 gap closure, 17-VERIFICATION.md):\n// createRefreshGuard() returns a fresh, independent refreshOnce closure per\n// call, each closing over its OWN private refreshPromise. Concurrent callers\n// against the SAME guard instance share the same in-flight Promise; the\n// guard clears on settle (success or failure) so a later expiry can trigger\n// a fresh refresh — this is the exactly-one-in-flight-at-a-time semantics §9\n// requires, not a permanent single-refresh-ever lock. Distinct guard\n// instances (one per SharedSession/NodeSession, D-13) never share state, so\n// a refresh on session A can never silently satisfy a concurrent refresh on\n// session B.\n\n/** A session-scoped single-flight guard closure, as returned by `createRefreshGuard()`. */\nexport type RefreshGuard = (doRefresh: () => Promise<void>) => Promise<void>;\n\n/** Test-only reset hook type, attached to each guard closure via `Object.assign`. @internal */\ninterface ResettableRefreshGuard {\n (doRefresh: () => Promise<void>): Promise<void>;\n __reset(): void;\n}\n\n/**\n * Build a fresh, independent single-flight refresh guard. Each call returns\n * its own closure with a private `refreshPromise` — instantiate one per\n * `SharedSession`/`NodeSession` (D-13) so refresh guards never cross-wire\n * between independent client instances (CR-02).\n */\nexport function createRefreshGuard(): RefreshGuard {\n let refreshPromise: Promise<void> | null = null;\n\n const guard = ((doRefresh: () => Promise<void>): Promise<void> => {\n if (!refreshPromise) {\n refreshPromise = doRefresh().finally(() => {\n refreshPromise = null;\n });\n }\n return refreshPromise;\n }) as ResettableRefreshGuard;\n\n guard.__reset = () => {\n refreshPromise = null;\n };\n\n return guard;\n}\n\n// Backward-compatible module-level default guard instance, retained for\n// test/core/singleFlightRefresh.test.ts and any caller still importing the\n// bare `refreshOnce`/`resetRefreshGuard` module-level functions. New\n// wiring (rest/interceptors.ts, grpc/callWithRefresh.ts) MUST use a\n// per-session guard from `createRefreshGuard()` instead (see\n// SharedSession.refreshGuard).\nconst defaultGuard = createRefreshGuard() as ResettableRefreshGuard;\n\n/**\n * Ensures at most one `doRefresh()` call is in flight at a time, backed by\n * the single module-level default guard instance. Concurrent callers share\n * the same in-flight Promise; after it settles, a subsequent call invokes\n * `doRefresh` again.\n *\n * @deprecated for new wiring — use a per-instance guard from\n * `createRefreshGuard()` instead (D-13/CR-02). Retained for backward\n * compatibility.\n */\nexport function refreshOnce(doRefresh: () => Promise<void>): Promise<void> {\n return defaultGuard(doRefresh);\n}\n\n/** Test-only helper to reset the module-level default guard between test cases. @internal */\nexport function resetRefreshGuard(): void {\n defaultGuard.__reset();\n}\n","// AxiamClientOptions — shared client configuration (CONTRACT.md §5/§6/§6.1).\n//\n// tenantSlug or tenantId is required at construction time per §5; there is\n// no default tenant. customCa is the sole TLS escape hatch (§6) — there is\n// no insecure/skip-verification option anywhere in this SDK.\n//\n// clientCert/clientKey (§6.1) configure a client identity for mutual TLS\n// (mTLS). They NEVER relax server verification — they are an ADDITIVE client\n// credential, kept on a separate code path from server-CA trust so CI's\n// TLS-bypass lint gates are never tripped. mTLS is a Node-only capability\n// (browsers cannot present a client certificate from JS); the browser build\n// validates the PEM shape then ignores it, exactly as it already ignores\n// customCa.\n\nimport { Sensitive } from './sensitive.js';\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 * 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","// SharedSession — the object other transports (Node persona 17-03, middleware\n// 17-05) attach gRPC/JWKS/middleware state to (D-13).\n//\n// Holds: the axios instance, the tenant header value (computed once at\n// construction), a mutable csrfToken store, the base URL, and a per-instance\n// single-flight refresh guard (CR-02: NOT the module-level default guard —\n// each SharedSession gets its own via createRefreshGuard(), so two\n// independent AxiamClient/NodeSession instances never cross-wire refreshes).\n// One login() drives all transports for a given session.\n\nimport axios, { type AxiosInstance } from 'axios';\nimport type { AxiamClientOptions, ClientIdentity, RefreshGuard } from '../core/index.js';\nimport {\n CERT_PEM_MARKER,\n createRefreshGuard,\n DEFAULT_CONNECT_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n resolveClientIdentity,\n} from '../core/index.js';\n\nconst PEM_MARKER = CERT_PEM_MARKER;\n\n/**\n * The single session object every AXIAM transport (REST here, gRPC/AMQP in\n * 17-03/17-04, middleware in 17-05) attaches to. Constructed once per\n * `AxiamClient` instance.\n */\nexport class SharedSession {\n /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */\n readonly axios: AxiosInstance;\n /** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */\n readonly baseUrl: string;\n /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */\n readonly tenantHeaderValue: string;\n /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */\n readonly tenantId: string | undefined;\n /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */\n readonly tenantSlug: string | undefined;\n /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */\n readonly orgId: string | undefined;\n /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */\n readonly orgSlug: string | undefined;\n /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */\n readonly expectedIssuer: string | undefined;\n /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */\n readonly expectedAudience: string | undefined;\n /**\n * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`\n * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config\n * when the UUID was supplied, then updated from the access-token `tenant_id`\n * claim after each successful login/refresh (Node persona only — the browser\n * cannot read the httpOnly access-token cookie).\n */\n resolvedTenantId: string | undefined;\n /**\n * Resolved organization UUID used to build the `refresh` body. Seeded from\n * `orgId` config, then updated from the access-token `org_id` claim after a\n * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.\n */\n resolvedOrgId: string | undefined;\n /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */\n csrfToken: string | undefined;\n /** Set true once a successful login/verifyMfa has completed. */\n authenticated = false;\n /**\n * Per-instance single-flight refresh guard (CR-02, D-13). Shared across\n * this session's REST and gRPC transports (rest/interceptors.ts,\n * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but\n * NEVER shared with a different SharedSession/NodeSession instance.\n *\n * @internal SDK-internal transport wiring, not intended to be invoked\n * directly by SDK consumers — refreshes are driven automatically by the\n * response interceptor (rest) or `callWithRefresh` (grpc).\n */\n readonly refreshGuard: RefreshGuard;\n\n constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string) {\n this.axios = axiosInstance;\n this.baseUrl = options.baseUrl;\n this.tenantHeaderValue = tenantHeaderValue;\n this.tenantId = options.tenantId;\n this.tenantSlug = options.tenantSlug;\n this.orgId = options.orgId;\n this.orgSlug = options.orgSlug;\n this.expectedIssuer = options.expectedIssuer;\n this.expectedAudience = options.expectedAudience;\n // Seed the resolved UUIDs from any UUID-form config so the browser persona\n // (which cannot decode the httpOnly access token) can still build a valid\n // refresh body. The Node persona later overwrites these from the\n // access-token claims (NodeSession#resolveIdentifiersFromToken).\n this.resolvedTenantId = options.tenantId;\n this.resolvedOrgId = options.orgId;\n this.refreshGuard = createRefreshGuard();\n }\n\n /**\n * Build the `POST /api/v1/auth/refresh` request body (§1). The server's\n * `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this\n * emits the resolved UUIDs — from the access-token claims after login, or\n * from UUID-form construction options as a fallback. Fields that could not\n * be resolved are omitted (the server then answers with a clear 400), rather\n * than sending a slug where a UUID is required.\n */\n buildRefreshBody(): Record<string, string> {\n const body: Record<string, string> = {};\n if (this.resolvedTenantId) {\n body.tenant_id = this.resolvedTenantId;\n }\n if (this.resolvedOrgId) {\n body.org_id = this.resolvedOrgId;\n }\n return body;\n }\n\n /**\n * Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the\n * configured tenant and organization identifiers (UUID or slug form) in\n * addition to the credentials — the server resolves the workspace from the\n * body, not the `X-Tenant-ID` header, and rejects a login that omits org\n * context. Undefined identifiers are omitted.\n */\n buildLoginBody(email: string, password: string): Record<string, string> {\n const body: Record<string, string> = { username_or_email: email, password };\n if (this.tenantId) {\n body.tenant_id = this.tenantId;\n }\n if (this.tenantSlug) {\n body.tenant_slug = this.tenantSlug;\n }\n if (this.orgId) {\n body.org_id = this.orgId;\n }\n if (this.orgSlug) {\n body.org_slug = this.orgSlug;\n }\n return body;\n }\n\n /**\n * Optional session-level hook invoked by rest/auth.ts after a successful\n * login()/verifyMfa() (CR-01, D-05). The base SharedSession (browser\n * persona) does not implement it — the browser reads document.cookie\n * directly on every request and has no jar to sync from. NodeSession\n * overrides this to populate `csrfToken` from its cookie jar and refresh\n * the cached access token.\n */\n onAuthenticated?(): Promise<void>;\n\n /**\n * Host-isolation guard (3A, defense in depth): returns `true` when `url`\n * targets a host other than this session's base origin — an absolute\n * third-party URL, or a redirect that axios/the browser resolved off-origin.\n * The tenant identifier and CSRF token must never be attached to such a\n * request. A relative/host-less `url` (the normal case, merged against\n * `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's\n * `_prepare_request` guard. Malformed input fails closed (treated as\n * foreign).\n */\n isForeignHost(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n const target = new URL(url, this.baseUrl);\n return target.host !== new URL(this.baseUrl).host;\n } catch {\n return true;\n }\n }\n}\n\n/**\n * Resolve the required tenant header value from options (§5). Throws if\n * neither tenantSlug nor tenantId is provided — there is no default tenant.\n */\nexport function resolveTenantHeaderValue(options: AxiamClientOptions): string {\n if (options.tenantSlug) {\n return options.tenantSlug;\n }\n if (options.tenantId) {\n return options.tenantId;\n }\n throw new Error(\n 'AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md §5).',\n );\n}\n\n/**\n * Build the Node-only `https.Agent` carrying the customCa server-trust PEM\n * (§6) and/or the mTLS client identity (§6.1). Guarded by\n * `typeof process !== 'undefined'` as a CAPABILITY guard (Node has node:https\n * available), NOT a persona-sniffing branch — browsers ignore both customCa\n * and the client certificate entirely since the platform manages TLS itself.\n *\n * The client cert/key (§6.1) is an ADDITIVE client credential: it is passed\n * as `{ cert, key }` alongside `{ ca }` and NEVER touches `rejectUnauthorized`\n * — strict server verification stays at its secure default. The private key is\n * exposed from its {@link ClientIdentity} `Sensitive` wrapper only here, at the\n * point of handing it to the TLS stack, and is not retained anywhere else.\n */\nfunction loadNodeHttps(): typeof import('node:https') {\n // Node >= 20.16 / >= 22.3: `process.getBuiltinModule` loads a builtin\n // SYNCHRONOUSLY with no module system involved — no `import`, no `require`,\n // nothing for a bundler to rewrite. That is the whole point here: this file\n // is shared with the browser-safe `.`/`/rest` entries, so it must never\n // statically reference a Node builtin, yet the Node persona needs one\n // synchronously (buildSession is called from a constructor).\n //\n // The previous `require('node:https')` satisfied the first constraint but\n // not the second: tsup rewrites a bare `require` in ESM output into a shim\n // that throws `Dynamic require of \"https\" is not supported`, so under\n // genuine Node ESM — which is what `axiam-sdk/node`'s `import` condition\n // resolves to — EVERY call needing customCa or a client certificate failed\n // before the TLS handshake. It is reached off `process`, which the caller\n // has already capability-guarded, so a browser bundle never evaluates it.\n const getBuiltinModule = (\n process as unknown as { getBuiltinModule?: (id: string) => unknown }\n ).getBuiltinModule;\n if (typeof getBuiltinModule === 'function') {\n return getBuiltinModule.call(process, 'node:https') as typeof import('node:https');\n }\n // Older Node (the package still declares engines.node >= 18). `require` is\n // real in the CJS build, so this keeps working there; in the ESM build it is\n // the throwing shim, and the catch turns that into an error that says what\n // to actually do instead of leaking a bundler implementation detail.\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require('node:https') as typeof import('node:https');\n } catch {\n throw new Error(\n `customCa and clientCert require Node's https module, which this ESM build cannot load on Node ${process.version}: ` +\n 'process.getBuiltinModule is unavailable (added in Node 20.16 / 22.3) and `require` does not exist in an ES module. ' +\n 'Upgrade Node to >= 20.16, or load the CommonJS build (CONTRACT.md §6 / §6.1).',\n );\n }\n}\n\nexport interface NodeTlsOptions {\n /** §6 server-trust PEM bundle. */\n ca?: string;\n /** §6.1 client-certificate chain (PEM). */\n cert?: string;\n /** §6.1 private key (PEM). Secret material — never logged or retained. */\n key?: string;\n}\n\n/**\n * The TLS material for a Node agent, or `undefined` when there is nothing to\n * configure. `rejectUnauthorized` is deliberately absent: strict server\n * verification stays at its secure default and this object never carries a\n * TLS-bypass switch (§6).\n *\n * Split out from {@link maybeBuildHttpsAgent} because the Node persona cannot\n * use a plain `https.Agent` at all — see {@link resolveNodeTlsOptions}.\n */\nfunction tlsOptionsFrom(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): NodeTlsOptions | undefined {\n if (!customCa) {\n // Still short-circuit only when there is nothing to configure at all.\n if (!identity) {\n return undefined;\n }\n } else if (!customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n return {\n ...(customCa ? { ca: customCa } : {}),\n ...(identity ? { cert: identity.cert, key: identity.key.expose() } : {}),\n };\n}\n\n/**\n * Re-derive the Node TLS options from client options, for a persona that must\n * build its own agent rather than use the one {@link createSession} attaches.\n *\n * The Node persona is exactly that case. `axios-cookiejar-support`'s request\n * interceptor THROWS (\"does not support for use with other http(s).Agent\")\n * when it finds an `httpsAgent` it did not create, and otherwise overwrites\n * the agent with a bare `HttpsCookieAgent` — so under `createNodeClient` a\n * customCa or client certificate was either fatal or silently discarded,\n * independently of the ESM/require problem in {@link loadNodeHttps}. The Node\n * persona therefore constructs ONE agent that is both jar-aware and\n * TLS-configured (see `src/node/cookieJar.ts`), using these options.\n *\n * Not exported from the package barrel: the returned object holds the private\n * key (§6.1 rule 3 / §7), and its only legitimate consumer is the agent\n * construction inside this SDK.\n */\nexport function resolveNodeTlsOptions(options: AxiamClientOptions): NodeTlsOptions | undefined {\n return tlsOptionsFrom(options.customCa, resolveClientIdentity(options));\n}\n\nfunction maybeBuildHttpsAgent(\n customCa: string | undefined,\n identity: ClientIdentity | undefined,\n): unknown {\n const tls = tlsOptionsFrom(customCa, identity);\n if (!tls) {\n return undefined;\n }\n if (typeof process === 'undefined') {\n // Browser: platform manages TLS; customCa and the client cert have no\n // effect there (a browser cannot present a client certificate from JS).\n return undefined;\n }\n // Node capability guard — resolved lazily (see loadNodeHttps) so this\n // branch never executes, and never needs to resolve, in a browser bundle.\n const https = loadNodeHttps();\n return new https.Agent(tls);\n}\n\n/** Build the axios instance + SharedSession for an AxiamClient (D-13/D-25). */\nexport function createSession(options: AxiamClientOptions): SharedSession {\n const tenantHeaderValue = resolveTenantHeaderValue(options);\n\n // customCa is validated (PEM-shape) even when running in an environment\n // that will end up ignoring it (browser), so construction fails fast and\n // consistently across personas (§6).\n if (options.customCa !== undefined && !options.customCa.includes(PEM_MARKER)) {\n throw new Error(\n 'customCa must be a PEM-encoded certificate (expected to contain \"-----BEGIN CERTIFICATE-----\") (CONTRACT.md §6).',\n );\n }\n\n // The mTLS client identity (§6.1) is likewise validated on every persona so\n // a one-of/bad-PEM misconfiguration throws identically in browser and Node,\n // even though only Node presents the certificate.\n const clientIdentity = resolveClientIdentity(options);\n\n const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);\n\n const axiosInstance = axios.create({\n baseURL: options.baseUrl,\n withCredentials: true,\n timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n ...(httpsAgent ? { httpsAgent } : {}),\n });\n\n const session = new SharedSession(options, axiosInstance, tenantHeaderValue);\n\n // Attach X-Tenant-ID to every outgoing request (§5.2) — except when the\n // request targets a host other than our own origin (host-isolation, 3A).\n axiosInstance.interceptors.request.use((config) => {\n if (session.isForeignHost(config.url)) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['X-Tenant-ID'] = session.tenantHeaderValue;\n return config;\n });\n\n return session;\n}\n","// Axios interceptors: CSRF forwarding (D-05, §3) + reactive single-flight\n// 401->refresh (D-07, §9). Mirrors frontend/src/lib/api.ts's proven pattern,\n// generalized off the app store: this is a library, not an app — refresh\n// failure clears session auth state and rejects; it never redirects\n// (no window.location access anywhere in this module).\n\nimport type { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport { csrfHeaderForMethod, mapHttpStatusToError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Endpoints that must never trigger a silent refresh (§9.3, §12.3 rule 3).\n *\n * Two groups:\n * - the refresh endpoint itself plus login/logout — not\n * authenticated-session-continuation calls, so refreshing would only build\n * an infinite loop;\n * - the `/oauth2/*` endpoints — they authenticate the *client* with\n * `client_id`/`client_secret`, not the user session. A `401` there is a\n * client-credential failure, not a session expiry, so retrying after a\n * session refresh cannot help and MUST NOT enter the §9 guard\n * (CONTRACT.md §12.3 rule 3). `oidcRefresh` reaches the §9 guard through\n * its own explicit call path instead (`OidcClient.oidcRefresh`).\n */\nexport const SKIP_REFRESH = [\n '/api/v1/auth/refresh',\n '/api/v1/auth/login',\n '/api/v1/auth/logout',\n '/oauth2/token',\n '/oauth2/introspect',\n '/oauth2/revoke',\n];\n\ntype RetryableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean };\n\n/**\n * Request interceptor: forwards the axiam_csrf cookie as X-CSRF-Token on\n * state-changing methods (POST/PUT/PATCH/DELETE) per §3/D-05.\n *\n * Browser: reads `document.cookie` directly (guarded by `typeof document !==\n * 'undefined'`). Node: reads the session's csrfToken store, populated by the\n * Node persona's cookie-jar read (17-03) — left undefined here since no jar\n * exists in the browser-only REST core built by this plan.\n */\nexport function installCsrfInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {\n // Host-isolation (3A): never echo the CSRF token to an off-origin host.\n if (session.isForeignHost(config.url)) {\n return config;\n }\n const method = (config.method ?? 'get').toLowerCase();\n const cookieString = typeof document !== 'undefined' ? document.cookie : '';\n const csrfToken =\n typeof document !== 'undefined' ? csrfHeaderForMethod(method, cookieString) : csrfHeaderForMethod(method, session.csrfToken ? `axiam_csrf=${session.csrfToken}` : '');\n\n if (csrfToken) {\n config.headers = config.headers ?? {};\n config.headers['X-CSRF-Token'] = csrfToken;\n }\n return config;\n });\n}\n\n/**\n * Response interceptor: on 401 (when authenticated, not a SKIP_REFRESH url,\n * not already retried) performs a reactive single-flight refresh and replays\n * the original request (D-07/§9). Non-2xx responses are mapped through\n * core's mapHttpStatusToError.\n */\nexport function installRefreshInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.response.use(\n (response) => response,\n async (error: AxiosError) => {\n const originalRequest = error.config as RetryableRequestConfig | undefined;\n\n if (!originalRequest || !error.response) {\n // No response at all (network/timeout) — surface as NetworkError below via caller mapping.\n return Promise.reject(error);\n }\n\n const status = error.response.status;\n const url = originalRequest.url ?? '';\n const isSkipRefresh = SKIP_REFRESH.some((skipUrl) => url.includes(skipUrl));\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated) {\n // CQ-F32: set _retry BEFORE the refresh call so a 401 on the replayed\n // request cannot trigger a second refresh cycle.\n originalRequest._retry = true;\n\n try {\n await session.refreshGuard(async () => {\n await session.axios.post('/api/v1/auth/refresh', session.buildRefreshBody());\n // H8 fix: resync the Node persona's cached access token + CSRF\n // token after a reactive refresh too — see the matching fix\n // and comment on rest/auth.ts's explicit refresh(). Without\n // this the replayed request below (and every request after it)\n // echoes a stale X-CSRF-Token and 403s.\n await session.onAuthenticated?.();\n });\n return axiosInstance(originalRequest);\n } catch (refreshError) {\n session.authenticated = false;\n session.csrfToken = undefined;\n return Promise.reject(\n mapHttpStatusToError(401, 'session refresh failed; re-authentication required', {\n cause: refreshError,\n }),\n );\n }\n }\n\n if (status === 401 && isSkipRefresh) {\n // url + body are forwarded so the mapper can apply the\n // endpoint-qualified §2 row: a 401 from /oauth2/introspect or\n // /oauth2/revoke carrying an OAuth2ErrorResponse body becomes an\n // OAuthProtocolError rather than a bare AuthError (§12.3 rule 3).\n return Promise.reject(\n mapHttpStatusToError(401, 'authentication failed', {\n url,\n body: error.response.data,\n cause: error,\n }),\n );\n }\n\n return Promise.reject(error);\n },\n );\n}\n\n/** Install both the CSRF and reactive single-flight refresh interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n}\n","// login/verifyMfa/refresh/logout over REST (D-18, §1).\n//\n// Mirrors the Rust SDK's src/rest/auth.rs's request/response shapes exactly\n// (mirror only, no server crate dependency). Tokens are delivered\n// exclusively via Set-Cookie — LoginResult deliberately carries no session\n// token field anywhere in the public API (T-17-07).\n\nimport { mapHttpStatusToError, NetworkError, sanitizeAxiosError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n LoginResult,\n LoginSuccessResponseWire,\n MfaRequiredResponseWire,\n RefreshSuccessResponseWire,\n} from './types.js';\n\nconst LOGIN_PATH = '/api/v1/auth/login';\nconst MFA_VERIFY_PATH = '/api/v1/auth/mfa/verify';\nconst REFRESH_PATH = '/api/v1/auth/refresh';\nconst LOGOUT_PATH = '/api/v1/auth/logout';\n\ninterface MfaVerifyRequestBody {\n challenge_token: string;\n totp_code: string;\n}\n\nfunction loginSuccessToResult(wire: LoginSuccessResponseWire): LoginResult {\n return {\n status: 'authenticated',\n user: { id: wire.user.id, username: wire.user.username, email: wire.user.email },\n sessionId: wire.session_id,\n expiresIn: wire.expires_in,\n };\n}\n\nfunction mfaRequiredToResult(wire: MfaRequiredResponseWire): LoginResult {\n return {\n status: 'mfa_required',\n mfaToken: wire.challenge_token,\n availableMethods: wire.available_methods,\n };\n}\n\nfunction extractErrorMessage(err: unknown): string {\n if (err && typeof err === 'object' && 'message' in err && typeof (err as { message?: unknown }).message === 'string') {\n return (err as { message: string }).message;\n }\n return 'request failed';\n}\n\n/**\n * `POST /api/v1/auth/login` (§1).\n *\n * On a 200 response returns the authenticated branch of the LoginResult\n * discriminated union; on the MFA-required response (202) returns the\n * mfa_required branch (mfaToken sourced from the wire challenge_token).\n */\nexport async function login(client: AxiamClient, email: string, password: string): Promise<LoginResult> {\n // The server resolves the workspace from the login body (org + tenant), not\n // the X-Tenant-ID header, so tenant/org context must travel here (§5).\n const body = client.session.buildLoginBody(email, password);\n\n try {\n // axios treats any 2xx (including 202 MFA-required) as a resolved\n // response, not a thrown error — branch on the actual status here.\n const response = await client.session.axios.post<LoginSuccessResponseWire | MfaRequiredResponseWire>(\n LOGIN_PATH,\n body,\n );\n if (response.status === 202) {\n return mfaRequiredToResult(response.data as MfaRequiredResponseWire);\n }\n client.session.authenticated = true;\n // CR-01/D-05: sync the Node persona's csrfToken (and cached access token)\n // from the jar now that the session cookie(s) have landed. No-op for the\n // browser SharedSession, which has no onAuthenticated implementation.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data as LoginSuccessResponseWire);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'login failed', {\n cause: err,\n });\n }\n throw new NetworkError('login request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/mfa/verify` (§1).\n *\n * Completes the two-phase flow started by login() when status was\n * 'mfa_required', using the caller-supplied mfaToken (the challenge token\n * returned from that prior login() call).\n */\nexport async function verifyMfa(client: AxiamClient, mfaToken: string, code: string): Promise<LoginResult> {\n const body: MfaVerifyRequestBody = { challenge_token: mfaToken, totp_code: code };\n\n try {\n const response = await client.session.axios.post<LoginSuccessResponseWire>(MFA_VERIFY_PATH, body);\n client.session.authenticated = true;\n // CR-01/D-05: same post-authentication sync as login()'s 200 branch.\n await client.session.onAuthenticated?.();\n return loginSuccessToResult(response.data);\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'verifyMfa failed', {\n cause: err,\n });\n }\n throw new NetworkError('verifyMfa request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/refresh` (§1).\n *\n * Callers typically do not invoke this directly — the response interceptor\n * (interceptors.ts) drives it reactively via the single-flight guard on a\n * 401 (D-07). Exposed as a public method for explicit proactive refresh.\n */\nexport async function refresh(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post<RefreshSuccessResponseWire>(REFRESH_PATH, client.session.buildRefreshBody());\n // H8 fix (SDK bench harness validation): a successful refresh rotates\n // the `axiam_csrf` cookie (new random token, CONTRACT.md §3) the same\n // way login does, but — unlike login/verifyMfa just below, which both\n // call `onAuthenticated?.()` — this path never resynced the Node\n // persona's in-memory `session.csrfToken` (only NodeSession.doRefresh\n // did that, and doRefresh is wired to gRPC's callWithRefresh only, never\n // to this REST path). Every REST call after the FIRST refresh() then\n // echoed a now-stale X-CSRF-Token and failed with 403 \"CSRF validation\n // failed\" — refresh() effectively broke the session after one use.\n // `onAuthenticated` is exactly the right hook to reuse: same\n // access/csrf resync as login, it's a no-op on the browser persona\n // (undefined there), and Node's implementation is idempotent.\n await client.session.onAuthenticated?.();\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n // §9.3: 401 on the refresh call itself is AuthError, no retry loop.\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'refresh failed', {\n cause: err,\n });\n }\n throw new NetworkError('refresh request failed', sanitizeAxiosError(err));\n }\n}\n\n/**\n * `POST /api/v1/auth/logout` (§1).\n *\n * Clears session csrf/auth state regardless of the response outcome once\n * the request has been sent successfully.\n */\nexport async function logout(client: AxiamClient): Promise<void> {\n try {\n await client.session.axios.post(LOGOUT_PATH, {});\n } catch (err) {\n const status = extractAxiosStatus(err);\n if (status !== undefined) {\n throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? 'logout failed', {\n cause: err,\n });\n }\n throw new NetworkError('logout request failed', sanitizeAxiosError(err));\n } finally {\n client.session.authenticated = false;\n client.session.csrfToken = undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// axios error helpers (kept local — core stays dependency-free of axios)\n// ---------------------------------------------------------------------------\n\nfunction extractAxiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number } }).response;\n return response?.status;\n }\n return undefined;\n}\n\nfunction extractAxiosData<T>(err: unknown): T | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { data?: T } }).response;\n return response?.data;\n }\n return undefined;\n}\n","// checkAccess/can/batchCheck over REST (D-08, FND-04, §1).\n//\n// Mirrors the Rust SDK's src/rest/authz.rs and\n// crates/axiam-api-rest/src/handlers/authz_check.rs exactly. tenant_id is\n// never sent in the body — the server derives it from the JWT (§5); the SDK\n// only sends X-Tenant-ID (already attached by session.ts's request\n// interceptor on every call). No client-side cache (D-08) — plain stateless\n// async functions.\n\nimport { mapHttpStatusToError, NetworkError } from '../core/index.js';\nimport type { AxiamClient } from './client.js';\nimport type {\n AccessCheck,\n AccessDecision,\n BatchCheckAccessBodyWire,\n BatchCheckAccessResponseWire,\n CheckAccessBodyWire,\n CheckAccessResponseWire,\n} from './types.js';\n\nconst CHECK_PATH = '/api/v1/authz/check';\nconst BATCH_CHECK_PATH = '/api/v1/authz/check/batch';\n\nfunction toWireBody(check: AccessCheck): CheckAccessBodyWire {\n return {\n action: check.action,\n resource_id: check.resourceId,\n scope: check.scope,\n subject_id: check.subjectId,\n };\n}\n\nfunction fromWireDecision(wire: CheckAccessResponseWire): AccessDecision {\n return { allowed: wire.allowed, reason: wire.reason };\n}\n\n/**\n * `POST /api/v1/authz/check` (§1, FND-04).\n *\n * A 403 authz denial (server-side error, distinct from the `allowed: false`\n * decision the endpoint itself returns) is mapped to AuthzError, not treated\n * as a transport failure.\n */\nexport async function checkAccess(client: AxiamClient, check: AccessCheck): Promise<AccessDecision> {\n try {\n const response = await client.session.axios.post<CheckAccessResponseWire>(CHECK_PATH, toWireBody(check));\n return fromWireDecision(response.data);\n } catch (err) {\n throw mapAuthzError(err, check.action, check.resourceId);\n }\n}\n\n/**\n * `can` — alias for checkAccess targeting browser/UI scenarios (§1 note),\n * returning just the boolean `allowed` outcome.\n */\nexport async function can(client: AxiamClient, action: string, resourceId: string, scope?: string): Promise<boolean> {\n const decision = await checkAccess(client, { action, resourceId, scope });\n return decision.allowed;\n}\n\n/**\n * `POST /api/v1/authz/check/batch` (§1). Results are returned in the same\n * order as the input `checks` array (server-guaranteed ordering).\n */\nexport async function batchCheck(client: AxiamClient, checks: AccessCheck[]): Promise<AccessDecision[]> {\n const body: BatchCheckAccessBodyWire = { checks: checks.map(toWireBody) };\n try {\n const response = await client.session.axios.post<BatchCheckAccessResponseWire>(BATCH_CHECK_PATH, body);\n return response.data.results.map(fromWireDecision);\n } catch (err) {\n throw mapAuthzError(err);\n }\n}\n\nfunction mapAuthzError(err: unknown, action?: string, resourceId?: string): Error {\n if (err && typeof err === 'object' && 'response' in err) {\n const response = (err as { response?: { status?: number; data?: { message?: string } } }).response;\n if (response?.status !== undefined) {\n if (response.status === 403) {\n // Body (response.data) carries the server's own action/resource_id\n // for the denial (structured 403 body) — preferred by the mapper\n // over the call-args action/resourceId below when present.\n return mapHttpStatusToError(403, response.data?.message ?? 'authorization denied', {\n action,\n resourceId,\n body: response.data,\n });\n }\n return mapHttpStatusToError(response.status, response.data?.message ?? 'authz request failed', {\n action,\n resourceId,\n body: response.data,\n cause: err,\n });\n }\n }\n return new NetworkError('authz request failed', err);\n}\n","// AxiamClient — the isomorphic REST + auth core (D-01/D-25).\n//\n// Constructor validates the required tenant (§5), builds the SharedSession\n// (D-13), and installs the CSRF + reactive single-flight refresh\n// interceptors (D-05/D-07). REST method implementations (login/verifyMfa/\n// refresh/logout/checkAccess/can/batchCheck) are added by Task 2's\n// auth.ts/authz.ts, which extend this class's prototype.\n\nimport type { AxiamClientOptions } from '../core/index.js';\nimport { createSession, SharedSession } from './session.js';\nimport { installInterceptors } from './interceptors.js';\nimport * as authMethods from './auth.js';\nimport * as authzMethods from './authz.js';\nimport type { AccessCheck, AccessDecision, LoginResult } from './types.js';\n\n/**\n * The main entry point for the AXIAM TypeScript/JavaScript SDK — an\n * isomorphic (browser + Node) REST client for authentication and\n * authorization against an AXIAM server.\n *\n * @remarks\n * `AxiamClient` implements the SDK's cross-language behavioral contract\n * (see `CONTRACT.md` §1–§10): the canonical `login`/`verifyMfa`/`refresh`/\n * `logout`/`checkAccess`/`can`/`batchCheck` method vocabulary (§1), the\n * three-way `AuthError`/`AuthzError`/`NetworkError` taxonomy (§2), automatic\n * CSRF forwarding (§3), the required tenant context (§5), and a per-instance\n * single-flight refresh guard that de-duplicates concurrent token refreshes\n * (§9).\n *\n * A `tenantSlug` or `tenantId` is mandatory at construction — there is no\n * default tenant, and AXIAM is a multi-tenant system where every\n * authenticated call is scoped by the `X-Tenant-ID` header this client\n * injects on every request (§5). Session tokens never appear as a return\n * value or public property anywhere on this class: they arrive exclusively\n * via `httpOnly` cookies set by the server.\n *\n * @example\n * ```ts\n * const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });\n *\n * const result = await client.login('user@example.com', 'hunter2');\n * if (result.status === 'mfa_required') {\n * await client.verifyMfa(result.mfaToken, '123456');\n * }\n *\n * const decision = await client.checkAccess({ action: 'read', resourceId: 'document:42' });\n * if (!decision.allowed) {\n * throw new Error(decision.reason ?? 'access denied');\n * }\n * ```\n */\nexport class AxiamClient {\n /** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */\n readonly session: SharedSession;\n\n /**\n * @param options client configuration (§5/§6).\n * @param session optional pre-built session to adopt instead of the default\n * browser `SharedSession`. This is the injection point for the Node\n * persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie\n * jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`\n * from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it\n * is adopted here, so httpOnly login/refresh cookies persist. When omitted\n * the browser `SharedSession` is built by default — the Node modules are\n * NEVER statically imported from this browser-safe module, so a `/rest`\n * browser bundle keeps pulling zero Node dependencies (SC#1).\n */\n constructor(options: AxiamClientOptions, session?: SharedSession) {\n this.session = session ?? createSession(options);\n installInterceptors(this.session.axios, this.session);\n }\n\n /** `POST /api/v1/auth/login` (§1, D-18). */\n login(email: string, password: string): Promise<LoginResult> {\n return authMethods.login(this, email, password);\n }\n\n /** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */\n verifyMfa(mfaToken: string, code: string): Promise<LoginResult> {\n return authMethods.verifyMfa(this, mfaToken, code);\n }\n\n /** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */\n refresh(): Promise<void> {\n return authMethods.refresh(this);\n }\n\n /** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */\n logout(): Promise<void> {\n return authMethods.logout(this);\n }\n\n /** `POST /api/v1/authz/check` (§1, FND-04). */\n checkAccess(check: AccessCheck): Promise<AccessDecision> {\n return authzMethods.checkAccess(this, check);\n }\n\n /** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */\n can(action: string, resourceId: string, scope?: string): Promise<boolean> {\n return authzMethods.can(this, action, resourceId, scope);\n }\n\n /** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */\n batchCheck(checks: AccessCheck[]): Promise<AccessDecision[]> {\n return authzMethods.batchCheck(this, checks);\n }\n}\n","// tough-cookie jar + axios wiring (CONTRACT.md §4, D-09).\n//\n// AXIAM delivers access/refresh tokens exclusively via httpOnly Set-Cookie\n// (RESEARCH.md Area 3 — login/refresh response bodies carry NO token\n// fields). A Node persona therefore needs an explicit, per-client-instance\n// cookie jar so httpOnly cookies persist across requests, and the only way\n// to obtain the token values is to read them back out of that jar by name.\n//\n// Cookie names/paths mirror the server's CSRF/cookie middleware exactly\n// (crates/axiam-api-rest/src/middleware/csrf.rs) and the already-shipped\n// Rust SDK (the Rust SDK's src/token/manager.rs).\n\nimport { CookieJar } from 'tough-cookie';\nimport { 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\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","// PKCE + CSPRNG primitives for the OIDC relying-party flow\n// (CONTRACT.md §12.1 \"oidc_begin inputs and construction\", RFC 7636).\n//\n// Node's `node:crypto` covers everything needed — CSPRNG, SHA-256 and\n// base64url — so §12 adds NO new runtime dependency (plan §6 criterion 4).\n// This module is deliberately tiny, pure and synchronous: `oidc_begin`\n// performs no network I/O (§12.1), and every value here is derived locally.\n//\n// S256 ONLY. `plain` is not implemented, not reachable, and not configurable:\n// there is no code path in this SDK that can emit\n// `code_challenge_method=plain`.\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The only PKCE code-challenge method this SDK emits (RFC 7636 §4.2,\n * CONTRACT.md §12.1 rule 3). `plain` is intentionally absent.\n */\nexport const CODE_CHALLENGE_METHOD_S256 = 'S256';\n\n/**\n * Entropy, in bytes, of a generated `state` / `nonce` / `code_verifier`.\n *\n * §12.1 rule 1 requires at least 16 bytes (128 bits) and RECOMMENDS 32;\n * rule 2 RECOMMENDS 32 bytes for the verifier, which base64url-encodes to\n * exactly 43 characters — the minimum RFC 7636 §4.1 length, drawn only from\n * the unreserved set `[A-Za-z0-9-._~]`.\n */\nexport const CSPRNG_BYTES = 32;\n\n/**\n * Generate a URL-safe random token: `bytes` CSPRNG bytes, base64url-encoded\n * **without** padding (RFC 4648 §5 — Node's `'base64url'` encoding never\n * emits `=`).\n *\n * Used for both `state` and `nonce`, which §12.3 rule 2 classes as\n * **non-secret**: they are returned as plain strings, are echoed through the\n * browser's address bar by construction, and are safe to log.\n */\nexport function randomUrlSafeToken(bytes: number = CSPRNG_BYTES): string {\n return randomBytes(bytes).toString('base64url');\n}\n\n/**\n * Generate a fresh PKCE `code_verifier` (RFC 7636 §4.1): 32 CSPRNG bytes\n * base64url-encoded without padding, i.e. 43 characters from the unreserved\n * set.\n *\n * Returned already wrapped in {@link Sensitive} — §12.5 makes the verifier\n * secret **for its whole lifetime**, including while it sits in the\n * `AuthorizationRequest` handed back to the caller and in any\n * `OidcStateStore` entry.\n */\nexport function generateCodeVerifier(): Sensitive<string> {\n return new Sensitive(randomUrlSafeToken(CSPRNG_BYTES));\n}\n\n/**\n * Derive the PKCE `code_challenge` from a verifier:\n * `BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))`, unpadded\n * (RFC 7636 §4.2, CONTRACT.md §12.1 rule 3).\n *\n * The verifier is hashed as ASCII exactly as the RFC specifies. Verified\n * against the RFC 7636 Appendix B test vector in\n * `test/node/oidcPkce.test.ts`, which every SDK must carry (§12.1 rule 3).\n *\n * The challenge is a one-way digest and is **not** secret — it travels in the\n * authorization URL — so it is returned as a plain string.\n */\nexport function computeCodeChallenge(codeVerifier: string): string {\n return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');\n}\n","// OIDC / SSO relying-party helpers — CONTRACT.md §12 (contract 1.4).\n//\n// The nine canonical §12 operations, under the exact §12.2 TypeScript names:\n// oidcDiscover, oidcBegin, oidcExchange, oidcRefresh, loginClientCredentials,\n// introspect, revoke, ssoStart, ssoComplete.\n//\n// ── Why a separate class instead of methods on AxiamClient ─────────────────\n// `AxiamClient` lives in the browser-safe `src/rest/` core, and CI's SC#1\n// bundle-and-grep gate proves a `/rest` browser bundle pulls in zero Node-only\n// code. These helpers need `node:crypto` (CSPRNG + SHA-256 for PKCE) and\n// `jose` (ID-token verification), so hanging them off `AxiamClient` would drag\n// both into every browser bundle. They therefore live on a Node-only\n// `OidcClient` reached through the `axiam-sdk/node` subpath — the same shape\n// the repo already uses for the gRPC-only operations (`AuthzGrpcClient`,\n// `UserInfoGrpcClient`). §12 fixes the *method names*, not which object hosts\n// them, so this is conformant; an SDK without a browser-bundle constraint\n// (Rust, Python, Go, Java, Kotlin, C#, PHP) SHOULD put the nine methods\n// directly on its existing client, as the plan's T2–T8 items say.\n//\n// Everything else is reuse, not reimplementation (§12 forbids forking):\n// * transport + §2 error mapping + §3 CSRF + §4 cookie jar + §5 tenant\n// header + §6 TLS → the SharedSession/NodeSession axios instance;\n// * §9 single-flight refresh → session.refreshGuard;\n// * §12.4 signature verification → node/jwks.ts's verifier;\n// * §7/§12.5 redaction → core/sensitive.ts.\n\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport {\n AuthError,\n AxiamError,\n mapHttpStatusToError,\n NetworkError,\n sanitizeAxiosError,\n Sensitive,\n} from '../core/index.js';\nimport type { SharedSession } from '../rest/session.js';\nimport { createJwksVerifier, type JwksVerifier } from './jwks.js';\nimport type { IdTokenClaims } from './oidcIdToken.js';\nimport {\n CODE_CHALLENGE_METHOD_S256,\n computeCodeChallenge,\n generateCodeVerifier,\n randomUrlSafeToken,\n} from './oidcPkce.js';\nimport type {\n AuthorizationRequest,\n IntrospectParams,\n IntrospectionResponseWire,\n IntrospectionResult,\n LoginClientCredentialsParams,\n OidcBeginParams,\n OidcConfiguration,\n OidcExchangeParams,\n OidcRefreshParams,\n OidcStartResponseWire,\n OidcTokenSet,\n RevokeParams,\n SsoCompleteParams,\n SsoCompleteResult,\n SsoLoginSuccessResponseWire,\n SsoStartParams,\n SsoStartResult,\n TokenResponseWire,\n} from './oidcTypes.js';\n\n/** Path of the OIDC discovery document, relative to the client base URL. */\nexport const DISCOVERY_PATH = '/.well-known/openid-configuration';\n\n/** Path of the federation SSO step-1 endpoint. */\nexport const SSO_START_PATH = '/api/v1/auth/federation/oidc/start';\n\n/** Path of the federation SSO step-2 (callback) endpoint. */\nexport const SSO_CALLBACK_PATH = '/api/v1/auth/federation/oidc/callback';\n\n/**\n * Minimum — and default — discovery-cache TTL. CONTRACT.md §12.3 rule 6 sets\n * a floor of 5 minutes; a smaller configured value is raised to it.\n */\nexport const MIN_DISCOVERY_TTL_MS = 300_000;\n\n/** The `openid` scope, which every authorization request must carry (§12.1 rule 4). */\nconst OPENID_SCOPE = 'openid';\n\n/**\n * The eight query parameters `oidcBegin` owns (§12.1 rule 5). Caller-supplied\n * `extraParams` may add to the authorization request but never override these.\n */\nconst RESERVED_AUTHORIZE_PARAMS = new Set([\n 'response_type',\n 'client_id',\n 'redirect_uri',\n 'scope',\n 'state',\n 'nonce',\n 'code_challenge',\n 'code_challenge_method',\n]);\n\n/** Shape of a UUID, used to reject a slug where §12.3 rule 4 requires a UUID. */\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/** Configuration for {@link OidcClient}. */\nexport interface OidcClientOptions {\n /**\n * The relying party's OAuth2 `client_id`. Used on every grant and matched\n * against the ID token's `aud`/`azp` (§12.4 rule 4).\n */\n clientId: string;\n /**\n * The `client_secret` for a confidential client, held behind\n * {@link Sensitive} (§12.5). Omit for a public client — then it is never\n * added to a form body (§12.1 \"MUST omit rather than send empty/null\").\n *\n * `introspect` and `revoke` REQUIRE it: the server marks `client_secret`\n * non-nullable on both, so a public client cannot call them (§12.1 note 4).\n */\n clientSecret?: Sensitive<string> | string;\n /**\n * Default tenant UUID for the `tenant_id` query parameter the token,\n * introspection and revocation endpoints require. Falls back to the\n * session's configured `tenantId` when it was built in UUID form; a\n * slug-only client must pass `tenantId` per call (§12.3 rule 4).\n */\n tenantId?: string;\n /**\n * Discovery-cache TTL in milliseconds. Defaults to (and is floored at)\n * {@link MIN_DISCOVERY_TTL_MS} — §12.3 rule 6 forbids a TTL under 5 minutes.\n */\n discoveryTtlMs?: number;\n /**\n * Permitted ID-token clock skew in seconds. Defaults to 60 and is clamped to\n * 60 — §12.4 rule 5 forbids configuring it higher.\n */\n clockSkewSec?: number;\n}\n\n/** A cached discovery document together with its expiry. */\ninterface CachedDiscovery {\n document: OidcConfiguration;\n expiresAt: number;\n}\n\n/**\n * Origin-keyed discovery cache with single-flight fetching\n * (CONTRACT.md §12.3 rule 6).\n *\n * @remarks\n * The key is the **normalized scheme + host + port** of the base URL the\n * document was fetched from, so a document fetched from one origin can never\n * be served for another (cross-issuer cache poisoning). The cache is *not*\n * keyed on the tenant, and — because each {@link OidcClient} owns its own\n * instance — it is not shared across tenants either, nor process-global.\n *\n * Single-flight uses the same mechanism §9 prescribes for TypeScript: a shared\n * `Promise` held in a map for the duration of the fetch, cleared on settle, so\n * N concurrent callers produce exactly one HTTP request and all receive the\n * same document (or the same failure).\n *\n * @internal\n */\nclass DiscoveryCache {\n readonly #documents = new Map<string, CachedDiscovery>();\n readonly #inFlight = new Map<string, Promise<OidcConfiguration>>();\n readonly #ttlMs: number;\n\n constructor(ttlMs: number) {\n this.#ttlMs = Math.max(ttlMs, MIN_DISCOVERY_TTL_MS);\n }\n\n async get(originKey: string, fetcher: () => Promise<OidcConfiguration>): Promise<OidcConfiguration> {\n const cached = this.#documents.get(originKey);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.document;\n }\n\n const pending = this.#inFlight.get(originKey);\n if (pending) {\n return pending;\n }\n\n const fetch = fetcher()\n .then((document) => {\n this.#documents.set(originKey, { document, expiresAt: Date.now() + this.#ttlMs });\n return document;\n })\n .finally(() => {\n this.#inFlight.delete(originKey);\n });\n this.#inFlight.set(originKey, fetch);\n return fetch;\n }\n}\n\n/**\n * Normalize a URL to its cache key: lowercased scheme and host with the port\n * always explicit (§12.3 rule 6). `https://IAM.example.com/` and\n * `https://iam.example.com:443/x` therefore share one key, while\n * `http://iam.example.com` gets its own.\n */\nexport function normalizeOrigin(url: string): string {\n const parsed = new URL(url);\n const scheme = parsed.protocol.replace(/:$/, '').toLowerCase();\n const host = parsed.hostname.toLowerCase();\n const defaultPort = scheme === 'https' ? '443' : scheme === 'http' ? '80' : '';\n const port = parsed.port || defaultPort;\n return `${scheme}://${host}:${port}`;\n}\n\n/** Read a secret that the caller may have supplied wrapped or bare. */\nfunction exposeSecret(value: Sensitive<string> | string): string {\n return typeof value === 'string' ? value : value.expose();\n}\n\n/** Pull the HTTP status off an axios-shaped error, if any. */\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/** Pull the parsed response body off an axios-shaped error, if any. */\nfunction axiosBody(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/** Best-effort human-readable message from a parsed error body. */\nfunction bodyMessage(body: unknown, fallback: string): string {\n if (body && typeof body === 'object') {\n const record = body as Record<string, unknown>;\n if (typeof record.error_description === 'string') {\n return record.error_description;\n }\n if (typeof record.message === 'string') {\n return record.message;\n }\n }\n return fallback;\n}\n\n/**\n * Map any failure from a §12 wire call onto the §2 taxonomy, routing\n * everything through the single `mapHttpStatusToError` source of truth so the\n * endpoint-qualified `OAuthProtocolError` rows apply (§12.3 rule 3).\n *\n * An error that is *already* an `AxiamError` is passed through untouched: the\n * rest/interceptors.ts response interceptor may have mapped it first (it does\n * exactly that for a 401 on an `/oauth2/*` path), and re-mapping would discard\n * the richer error it built.\n */\nfunction mapOidcError(err: unknown, url: string, fallbackMessage: string): AxiamError {\n if (err instanceof AxiamError) {\n return err;\n }\n const status = axiosStatus(err);\n if (status !== undefined) {\n const body = axiosBody(err);\n return mapHttpStatusToError(status, bodyMessage(body, fallbackMessage), { url, body, cause: err });\n }\n return new NetworkError(fallbackMessage, sanitizeAxiosError(err));\n}\n\n/**\n * The OIDC / SSO relying-party client (CONTRACT.md §12).\n *\n * @remarks\n * Build one with {@link createOidcClient}, passing the same session your\n * `AxiamClient` uses so the cookie jar (§4), TLS configuration (§6), tenant\n * header (§5) and single-flight refresh guard (§9) are shared rather than\n * duplicated.\n *\n * **The caller owns the login state.** `oidcBegin` returns `state`, `nonce`\n * and `codeVerifier`; this class stores none of them (§12.3 rule 1). Keep them\n * in your own HTTP session — or use {@link MemoryOidcStateStore} together with\n * the `oidcLoginHandlers` glue from `axiam-sdk/middleware`, which does that\n * bookkeeping for you.\n *\n * @example\n * ```ts\n * const session = createNodeSession({ baseUrl, tenantId });\n * const oidc = createOidcClient(session, { clientId: 'my-app', clientSecret: secret });\n *\n * // 1. redirect the browser\n * const configuration = await oidc.oidcDiscover();\n * const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });\n * // …store request.state / request.nonce / request.codeVerifier in your session…\n * res.redirect(request.url);\n *\n * // 2. on the callback, having checked the returned `state` matches\n * const tokens = await oidc.oidcExchange({\n * code, codeVerifier: request.codeVerifier, nonce: request.nonce, redirectUri,\n * });\n * console.log(tokens.idClaims?.sub); // validated ID-token subject\n * ```\n */\nexport class OidcClient {\n readonly #session: SharedSession;\n readonly #options: OidcClientOptions;\n readonly #discoveryCache: DiscoveryCache;\n /** One verifier per `jwks_uri` — the same node/jwks.ts implementation the §10 middleware uses. */\n readonly #verifiers = new Map<string, JwksVerifier>();\n /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */\n #adoptedCredential: Sensitive<string> | null = null;\n #adoptionInterceptorInstalled = false;\n /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */\n #pendingRefresh: Promise<OidcTokenSet> | null = null;\n\n constructor(session: SharedSession, options: OidcClientOptions) {\n this.#session = session;\n this.#options = options;\n this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);\n }\n\n // -------------------------------------------------------------------------\n // 1. oidcDiscover\n // -------------------------------------------------------------------------\n\n /**\n * `GET /.well-known/openid-configuration` (§12.1) — fetch the OIDC discovery\n * document, cached per origin with a ≥5-minute TTL and single-flight\n * de-duplication of concurrent calls (§12.3 rule 6).\n *\n * The document's own `issuer` is authoritative for ID-token validation and\n * may legitimately differ from `baseUrl` behind a proxy, so a mismatch is\n * never treated as an error.\n */\n async oidcDiscover(): Promise<OidcConfiguration> {\n const originKey = normalizeOrigin(this.#session.baseUrl);\n return this.#discoveryCache.get(originKey, async () => {\n const response = await this.#get<OidcConfiguration>(DISCOVERY_PATH, 'oidc discovery request failed');\n return response.data;\n });\n }\n\n // -------------------------------------------------------------------------\n // 2. oidcBegin\n // -------------------------------------------------------------------------\n\n /**\n * Build an authorization request (§12.1) — **pure local computation, no\n * network I/O**.\n *\n * Generates a 32-byte CSPRNG `state` and `nonce` (base64url, unpadded) and a\n * fresh PKCE verifier/challenge pair using **S256 only** — `plain` is not\n * implemented anywhere in this SDK. The URL is built from the discovery\n * document's `authorization_endpoint` with exactly the eight parameters\n * §12.1 rule 5 mandates, plus any `extraParams` the caller adds.\n *\n * Nothing is stored: persist the returned `state`, `nonce` and\n * `codeVerifier` yourself (§12.3 rule 1).\n *\n * @throws Error when `extraParams` tries to override one of the eight\n * SDK-owned parameters — a programming error, caught at call time.\n */\n oidcBegin(params: OidcBeginParams): AuthorizationRequest {\n const state = randomUrlSafeToken();\n const nonce = randomUrlSafeToken();\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = computeCodeChallenge(codeVerifier.expose());\n\n const scope = normalizeScope(params.scope);\n const target = new URL(params.configuration.authorization_endpoint);\n const query = new URLSearchParams(target.search);\n\n for (const [key, value] of Object.entries(params.extraParams ?? {})) {\n if (RESERVED_AUTHORIZE_PARAMS.has(key)) {\n throw new Error(\n `oidcBegin: extraParams may not override the SDK-owned authorization parameter \"${key}\" (CONTRACT.md §12.1 rule 5).`,\n );\n }\n query.set(key, value);\n }\n\n query.set('response_type', 'code');\n query.set('client_id', this.#options.clientId);\n query.set('redirect_uri', params.redirectUri);\n query.set('scope', scope);\n query.set('state', state);\n query.set('nonce', nonce);\n query.set('code_challenge', codeChallenge);\n query.set('code_challenge_method', CODE_CHALLENGE_METHOD_S256);\n\n // URLSearchParams serializes a space as '+', which is legal in a query\n // string but not RFC 3986 percent-encoding; §12.1 rule 5 asks for the\n // latter, so spaces become %20. Every other character is already\n // percent-encoded correctly by URLSearchParams.\n target.search = query.toString().replace(/\\+/g, '%20');\n\n return { url: target.toString(), state, nonce, codeVerifier };\n }\n\n // -------------------------------------------------------------------------\n // 3. oidcExchange\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=authorization_code` (§12.1) —\n * exchange an authorization code for a token set, validating the returned\n * ID token in full before returning.\n *\n * The `nonce` argument is mandatory: this grant always requests the `openid`\n * scope, so §12.4 rule 6 always applies. If **any** §12.4 rule fails, the\n * whole token set is discarded and `AuthError` is raised with the matching\n * reason code — the access and refresh tokens from the same response are\n * never returned (§12.4 rule 7).\n */\n async oidcExchange(params: OidcExchangeParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'authorization_code');\n form.set('code', params.code);\n form.set('code_verifier', exposeSecret(params.codeVerifier));\n form.set('redirect_uri', params.redirectUri);\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n return this.#toTokenSet(wire, configuration, params.nonce);\n }\n\n // -------------------------------------------------------------------------\n // 4. oidcRefresh\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an\n * {@link OidcTokenSet}, under the §9 single-flight refresh guard.\n *\n * @remarks\n * This is a **distinct operation** from `AxiamClient.refresh()`, which drives\n * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The\n * two are never merged or aliased and neither falls back to the other\n * (§12.1). They do share the session's §9 guard, so at most one refresh of\n * either kind is ever in flight for a session.\n *\n * Concurrent `oidcRefresh` calls collapse into one HTTP request and all\n * receive the same token set — §9 rule 2's result sharing.\n *\n * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;\n * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce\n * in a refresh-issued ID token.\n */\n oidcRefresh(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const existing = this.#pendingRefresh;\n if (existing) {\n return existing;\n }\n const pending = this.#refreshUnderGuard(params);\n this.#pendingRefresh = pending;\n const clear = (): void => {\n if (this.#pendingRefresh === pending) {\n this.#pendingRefresh = null;\n }\n };\n pending.then(clear, clear);\n return pending;\n }\n\n // -------------------------------------------------------------------------\n // 5. loginClientCredentials\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=client_credentials` (§12.1) —\n * service-account machine-to-machine login.\n *\n * Requests no `openid` scope, so the response carries no `id_token`. Pass\n * `adoptAsCredential: true` to additionally use the returned access token as\n * this session's bearer credential for subsequent REST calls (§12.1, a MAY).\n *\n * @throws AuthError when no `clientSecret` is configured — this grant cannot\n * be performed by a public client.\n */\n async loginClientCredentials(params: LoginClientCredentialsParams = {}): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'client_credentials');\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('loginClientCredentials'));\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to this grant (§12.4 rule 6).\n const tokenSet = await this.#toTokenSet(wire, configuration, undefined);\n\n if (params.adoptAsCredential) {\n this.#adoptCredential(tokenSet.accessToken);\n }\n return tokenSet;\n }\n\n // -------------------------------------------------------------------------\n // 6. introspect\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/introspect` (RFC 7662, §12.1) — ask the server whether a\n * token is active and, if so, for its metadata.\n *\n * Requires confidential-client credentials (§12.1 note 4). A `401` here is a\n * *client-credential* failure surfaced as `OAuthProtocolError`; it never\n * enters the §9 refresh guard, because refreshing the user session cannot\n * fix a bad `client_secret` (§12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async introspect(params: IntrospectParams): Promise<IntrospectionResult> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('introspect'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.introspection_endpoint, params.tenantId);\n const response = await this.#postForm<IntrospectionResponseWire>(url, form, 'introspect request failed');\n const wire = response.data;\n return {\n active: wire.active,\n ...(wire.sub != null ? { sub: wire.sub } : {}),\n ...(wire.client_id != null ? { clientId: wire.client_id } : {}),\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.token_type != null ? { tokenType: wire.token_type } : {}),\n ...(wire.exp != null ? { exp: wire.exp } : {}),\n ...(wire.iat != null ? { iat: wire.iat } : {}),\n };\n }\n\n // -------------------------------------------------------------------------\n // 7. revoke\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/revoke` (RFC 7009, §12.1) — revoke an access or refresh\n * token. Returns nothing.\n *\n * Per RFC 7009 the server answers `200` for unknown, expired and\n * already-revoked tokens alike, so revocation is **idempotent**: any `200`\n * is success and no error is raised for a token the server has never seen.\n * Only a `401` (client authentication failed) is an error, surfaced as\n * `OAuthProtocolError` (§12.1 note 5, §12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async revoke(params: RevokeParams): Promise<void> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('revoke'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.revocation_endpoint, params.tenantId);\n await this.#postForm<void>(url, form, 'revoke request failed');\n }\n\n // -------------------------------------------------------------------------\n // 8. ssoStart\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/start` (§12.1) — step 1 of first-time\n * SSO against an **upstream** IdP. No JWT required.\n *\n * One tenant form (`tenantId` or `tenantSlug`) and one org form (`orgId` or\n * `orgSlug`) must be resolvable, from the arguments or from the session's\n * construction options (§5.1). Redirect the browser to the returned\n * `authorizeUrl` and round-trip `state` back into {@link ssoComplete}\n * unmodified — the server keeps the nonce to itself (§12.1 note 7).\n *\n * @throws AuthError client-side, without a wire call, when tenant or org\n * context cannot be resolved.\n */\n async ssoStart(params: SsoStartParams): Promise<SsoStartResult> {\n const tenantId = params.tenantId ?? this.#session.tenantId;\n const tenantSlug = params.tenantSlug ?? this.#session.tenantSlug;\n const orgId = params.orgId ?? this.#session.orgId;\n const orgSlug = params.orgSlug ?? this.#session.orgSlug;\n\n if (!tenantId && !tenantSlug) {\n throw new AuthError(\n 'ssoStart requires tenant context: pass tenantId or tenantSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n if (!orgId && !orgSlug) {\n throw new AuthError(\n 'ssoStart requires organization context: pass orgId or orgSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n\n const body: Record<string, string> = {\n federation_config_id: params.federationConfigId,\n redirect_uri: params.redirectUri,\n };\n // One tenant form AND one org form (§5.1). The UUID form wins when both\n // are present, mirroring how tenantSlug/tenantId already resolve.\n if (tenantId) {\n body.tenant_id = tenantId;\n } else if (tenantSlug) {\n body.tenant_slug = tenantSlug;\n }\n if (orgId) {\n body.org_id = orgId;\n } else if (orgSlug) {\n body.org_slug = orgSlug;\n }\n\n const response = await this.#postJson<OidcStartResponseWire>(\n SSO_START_PATH,\n body,\n 'ssoStart request failed',\n );\n return {\n authorizeUrl: response.data.authorize_url,\n state: response.data.state,\n expiresInSecs: response.data.expires_in_secs,\n };\n }\n\n // -------------------------------------------------------------------------\n // 9. ssoComplete\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/callback` (§12.1) — step 2 of upstream\n * SSO: consumes the single-use `state`, provisions or links the user, and\n * establishes the session.\n *\n * @remarks\n * The session arrives as **`Set-Cookie`**, not in the response body\n * (§12.1 note 6), so this call must go through the §4 cookie jar: use a\n * `NodeSession` (`createNodeSession`/`createNodeClient`) or the session is\n * silently lost. On success the session is marked authenticated and its\n * post-authentication hook runs, syncing the CSRF token and cached access\n * token out of the jar exactly as `login()` does.\n *\n * §12.4 does not apply here — no ID token ever reaches the SDK on the\n * federation path.\n */\n async ssoComplete(params: SsoCompleteParams): Promise<SsoCompleteResult> {\n const response = await this.#postJson<SsoLoginSuccessResponseWire>(\n SSO_CALLBACK_PATH,\n { state: params.state, code: params.code },\n 'ssoComplete request failed',\n );\n\n this.#session.authenticated = true;\n // Same post-login sync login()/verifyMfa() perform (CR-01/D-05): reads the\n // freshly-set axiam_csrf/axiam_access cookies out of the jar. A no-op on\n // the browser SharedSession, which has no jar.\n await this.#session.onAuthenticated?.();\n\n return {\n userId: response.data.user_id,\n sessionId: response.data.session_id,\n expiresIn: response.data.expires_in,\n redirectUri: response.data.redirect_uri,\n };\n }\n\n // -------------------------------------------------------------------------\n // internals\n // -------------------------------------------------------------------------\n\n /**\n * Run one `refresh_token` grant under the session's §9 single-flight guard.\n *\n * The guard's callback signature returns `void`, so the token set is\n * published through a local variable. When the callback does NOT run, the\n * guard was already busy with a *different* refresh (the §1 cookie-session\n * path, which cannot produce an `OidcTokenSet`); rather than return a stale\n * or wrong result we simply try again now that the other refresh has\n * settled. Bounded, so a pathologically busy guard fails loudly instead of\n * spinning.\n */\n async #refreshUnderGuard(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'refresh_token');\n form.set('refresh_token', exposeSecret(params.refreshToken));\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n for (let attempt = 0; attempt < 3; attempt += 1) {\n let refreshed: OidcTokenSet | undefined;\n await this.#session.refreshGuard(async () => {\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to a refresh-issued ID token.\n refreshed = await this.#toTokenSet(wire, configuration, undefined);\n });\n if (refreshed) {\n return refreshed;\n }\n }\n throw new AuthError(\n 'oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md §9); another refresh kept it busy.',\n );\n }\n\n /** POST a form body to the token endpoint from the discovery document. */\n async #postToken(\n configuration: OidcConfiguration,\n form: URLSearchParams,\n tenantId: string | undefined,\n ): Promise<TokenResponseWire> {\n const url = this.#endpointUrl(configuration.token_endpoint, tenantId);\n const response = await this.#postForm<TokenResponseWire>(url, form, 'token request failed');\n return response.data;\n }\n\n /**\n * Convert a `TokenResponse` into an {@link OidcTokenSet}, validating any\n * `id_token` first (§12.4). Validation precedes construction, so a failure\n * discards the whole set — the caller never sees the access or refresh token\n * from a response whose ID token was rejected (§12.4 rule 7).\n */\n async #toTokenSet(\n wire: TokenResponseWire,\n configuration: OidcConfiguration,\n nonce: string | undefined,\n ): Promise<OidcTokenSet> {\n let idClaims: IdTokenClaims | undefined;\n if (wire.id_token) {\n idClaims = await this.#verifierFor(configuration.jwks_uri).verifyIdToken(wire.id_token, {\n issuer: configuration.issuer,\n clientId: this.#options.clientId,\n ...(nonce !== undefined ? { nonce } : {}),\n ...(this.#options.clockSkewSec !== undefined ? { clockSkewSec: this.#options.clockSkewSec } : {}),\n });\n }\n\n return {\n accessToken: new Sensitive(wire.access_token),\n tokenType: wire.token_type,\n expiresIn: wire.expires_in,\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.refresh_token != null ? { refreshToken: new Sensitive(wire.refresh_token) } : {}),\n ...(wire.id_token != null ? { idToken: new Sensitive(wire.id_token) } : {}),\n ...(idClaims !== undefined ? { idClaims } : {}),\n };\n }\n\n /** Lazily build (and reuse) the JWKS verifier for a `jwks_uri` (§12.3 rule 6). */\n #verifierFor(jwksUri: string): JwksVerifier {\n const existing = this.#verifiers.get(jwksUri);\n if (existing) {\n return existing;\n }\n const verifier = createJwksVerifier(jwksUri);\n this.#verifiers.set(jwksUri, verifier);\n return verifier;\n }\n\n /**\n * Build the final endpoint URL: the discovery document's endpoint plus the\n * mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2). Existing\n * query parameters on the endpoint are preserved.\n */\n #endpointUrl(endpoint: string, tenantId: string | undefined): string {\n const url = new URL(endpoint);\n url.searchParams.set('tenant_id', this.#resolveTenantId(tenantId));\n return url.toString();\n }\n\n /**\n * Resolve the tenant UUID for the `tenant_id` query parameter (§12.3\n * rule 4): the explicit argument, else the client-level `tenantId`, else the\n * session's `tenantId` — and only ever a UUID. A slug-only client raises the\n * taxonomy error client-side, with no wire call, rather than sending a slug\n * where the server requires a UUID.\n */\n #resolveTenantId(explicit: string | undefined): string {\n const candidate = explicit ?? this.#options.tenantId ?? this.#session.tenantId;\n if (!candidate) {\n throw new AuthError(\n 'this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenantId explicitly, ' +\n 'or construct the client with the tenantId (UUID) form (CONTRACT.md §12.3 rule 4).',\n );\n }\n if (!UUID_RE.test(candidate)) {\n throw new AuthError(\n 'tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted ' +\n '(CONTRACT.md §12.3 rule 4).',\n );\n }\n return candidate;\n }\n\n /**\n * Add `client_secret` to a form body for a confidential client, and omit it\n * entirely for a public client — §12.1 forbids sending an empty/null value\n * for an absent optional field.\n */\n #appendClientSecret(form: URLSearchParams): void {\n const secret = this.#options.clientSecret;\n if (secret !== undefined) {\n form.set('client_secret', exposeSecret(secret));\n }\n }\n\n /** The `client_secret` for an operation that cannot be performed without one (§12.1 note 4). */\n #requireClientSecret(operation: string): string {\n const secret = this.#options.clientSecret;\n if (secret === undefined) {\n throw new AuthError(\n `${operation} requires confidential-client credentials: construct the OidcClient with a clientSecret ` +\n '(CONTRACT.md §12.1 note 4).',\n );\n }\n return exposeSecret(secret);\n }\n\n /**\n * Adopt an access token as this session's bearer credential (§12.1, opt-in).\n *\n * The token lives only inside the interceptor closure, behind\n * {@link Sensitive} — never on `axios.defaults`, a public property or the\n * cookie jar — so it stays unreachable through any public getter (§12.3\n * rule 2). It is deliberately NOT sent to `/oauth2/*`: those endpoints\n * authenticate the client through the form body (§12.1 note 3).\n */\n #adoptCredential(accessToken: Sensitive<string>): void {\n this.#adoptedCredential = accessToken;\n if (this.#adoptionInterceptorInstalled) {\n return;\n }\n this.#adoptionInterceptorInstalled = true;\n this.#session.axios.interceptors.request.use((config) => {\n const adopted = this.#adoptedCredential;\n const url = config.url ?? '';\n if (!adopted || this.#session.isForeignHost(url) || url.includes('/oauth2/')) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['Authorization'] = `Bearer ${adopted.expose()}`;\n return config;\n });\n }\n\n /** GET through the session transport, mapping failures onto the §2 taxonomy. */\n async #get<T>(url: string, fallbackMessage: string): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.get<T>(url);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a form-encoded body (§12.1 note 1) through the session transport. */\n async #postForm<T>(\n url: string,\n form: URLSearchParams,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n const config: AxiosRequestConfig = {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n };\n try {\n return await this.#session.axios.post<T>(url, form.toString(), config);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a JSON body (the federation endpoints) through the session transport. */\n async #postJson<T>(\n url: string,\n body: Record<string, string>,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.post<T>(url, body);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n}\n\n/**\n * Normalize the requested scope to a space-separated string that always\n * contains `openid` (§12.1 rule 4 — the helper adds it when the caller omits\n * it). Duplicate entries are collapsed so `\"openid openid profile\"` cannot be\n * produced.\n */\nfunction normalizeScope(scope: string | string[] | undefined): string {\n const requested = Array.isArray(scope) ? scope : (scope ?? '').split(' ');\n const values = requested.map((value) => value.trim()).filter(Boolean);\n if (!values.includes(OPENID_SCOPE)) {\n values.unshift(OPENID_SCOPE);\n }\n return [...new Set(values)].join(' ');\n}\n\n/**\n * Build an {@link OidcClient} on an existing session (CONTRACT.md §12).\n *\n * @param session the session the rest of the SDK already uses — normally a\n * `NodeSession` from `createNodeSession`, so the §4 cookie jar is in place\n * for `ssoComplete` (its session arrives as `Set-Cookie`).\n * @param options the relying party's `clientId`, optional `clientSecret`, and\n * optional tenant/TTL/skew overrides.\n *\n * @example\n * ```ts\n * import { createNodeSession, createOidcClient } from 'axiam-sdk/node';\n *\n * const session = createNodeSession({ baseUrl, tenantId, orgId });\n * const oidc = createOidcClient(session, {\n * clientId: process.env.AXIAM_CLIENT_ID!,\n * clientSecret: process.env.AXIAM_CLIENT_SECRET,\n * });\n * ```\n */\nexport function createOidcClient(session: SharedSession, options: OidcClientOptions): OidcClient {\n return new OidcClient(session, options);\n}\n","// OidcStateStore + MemoryOidcStateStore (CONTRACT.md §12.3 rule 1).\n//\n// STRICTLY OPTIONAL. The nine §12 operations never touch a store: `oidcBegin`\n// and `oidcExchange` are stateless by contract, and the caller normally keeps\n// `state`/`nonce`/`code_verifier` in its own HTTP session. This store exists\n// for the framework glue (`middleware/oidcLogin*`), where a login and its\n// callback are two separate HTTP requests with nothing but a `state` value\n// linking them.\n//\n// Semantics mirror the server's `federation_login_state` table exactly:\n// 10-minute TTL, single-use consume. That symmetry is deliberate — a reader\n// who knows the server side already knows this class.\n\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The tuple an {@link OidcStateStore} holds for one in-flight login.\n *\n * @remarks\n * `codeVerifier` stays {@link Sensitive} while stored (§12.5: the verifier is\n * secret for its whole lifetime, \"including … in any `OidcStateStore` entry\"),\n * so `JSON.stringify()`ing an entry — e.g. into a Redis-backed store — emits\n * `\"[SENSITIVE]\"` rather than the verifier. A store implementation that needs\n * to persist the value must call `expose()` explicitly and is then responsible\n * for protecting it at rest.\n */\nexport interface OidcStateEntry {\n /** The `state` value this entry is keyed by. Not a secret (§12.3 rule 2). */\n state: string;\n /** The `nonce` to check the ID token's `nonce` claim against. Not a secret (§12.3 rule 2). */\n nonce: string;\n /** The PKCE verifier for the matching authorization request (§12.5 secret). */\n codeVerifier: Sensitive<string>;\n /** The `redirect_uri` that was sent on the authorization request and must be replayed on exchange. */\n redirectUri: string;\n /** Optional application-owned data, e.g. the page the user was heading to before login. */\n returnTo?: string;\n}\n\n/**\n * Optional server-side store for in-flight `oidcBegin` state\n * (CONTRACT.md §12.3 rule 1).\n *\n * @remarks\n * Implement this to back the login/callback handlers with your own storage\n * (Redis, a database, an encrypted cookie). Two invariants are normative:\n *\n * 1. **Single-use.** {@link consume} MUST return the entry *and delete it\n * atomically*, so a replayed callback cannot reuse a `state`.\n * 2. **Expiry.** An entry older than 10 minutes MUST NOT be returned.\n */\nexport interface OidcStateStore {\n /** Persist an entry, keyed by its `state`, starting its TTL now. */\n save(entry: OidcStateEntry): Promise<void>;\n /**\n * Atomically fetch **and remove** the entry for `state`. Returns\n * `undefined` when the state is unknown, already consumed, or expired —\n * three cases a caller MUST treat identically (as a failed login), because\n * distinguishing them leaks whether a `state` ever existed.\n */\n consume(state: string): Promise<OidcStateEntry | undefined>;\n}\n\n/**\n * The contract-mandated TTL for stored login state: 10 minutes, matching the\n * server's `federation_login_state` row lifetime (D-22, §12.3 rule 1).\n */\nexport const OIDC_STATE_TTL_MS = 600_000;\n\n/**\n * In-memory reference implementation of {@link OidcStateStore} (§12.3 rule 1).\n *\n * @remarks\n * Per-instance (never process-global), single-use, 10-minute TTL. Expired\n * entries are dropped lazily on {@link consume} and swept opportunistically on\n * {@link save}, so no timer is held and the store needs no shutdown hook — a\n * long-lived `setInterval` would keep a Node process alive and would be a\n * surprising side effect for a library.\n *\n * Suitable for a single-process app and for tests. A multi-instance deployment\n * needs a shared store (Redis, database) — implement {@link OidcStateStore}\n * yourself for that; nothing in the SDK assumes this class.\n *\n * @example\n * ```ts\n * const store = new MemoryOidcStateStore();\n * await store.save({ state, nonce, codeVerifier, redirectUri });\n * const entry = await store.consume(state); // returns the entry\n * const again = await store.consume(state); // undefined — single-use\n * ```\n */\nexport class MemoryOidcStateStore implements OidcStateStore {\n readonly #entries = new Map<string, { entry: OidcStateEntry; expiresAt: number }>();\n readonly #ttlMs: number;\n\n /**\n * @param ttlMs entry lifetime in milliseconds. Defaults to\n * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a\n * shorter TTL is honoured (useful in tests), a longer one is reduced,\n * because §12.3 rule 1 fixes 10 minutes as the maximum.\n */\n constructor(ttlMs: number = OIDC_STATE_TTL_MS) {\n this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);\n }\n\n /** Number of unexpired entries currently held. Intended for tests and metrics. */\n get size(): number {\n this.#sweep();\n return this.#entries.size;\n }\n\n /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */\n async save(entry: OidcStateEntry): Promise<void> {\n this.#sweep();\n this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });\n }\n\n /**\n * Atomically return and delete the entry for `state`. Deletion happens\n * before the expiry check, so even an expired hit is removed rather than\n * left to accumulate — and a second call can never return the same entry\n * twice regardless of timing (JavaScript's single-threaded event loop makes\n * this get-then-delete pair genuinely atomic; a store backed by real\n * concurrency must use an atomic primitive such as Redis `GETDEL`).\n */\n async consume(state: string): Promise<OidcStateEntry | undefined> {\n const held = this.#entries.get(state);\n if (!held) {\n return undefined;\n }\n this.#entries.delete(state);\n if (held.expiresAt <= Date.now()) {\n return undefined;\n }\n return held.entry;\n }\n\n /** Drop every expired entry. Lazy housekeeping — no background timer. */\n #sweep(): void {\n const now = Date.now();\n for (const [state, held] of this.#entries) {\n if (held.expiresAt <= now) {\n this.#entries.delete(state);\n }\n }\n }\n}\n","// Webhook signature verification (CONTRACT.md §13, T-145).\n//\n// Verifies the server's Stripe-style signed-timestamp webhook scheme:\n// X-Axiam-Signature: t=<unix_seconds>,v1=<hex_lowercase_hmac>\n// v1 = HMAC-SHA256(secret_utf8_bytes, \"<t>.<raw_body>\")\n// Mirrors — never imports — the server's algorithm in\n// crates/axiam-api-rest/src/webhook.rs (`compute_signature_v2`), the same\n// \"reproduce, don't import\" discipline `amqp/hmac.ts` follows for the AMQP\n// HMAC contract (CONTRACT.md §8).\n//\n// The raw body is load-bearing: re-serializing parsed JSON before calling\n// this changes key order/whitespace and breaks the MAC. Common frameworks\n// discard the raw bytes by default — Express's `express.json()` does not\n// keep them — so callers MUST capture the untouched bytes off the wire\n// (Express `verify` callback, or `express.raw({ type: 'application/json' })`\n// on the webhook route) and pass those, not a re-stringified object. See the\n// README for the worked receiver example.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { Sensitive } from '../core/sensitive.js';\n\n/** Default freshness window, in seconds, for the `t=` timestamp (CONTRACT.md §13.2). */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;\n\n/**\n * Stable, machine-readable reason codes for a failed {@link verifyWebhook}\n * call. Never derived from — and never leaks — the expected/computed\n * signature or the secret (CONTRACT.md §13.3 rule 6).\n */\nexport type WebhookVerifyFailureReason =\n | 'malformed_header'\n | 'invalid_timestamp'\n | 'signature_mismatch'\n | 'stale_timestamp'\n | 'future_timestamp';\n\n/**\n * Thrown by {@link verifyWebhook} on any verification failure.\n *\n * @remarks\n * Carries a stable {@link reason} code for programmatic branching. `message`\n * is short and generic — it MUST NOT, and never does, include the expected\n * or computed signature, the secret, or the raw signature header value\n * (CONTRACT.md §13.3 rule 6). Callers should treat any `WebhookVerifyError`\n * uniformly (reject the delivery); the `reason` is for logging/metrics, not\n * for varying the trust decision.\n */\nexport class WebhookVerifyError extends Error {\n /** Stable reason code — see {@link WebhookVerifyFailureReason}. */\n readonly reason: WebhookVerifyFailureReason;\n\n constructor(reason: WebhookVerifyFailureReason, message: string) {\n super(message);\n this.name = 'WebhookVerifyError';\n this.reason = reason;\n Object.setPrototypeOf(this, WebhookVerifyError.prototype);\n }\n}\n\n/** The verified event returned by {@link verifyWebhook} on success. */\nexport interface VerifiedWebhookEvent {\n /** The delivery body's `event` field (event type), when the body is a JSON object carrying one. */\n event?: string;\n /**\n * The delivery body's `id` field. Use this — or the separate\n * `X-Axiam-Delivery` request header — as the at-least-once dedup key\n * (CONTRACT.md §13.3 rule 7): a retried delivery replays a validly-signed\n * request inside the freshness window, so receivers should keep a\n * short-lived seen-set keyed on it.\n */\n id?: string;\n /** The verified `t=` timestamp, epoch seconds. */\n timestamp: number;\n /** The JSON-parsed body, when it parses as JSON; `undefined` for a non-JSON payload (the signature is still verified either way). */\n body?: unknown;\n /** The exact raw body bytes that were verified. */\n rawBody: Buffer;\n}\n\n/** Options for {@link verifyWebhook}. */\nexport interface VerifyWebhookOptions {\n /**\n * Freshness window in seconds. Defaults to\n * {@link DEFAULT_WEBHOOK_TOLERANCE_SEC} (300s). Two-sided: a `t=` more\n * than `tolerance` seconds in the past OR more than `tolerance` seconds in\n * the future is rejected (CONTRACT.md §13.3 rule 5 — rejecting\n * future-dated timestamps too is required, not optional, as a guard\n * against clock-skew abuse).\n */\n tolerance?: number;\n /**\n * Injectable \"current time\" in epoch seconds, for deterministic tests.\n * Defaults to `Math.floor(Date.now() / 1000)`.\n */\n now?: number;\n}\n\nfunction fail(reason: WebhookVerifyFailureReason, message: string): never {\n throw new WebhookVerifyError(reason, message);\n}\n\nconst STRICT_HEX_PATTERN = /^[0-9a-fA-F]+$/;\nconst STRICT_INTEGER_PATTERN = /^-?\\d+$/;\n\n/**\n * Parse `t=<seconds>,v1=<hex>[,v1=<hex>,...]` into the timestamp string and\n * the set of candidate `v1` hex signatures. Unknown keys/schemes are ignored\n * for forward compatibility (CONTRACT.md §13.3 rule 3); a header carrying no\n * `t` or no `v1` at all is a hard failure — \"nothing to verify\" is never\n * treated as success.\n */\nfunction parseSignatureHeader(header: string): { t: string; v1: string[] } {\n let t: string | undefined;\n let tCount = 0;\n const v1: string[] = [];\n\n for (const rawPair of header.split(',')) {\n const pair = rawPair.trim();\n if (pair.length === 0) continue;\n const eq = pair.indexOf('=');\n if (eq === -1) continue;\n const key = pair.slice(0, eq).trim();\n const value = pair.slice(eq + 1).trim();\n if (key === 't') {\n t = value;\n tCount += 1;\n } else if (key === 'v1') {\n v1.push(value);\n }\n // Any other key is an unrecognized/future scheme — ignored.\n }\n\n if (tCount !== 1 || t === undefined) {\n fail('malformed_header', 'signature header must carry exactly one \"t\" field');\n }\n if (v1.length === 0) {\n fail('malformed_header', 'signature header carries no \"v1\" field');\n }\n return { t, v1 };\n}\n\n/**\n * Verify an AXIAM webhook delivery's `X-Axiam-Signature` header against the\n * raw request body (CONTRACT.md §13).\n *\n * Verification order (§13.3, normative): parse the header → parse `t` →\n * recompute `HMAC-SHA256(secret, \"<t>.<raw_body>\")` → constant-time compare\n * against every supplied `v1` candidate → two-sided freshness check → on\n * success, return the parsed event.\n *\n * @param secret The webhook's plaintext signing secret, wrapped per\n * CONTRACT.md §7.\n * @param signatureHeader The raw `X-Axiam-Signature` header value. (Do NOT\n * pass `X-Axiam-Timestamp` here — `t=` in this header is the value\n * actually covered by the MAC; if you also read the separate\n * `X-Axiam-Timestamp` header, require it to equal the parsed `t` yourself\n * before calling this function.)\n * @param body The **exact raw bytes** received off the wire (`Buffer`,\n * `Uint8Array`, or the identical raw string) — never a re-serialized\n * `JSON.stringify` of the parsed body, which changes key order/whitespace\n * and breaks the MAC.\n * @param options Freshness tolerance (default 300s) and a `now` injection\n * seam for tests.\n * @returns The verified event on success.\n * @throws {WebhookVerifyError} On any verification failure. Never throws a\n * generic `Error` whose message could leak the expected signature.\n */\nexport function verifyWebhook(\n secret: Sensitive<string>,\n signatureHeader: string,\n body: Buffer | Uint8Array | string,\n options: VerifyWebhookOptions = {},\n): VerifiedWebhookEvent {\n const { t, v1 } = parseSignatureHeader(signatureHeader);\n\n if (!STRICT_INTEGER_PATTERN.test(t)) {\n fail('invalid_timestamp', 'signature header \"t\" is not an integer');\n }\n const timestamp = Number(t);\n if (!Number.isFinite(timestamp)) {\n fail('invalid_timestamp', 'signature header \"t\" is out of range');\n }\n\n const rawBody: Buffer = typeof body === 'string' ? Buffer.from(body, 'utf8') : Buffer.from(body);\n const secretBytes = Buffer.from(secret.expose(), 'utf8');\n const signedPayload = Buffer.concat([Buffer.from(`${t}.`, 'utf8'), rawBody]);\n const expected = createHmac('sha256', secretBytes).update(signedPayload).digest();\n\n // Constant-time compare over DECODED bytes, never the hex strings\n // themselves, and never an early-return byte-by-byte loop. A length\n // mismatch is not itself secret information (it depends only on the\n // attacker-supplied candidate's own length), so short-circuiting past it\n // is safe and required — `timingSafeEqual` throws on unequal-length\n // buffers, so this guard is load-bearing, not just an optimization.\n let matched = false;\n for (const candidate of v1) {\n if (!STRICT_HEX_PATTERN.test(candidate) || candidate.length % 2 !== 0) {\n // Malformed hex fails closed: never decoded, never compared, never\n // treated as a match.\n continue;\n }\n const candidateBytes = Buffer.from(candidate, 'hex');\n if (candidateBytes.length !== expected.length) continue;\n if (timingSafeEqual(candidateBytes, expected)) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n fail('signature_mismatch', 'no v1 signature in the header matched the computed HMAC');\n }\n\n // Freshness — two-sided (§13.3 rule 5): a future-dated timestamp is\n // rejected exactly like a stale one.\n const nowSec = options.now ?? Math.floor(Date.now() / 1000);\n const tolerance = options.tolerance ?? DEFAULT_WEBHOOK_TOLERANCE_SEC;\n const age = nowSec - timestamp;\n if (age > tolerance) {\n fail('stale_timestamp', `timestamp is ${age}s old, outside the ${tolerance}s tolerance`);\n }\n if (-age > tolerance) {\n fail('future_timestamp', `timestamp is ${-age}s in the future, outside the ${tolerance}s tolerance`);\n }\n\n let parsedBody: unknown;\n let event: string | undefined;\n let id: string | undefined;\n try {\n parsedBody = JSON.parse(rawBody.toString('utf8'));\n if (parsedBody !== null && typeof parsedBody === 'object') {\n const obj = parsedBody as Record<string, unknown>;\n if (typeof obj.event === 'string') event = obj.event;\n if (typeof obj.id === 'string') id = obj.id;\n }\n } catch {\n // Signature verification does not depend on the body being JSON; a\n // non-JSON (but correctly signed) payload still verifies, it just\n // carries no `event`/`id` convenience fields.\n parsedBody = undefined;\n }\n\n return { event, id, timestamp, body: parsedBody, rawBody };\n}\n"]}